1

I'm experiencing some interesting results using post_parent along with post_type (local, WP 5.8):

I have a custom post type project (with 'hierarchical' => true) where I'm grabbing all child posts of a parent on a single view using WP_Query.

When setting post_type to project while setting post_parent I get the same results as if I had not set a post_parent at all: that is, I get all top-level posts with a custom post type of project.

If I set the post_type to any then I get the correct child posts. I have already checked to make sure that the $post->ID for the parent is correct (and not 0) and that the posts are all of the same custom post type. I've also double checked the DB for weirdness and verified the parent-child relationships.

To make this stranger, this is on my local; the previous code (setting post_parent AND post_type) works fine on a live/production site (though that's on an earlier WP version).

This is the query:

$args = array(
    'post_type'   => 'project',
    'post_status' => 'publish',
    'post_parent' => $post->ID,
    'posts_per_page' => -1,
    'orderby' => 'menu_order title',
    'order' => 'ASC'
);

$projects = new WP_Query( $args );
if( $projects->have_posts() ) :
    while( $projects->have_posts() ) :
        $projects->the_post();

As described, if I change to 'post_type' => 'any', then I get the correct child post(s).

What am I missing? Is my data corrupted (though I can't see any evidence of this)...

10
  • Are the database engine or SQL versions different between live/local? Aug 27 at 18:29
  • Are the posts all in the same order?
    – Howard E
    Aug 27 at 19:16
  • @montrealist local is MySQL 8.0.16, live is 5.7.12
    – rsigg
    Aug 27 at 19:32
  • 1
    If the posts are already in the order then wouldn't the results be the same? Also, where is $post->ID coming from in this case? Have you tried dumping your $args or $projects->request to make sure you're getting expected queries?
    – Howard E
    Aug 27 at 19:40
  • 1
    Let us continue this discussion in chat.
    – rsigg
    Aug 27 at 20:37
0

It turns out I have an errant pre_get_posts function:

function fgw_parents_only( $query ) {
    if ( ! is_admin() && $query->is_post_type_archive( 'project' ) ) {
        $query->set( 'post_parent', 0 );
        $query->set( 'posts_per_page', -1);
    }
}
add_action( 'pre_get_posts', 'fgw_parents_only' );

Not exactly sure why is_post_type_archive caused this to show up on a single-project.php template, but I managed to solve this by changing the test to:

if ( ! is_admin() && $query->is_post_type_archive( 'project' ) && ! is_single() ) {

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.