Programatically set "post_parent" using variable in "wp_update_post" argument

156 Views Asked by At

So let me start with in a nutshell, my application has the user submit a form which then creates a post and populates some custom fields (I am using fieldmanager). one of the fields on the form is a select that contains a list of the posts already published and they can select one to be the parent page of the new submission (post)

In the post, I am attempting to set the "post_parent" by running "wp_update_post". What I will do is check if the custom field containing the intended parent post title is there. Then run a query to get its ID then update the post (code below)

$emergency_id = get_the_ID();
$parent = get_post_meta($emergency_id, 'Parent Call', true);

if ($parent) {

        $parent_id = array(
            'post_type' => 'hood_to_coast_calls',
            'title' => $parent
        );

        $parent_id_query = new WP_Query($parent_id);

        if ($parent_id_query->have_posts()) {
            while ($parent_id_query->have_posts()) {
                $parent_id_query->the_post();

                $parent_hood_id = the_ID();
            }
        }

        echo $parent_hood_id;

        $update_call = array(
            'ID' => $emergency_id,
            'post_type'      => 'hood_to_coast_calls',
            'post_parent' => $parent_hood_id
        );
        wp_update_post($update_call);
    }

My issue is that using the variable that stores the intended parent post id in the query arguments doesn't work. When I echo the variable it contains the correct ID, but using it in the query args doesn't update the post with the parent. If I switch out the variable with the actual int value ID of the intended parent_post, then it works as expected.

Does anyone know if there is something I am doing wrong here? Or is there a better approach to this?

1

There are 1 best solutions below

1
On

You have a small bug in your code.

The bug is you are trying to assign the ID to a variable like $parent_hood_id = the_ID();

$parent_hood_id is always null since the method the_ID() doesn't return anything, it just echos the loop's current post ID. A qucik fix to that would be $parent_hood_id = get_the_ID(); instead.

So what you are confusing is that the correct ID is being printed by the call to $parent_hood_id = the_ID(); and not from your echo $parent_hood_id; call.

Additonally i would also limit the Query with posts_per_page to 1 and also wp_reset_postdata() after your Query's loop.

Hope that helps!