Skip Navigation

[Resolved] Direct query child post by post title

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 10:00 – 13:00 -
- 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 14:00 – 18:00 -

Supporter timezone: Asia/Kolkata (GMT+05:30)

This topic contains 1 reply, has 1 voice.

Last updated by Minesh 2 weeks, 4 days ago.

Assisted by: Minesh.

Author
Posts
#2791381

Dear Sir/Madam,

I have below script to query all the child posts with $post_id = 1201

$child_posts = toolset_get_related_posts( $post_id, 'class-materials-grp', array( 'query_by_role' => 'parent', 'return' => 'post_object'));

foreach ($child_posts as $child_post) {
    
    $custom_title = types_render_field('post_title', array("id"=> "$child_post->ID"));
    printf("(Post ID: %s) %s<br/>", $child_post->ID, $child_post->post_title);
}

I can have the query result as below:

(Post ID: 1204) 01 IoT Smart Home Concept
(Post ID: 1206) Weather Observation - Equipment - Thermometer
(Post ID: 1207) Basic Practice - Smart home IoT Setup
(Post ID: 1208) Exercise 2 - Remote Control
(Post ID: 1209) Exercise 1 - Collect sensor data to MQTT platform
(Post ID: 1210) Schedule
(Post ID: 1211) Wifi Setting
(Post ID: 1212) MQTT Broker
(Post ID: 1213) IoT Remote Control Worksheet
(Post ID: 1214) Smart Home Demo

I want to have a query to directly find the child post by provide the parent_post id 1201 as below

$parent_post_id = 1201; 

$args = array(
    'post_type'      => 'class-materials-grp', 
    'post_parent'    => $parent_post_id,
    'title'          => 'MQTT Broker',
    'posts_per_page' => 1,
);

$query = new WP_Query($args);

if ($query->have_posts()) {
    while ($query->have_posts()) {
        $query->the_post();
        printf("Found Child Post: %s<br/>", get_the_title());
    }
} else {
    echo "No child post with title 'MQTT Broker' found.";
}

wp_reset_postdata();

but I got

No child post with title 'MQTT Broker' found.

What is the problem to my script, I do check the child post type is <b>class-materials-grp</b>

#2791382

Minesh
Supporter

Languages: English (English )

Timezone: Asia/Kolkata (GMT+05:30)

Hello. Thank you for contacting the Toolset support.

Well - "post_parent" is used when you have heiarchical post structure. "post_parent" is not the right thing to use.

Here is the post relationship API doc:
- https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/

And if you would like to fetch the child post using WP_Query, please check the following doc and check the New approach:
- https://toolset.com/documentation/customizing-sites-using-php/post-relationships-api/how-to-migrate-your-site-to-new-post-relationships/#new-approach