0

I have a function to create a meta key for my custom post types. It works pretty well for them but now I want to use the same function for the attachment post type.

  • Normally it should work with the hook: add_action('add attachment', 'bZive_generate_AlphanumericID', 10, 3);

  • Because it's pretty much the same as (which works!):
    add_action('wp_insert_post', 'bZive_generate_AlphanumericID', 10, 3);

But for some reason no keys are getting generated (I checked my db in the postmeta table - also in the right blog...)

Here the full code

function bZive_generate_AlphanumericID( $post_id ) {

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

    if (in_array( $postType, $postTypes ) and empty( get_post_meta( $post_id, 'alphanumeric_id', true ) ) ) {


        $characters = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ'$§%&!";

        $charactersLength = strlen($characters);
        $randomString = '';
        for ($i = 0; $i < 13; $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('wp_insert_post', 'bZive_generate_AlphanumericID', 10, 3);
add_action('add attachment', 'bZive_generate_AlphanumericID', 10, 3);
2

You're missing an underscore:

add_action('add attachment', 'bZive_generate_AlphanumericID', 10, 3);

Needs to be:

add_action('add_attachment', 'bZive_generate_AlphanumericID', 10, 1);

I also changed the number of accepted arguments to 1, because add_attachment only has 1 and your callback function is only using 1 anyway.

  • Yea ok, thanks but after I posted this I saw it by my self - you were quicker :) – Game Unity Oct 17 '17 at 12:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.