0

How can I update post_parent by ids?

I tried:

add_action('init','updating_parent');

function updating_parent(){

    $args = array(
       'post__in' => array(208,51) 
    );

    $my_posts = get_posts( $args );

    foreach ( $my_posts as $my_post ):

        $my_post['post_parent'] = 12;

        wp_update_post( $my_post );

    endforeach;
}

But this is not working. But even it wouldn't be what I need. Since I have data like:

ID => post_parent
208 => 12
51 => 19
and so on...

So I need an array at post_parent as well.

  • If you want achieve the same. Use SQL: INSERT INTO wp_posts (id,post_parent) VALUES (208,12),(51,19) ON DUPLICATE KEY UPDATE post_parent=VALUES(post_parent); – Emanuel Schiendorfer Feb 3 '17 at 0:15
0

A post can only ever have one parent post.

I'm certain you can still accomplish what you want using post meta, though. If you give us a better explanation of what you're trying to do we might be able to help.

For example,

function updating_parent() {
    // your code to get posts

    foreach ( $my_posts as $post ) {
        update_post_meta( $post->ID, 'related_posts', array( 12, 23, 42 ) );
    }
}

Then you can access this data using get_post_meta:

$related_posts = get_post_meta( get_the_ID(), 'related_posts', true );
  • Sorry for not beeing clear. I just wanted one parent_post. But I understood now, that it's much easier to achieve with SQL: INSERT INTO wp_posts (id,post_parent) VALUES (208,12),(51,19) ON DUPLICATE KEY UPDATE post_parent=VALUES(post_parent); – Emanuel Schiendorfer Feb 3 '17 at 0:14
  • Ah yeah, I interpreted it as needed multiple post parents tied to a single post. If you're just trying to batch-update a number of posts' parents I don't see anything wrong with using raw SQL. – The Maniac Feb 3 '17 at 0:15

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.