I'm trying to 'batch' update the value in my post_parent fields in my wp_posts table. I can do it from within phpmyadmin using the following SQL Query:

UPDATE wp_posts SET post_parent = '8' WHERE post_type = 'the_name_of_my_post-type_here';

but I can't get it to work from within wordpress.

Any thoughts?

1 Answer 1


The function you are looking for is wp_update_post().

You would want to have your posts which you want to update, then set up a loop to update each one individually.

// However you get your posts, ID's, etc.
$posts = get_posts( array( 'post_type' => 'post' ) );

for ( $posts as $post ) {
    wp_update_post( array( 'ID' => $post->ID, 'post_parent' => 8 ) );

For a generic SQL call, look at the $wpdb object, and it's prepare and query functions:

global $wpdb;

$query = $wpdb->prepare( 'UPDATE wp_posts SET post_parent = %d WHERE post_type = %s', 8, 'my-post-type' );

$wpdb->query( $query );

You could also look into $wpdb->update - it may suit your needs better in the future.

  • I'll give that a go Eric. Thanks for the quick reply. Will let you know how I get on.
    – Jonirish
    Commented Jul 27, 2015 at 13:12
  • If you want to run that exact query from within WordPress, just use the global $wpdb object's `query' and 'prepare' functions. Adding example in answer. Commented Jul 27, 2015 at 13:23
  • I did not try the loop method so I cannot comment on it. For the $wpdb object, your code as written didn't cause any errors but not did it perform any changes to the post_parent fields. In the end I tried a very similar piece of code that worked for me global $wpdb; $wpdb->query( $wpdb->prepare( "UPDATE $wpdb->posts SET post_parent = %d WHERE post_type = %s",8, 'my-post-type' ) ); . So, what's the best way to accept answer here etc? ... I don't use stackexchange that much but want to ensure any future visitors are helped.
    – Jonirish
    Commented Jul 27, 2015 at 15:49
  • Yes, I guess I forgot to add $wpdb->query( $query ); to the end of mine. :) Commented Jul 27, 2015 at 19:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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