Skip to content

Instantly share code, notes, and snippets.

@RadGH
Created August 5, 2019 22:42
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 RadGH/c2eb259729fdac81a4a0bd66ebeeea12 to your computer and use it in GitHub Desktop.
Save RadGH/c2eb259729fdac81a4a0bd66ebeeea12 to your computer and use it in GitHub Desktop.
Process/iterate through all posts in a post type
<?php
/*
This function will loop through all posts matching a filter, allowing you to make some edits to them with PHP.
To begin just visit your site ending with /?FojVDY83
Important: To avoid re-processing the same post infinitely, you need to make sure the meta_query will not match the same post after it has been processed. This is done below by checking if the meta key "status" exists or not.
*/
function rs_FojVDY83_process_posts() {
$args = array(
'post_type' => 'media-request',
'meta_query' => array(
array(
'key' => 'status',
'compare' => 'NOT EXISTS',
),
),
'posts_per_page' => 20,
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while( $query->have_posts() ): $query->the_post();
echo 'Updating post: <a href="' . esc_attr( get_edit_post_link( get_the_ID() ) ) . '" target="_blank">' . get_the_title() . '</a>';
echo "<br>";
// Change the post title if the "subject" field is set in ACF
$subject = get_field( 'subject', get_the_ID() );
if ( $subject ) {
$args = array(
'ID' => get_the_ID(),
'post_title' => $subject,
);
wp_update_post( $args );
}
// Update the custom status field, this also prevents the same post from being processed a second time.
update_field( 'status', 'Imported', get_the_ID() );
endwhile;
// Reload the page to continue processing while we have results
?>
<script type="text/javascript">setTimeout(function () {
window.location.href = window.location.href;
}, 500);</script>
<?php
}else{
// When we've processed everything, just say we're done
echo 'done';
}
exit;
}
if ( isset( $_REQUEST['FojVDY83'] ) ) {
add_action( 'init', 'rs_FojVDY83_process_posts' );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment