Skip to content

Instantly share code, notes, and snippets.

@AustinGil
Last active August 29, 2017 17:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save AustinGil/296db77169348e0752c2bb8d824dc342 to your computer and use it in GitHub Desktop.
Save AustinGil/296db77169348e0752c2bb8d824dc342 to your computer and use it in GitHub Desktop.
Loop through posts that are missing meta data, and add some default value
<?php
/**
* Template Name: Full Width
*
* Gets all posts that are missing default meta value, and gives them a default meta value.
* Add this file to your theme then add a page with this template.
*
* IMPORTANT:
* Visit that page and keep refreshing until you see no more posts left.
* Each page load adds the new post meta, so the loop count drops by the posts_per_page count each time.
* Therefore regular pagination does not work as expected.
*/
while ( have_posts() ) : the_post();
// Variables
$post_type = array('resource');
$posts_per_page = 500; // A very large number could crash. -1 to get all posts
$meta_key = 'views';
$default_meta_value = '';
// Setup the query for posts where the meta_key doesn't exist
$args = array(
'post_type' => $post_type,
'posts_per_page' => $posts_per_page,
'paged' => $paged,
'meta_key' => $meta_key,
'meta_compare' => 'NOT EXISTS'
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
echo '<h4>' . count($query->posts) . ' posts out of ' . $query->found_posts . ' have been updated.</h4>';
echo '<p>To update the next batch, just refresh the page.</p>';
// Update the meta key for all posts with the default initial value
while ( $query->have_posts() ) : $query->the_post();
$post_id = get_the_ID();
update_post_meta( $post_id, $meta_key, $default_meta_value );
// Just so we can see them
echo '<p>' . get_the_title() . ' | ' . $meta_key . ' = ' . get_post_meta( $post_id, $meta_key, true ). '</p>';
endwhile;
// Just in case
wp_reset_postdata();
else :
echo '<p>Yay! No more missing data</p>';
endif;
endwhile; ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment