创建一个随机的唯一6位数字作为自定义帖子类型的自定义字段

时间:2015-09-21 作者:Snowball

我使用以下函数创建一个随机唯一的6位数,并将其保存在自定义的post type元字段中。

我不确定rewind_posts() 在while循环内。其目的是检查$random 任何现有自定义帖子中都已存在编号。如果它存在,它会生成一个新的随机数,并再次检查所有自定义帖子。

function create_random_unique_id() {

  // Create random 6 digit number
  $random   = substr( rand() * 900000 + 100000, 0, 6 );

  // Get all Custom Posts  
  $args = array( \'post_type\' => \'my_custom_post_type\', \'posts_per_page\' => -1 );
  $loop = new WP_Query( $args );

  // For each Custom Post, check if $random matches $cpt_id
  while ( $loop->have_posts() ) {

    $loop->the_post();
    $cpt_id = get_post_meta ( get_the_id(), \'id\', true );

    // If $random matches $subscriber_id assign a different random 6 digit number
    if ( $cpt_id == $random ) {
      $random = substr( rand() * 900000 + 100000, 0, 6 );
      rewind_posts();
    }

  }

  return $random;
}

1 个回复
最合适的回答,由SO网友:Pieter Goosen 整理而成

这是一个相当昂贵的操作,你在做什么,我也有错误的工作流程。你想做的是

获取所有meta_value来自特定meta_key 你需要。

然后,您可以将随机数与特定meta_key

这里有一个关于代码的非常基本的想法:(该代码归功于pwdtechnology.com的Chinmoy Paul。为了便于理解,对代码进行了注释)

以下内容涉及functions.php

/**    
 * Description: Getting all the values associated with a specific custom post meta key, across all posts
 * Author: Chinmoy Paul
 * Author URL: http://pwdtechnology.com
 *
 * @param string $key Post Meta Key.
 *
 * @param string $type Post Type. Default is post. You can pass custom post type here.
 *
 * @param string $status Post Status like Publish, draft, future etc. default is publish
 *
 * @return array
 */
function get_unique_post_meta_values( $key = \'\', $type = \'post\', $status = \'publish\' ) 
{
    global $wpdb;
    if( empty( $key ) )
        return;
    $res = $wpdb->get_col( 
        $wpdb->prepare( 
            "SELECT DISTINCT pm.meta_value 
            FROM {$wpdb->postmeta} pm
            LEFT JOIN {$wpdb->posts} p 
            ON p.ID = pm.post_id
            WHERE pm.meta_key = \'%s\'
            AND p.post_status = \'%s\'
            AND p.post_type = \'%s\'", 
            $key, 
            $status, 
            $type 
        ) 
    );
    return $res;
}
现在,从给定的meta_key 从特定post_typepost_status, 您可以尝试以下方法

// Get ids to exclude
$ids_to_exclude = get_unique_post_meta_values(
    \'id\', // This is our meta_key to get values from
    \'MY_POST_TYPE\', // This is the name of your custom post type
    \'POST_STATUS\' // Any other post status except publish as publish is default
);

/**
 * Generate a unique id
 * Thanks to Gautam3164 for the code
 * @see http://stackoverflow.com/a/17109530/1908141
 */
do {   
    // This is taken as is from your code in question
    $random   = substr( rand() * 900000 + 100000, 0, 6 );
} 
while( in_array( $random, $ids_to_exclude ) );
echo $random;
编辑您可以将所有内容整合到一个功能齐全的功能中。

/**    
 * Description: Get a random unique 6 number id for any given meta_key
 *
 * @param string $key Post Meta Key.
 *
 * @param string $type Post Type. Default is post. You can pass custom post type here.
 *
 * @param string $status Post Status like Publish, draft, future etc. default is publish
 *
 * @return array
 */
function get_unique_random_value( 
    $key = \'\', 
    $type = \'post\', 
    $status = \'publish\' 
) {
    global $wpdb;

    // Check if we have a meta_key before continuing, if not, return false
    if( empty( $key ) )
        return false;

    $res = $wpdb->get_col( 
        $wpdb->prepare( 
            "SELECT DISTINCT pm.meta_value 
            FROM {$wpdb->postmeta} pm
            LEFT JOIN {$wpdb->posts} p 
            ON p.ID = pm.post_id
            WHERE pm.meta_key = \'%s\'
            AND p.post_status = \'%s\'
            AND p.post_type = \'%s\'", 
            $key, 
            $status, 
            $type 
        ) 
    );
    // Check if we actually have an array of values, if not, return false
    if ( !$res )
        return false;

    /**
     * Generate a unique id
     * Thanks to Gautam3164 for the code
     * @see http://stackoverflow.com/a/17109530/1908141
     */
    do {   
        // This is taken as is from your code in question
        $random   = substr( rand() * 900000 + 100000, 0, 6 );
    } 
    while( in_array( $random, $res ) );
    return $random;
}
然后您可以按如下方式使用它

$random_id = get_unique_random_value (
    \'id\', // This is our meta_key to get values from
    \'MY_POST_TYPE\', // This is the name of your custom post type
    \'POST_STATUS\' // Any other post status except publish as publish is default
);
echo $random_id;

相关推荐

无法在模板函数.php中使用IS_HOME

我试图在标题中加载一个滑块,但只在主页上加载。如果有帮助的话,我正在使用Ultralight模板。我正在尝试(在template functions.php中)执行以下操作:<?php if ( is_page( \'home\' ) ) : ?> dynamic_sidebar( \'Homepage Widget\' ); <?php endif; ?> 但这行不通。现在,通过快速的google,我似乎需要将请