web-dev-qa-db-ja.com

Wp_insert_postに固有の英数字IDを作成する

パーマリンクとマルチサイトインストール間の事後関係のために、ランダムな(そしてユニークな)英数字IDが必要です。私の考えは、このIDをwp_insert_postに生成し、それをカスタムフィールド値として_alphanumeric_idに保存することです。

私はすでに自分自身でこれを理解しようとしました、しかし私は500エラーを得ました:

function generateAlphanumericID( $length = 11, $post_id ) {

    $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ-_~'!,";
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[Rand(0, $charactersLength - 1)];
    }
    /**
     * Now check here if the string is in the database
     * I am using two custom functions is_AlphanumericID_available() and save_AlphanumericID_into_db()
     */
    if( is_AlphanumericID_available( $randomString ) ){
        save_AlphanumericID_into_db( $randomString, $post_id );
        return $randomString;
    } else {
        return generateAlphanumericID();
    }
}
add_action('wp_insert_post','generateAlphanumericID'10, 3);



// function to grab all possible meta values of the chosen meta key.
function get_meta_values( $meta_key,  $post_type = 'post' ) {

    $posts = get_posts(
        array(
            'post_type' => $post_type,
            'meta_key' => $meta_key,
            'posts_per_page' => -1,
        )
    );

    $meta_values = array();
    foreach( $posts as $post ) {
        $meta_values[] = get_post_meta( $post->ID, $meta_key, true );
    }

    return $meta_values;

}

// function to check if the randomString is available
function is_AlphanumericID_available( $randomString ) {

    $arrayString = get_meta_values( '_alphanumeric_id', 'article' );


    if (in_array( $randomString, $arrayString)) {
      return false; // "Match found"
    }  else {
      return true;  // "Match not found"
    }


}



// function to save the randomString as custom field value
function save_AlphanumericID_into_db( $randomString, $post_id ) {

    add_post_meta($post_id, '_alphanumeric_id', $randomString);
}
add_action('wp_insert_post', 'save_AlphanumericID_into_db', 10, 3);

更新05.Okt.2017:

function save_AlphanumericID_into_db( $post_id ) {

    $randomString = 'Y-7Gd789ovW';


    // check if the randomString is available
    $posts = get_posts( array( 
        'post_type' => 'article',
        'meta_key' => '_alphanumeric_id', 
        'posts_per_page' => -1,
        )
    );  

    $meta_values = array();
    foreach( $posts as $post ) {
        $meta_values[] = get_post_meta( $post->ID, $meta_key, true );
    }

    if (in_array( $randomString, $arrayString)) {
        // "Match found"
         add_post_meta($post_id, '_alphanumeric_id', 'error');

    }  else {
        // "Match not found"
        add_post_meta($post_id, '_alphanumeric_id', $randomString);
    }





}
add_action('wp_insert_post', 'save_AlphanumericID_into_db', 10, 3);

これはエラーなしで(単一の関数として)機能しますが、dbチェックは機能しません - キーが既に存在する場合は 'error'を追加しません。 - 何か考え

1
Game Unity

実用版はこちら

// function to save the randomString as custom field value
function generate_AlphanumericID( $post_id ) {

    $postTypes = array('profile', 'article');
    $postType = get_post_type( $post_id );

    if (in_array( $postType, $postTypes ) ) {


        $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ-_~'!,";

        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < 11; $i++) {
            $randomString .= $characters[Rand(0, $charactersLength - 1)];
        }

         /**
         * Now check here if the string is in the database
         */
        $args = array(
        'post_type'     =>  array(
                $postTypes 
            ),
        'meta_query'    =>  array(
            array(
                'meta_key'  =>  '_alphanumeric_id'
            )
        )
        );
        $posts = new WP_Query( $args );


        $meta_values = '';
        if( $posts->have_posts() ) {
          while( $posts->have_posts() ) {
            $posts->the_post();

            $meta_values[] = get_post_meta( get_the_ID(), '_alphanumeric_id', true );
          }
        } 
        wp_reset_postdata();


        if (in_array( $randomString, $meta_values )) {
            // "Match found"
            return generate_AlphanumericID;

        }  else {
            // "Match not found"
            add_post_meta($post_id, '_alphanumeric_id', $randomString);
            return $randomString;
        }

    }

}
add_action('draft_to_publish', 'generate_AlphanumericID', 10, 3);

注意:

このキーをパーマリンクタグとして使うには、これをお勧めします https://github.com/athlan/wordpress-custom-fields-permalink-plugin

1
Game Unity