0

I have a function where I am counting letters in a title and adding that _product_meta_title key, everything is working fine when I am adding a new product but I have 500 products that don't have this key. So I need to run my function on all posts once.

function save_post_title_length_meta( $post_id, $post, $update ) {

/*
 * In production code, $slug should be set only once in the plugin,
 * preferably as a class property, rather than in each function that needs it.
 */
$post_type = get_post_type($post_id);

$title = get_post_field( 'post_name', $post_id );

$title_length = strlen( $title );


// If this isn't a 'product' post, don't update it.
if ( "product" != $post_type ) return;

// - Update the post's metadata.

if ( $title ) {
    update_post_meta( $post_id, '_product_title_length', $title_length );
}}

I am using this action to run my function

add_action( 'save_post', 'save_post_title_length_meta', 10, 3 );

How to run it so it will affect all my existing post on wp load, init? Any recommendations on where to start?

Thanks

  • How many "product" posts do you need to edit?? – ChristopherJones Jun 13 at 18:47
1

Rather than hooking into init or wp_load, here is a snippet you can drop into functions.php or on a theme file. I put it behind a $_GET so that you can only hit it once and when you are ready. Something like https://domain.com/page/?update_post_meta

// Hide it from the public
if(isset($_GET['update_post_meta'])){

  // Let's query all of the product post_type.
  $product_args = array(
    'post_type' => 'product',
    'posts_per_page' => -1
  );
  $product_query = new WP_Query($product_args);

  while( $product_query->have_posts()): $product_query->the_post();

    $title_length = strlen($post->post_name);

    // - Update the post's metadata.
    if ( $post->post_name ) {
      update_post_meta( $post->ID, '_product_title_length', $title_length );
    }

  endwhile; 

}

If you want to run this on specific posts you have not edited already, you can update the $product_args array to have a date range in it.

Hope this helps!!

  • perfect! thanks – Wojciech Jun 14 at 11:28

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.