remove child post from custom post type archive

I have a custom post type and a page like this for displaying the posts inside :

archive-(myCPT).php
I’ve created 2 posts, and one of them is the child.
How can I display just the parent page inside my archive-(myCPT).php

Read More

Here is a snippet from archive-(myCPT).php :

<?php 

        if( have_posts() ){ 
            // normal blog layout
                $x = 1;
                while ( have_posts() ){
                    the_post(); 
                    get_template_part( 'inc/post-format/content-debate');
                    // advertising between posts
                    if($ad_posts_mode != 'none'){
                        // take into account ad frequency
                        if (($x % $ad_posts_frequency) == 0){

                            switch ($ad_posts_mode) {
                                case 'image':
                                    echo '<div class="'.(($ad_posts_box) ? 'box' : '').' between_posts"><a target="_blank" href="'.of_get_option('ad_posts_image_link').'"><img src="'.of_get_option('ad_posts_image').'"></a></div>';
                                break;
                                case 'html':
                                    echo '<div class="'.(($ad_posts_box) ? 'box' : '').' between_posts">'.apply_filters('shortcode_filter',do_shortcode(of_get_option('ad_posts_code'))).'</div>';
                                break;
                            }
                        }
                    }
                    $x++;
                }
            }

Related posts

1 comment

  1. When a post (of ony type) is a child, its property post_parent is a number with the parent’s post ID. Posts without a parent have a value 0 instead. So you can test this value:

    if ( 0 === (int) $post->post_parent )
    {
        // show the post
    }     
    

    Another option is a filter on pre_get_posts (not tested, just an idea):

    add_action( 'pre_get_posts','hide_children' );
    
    function hide_children( $query ) 
    {
        remove_action( 'pre_get_posts', current_filter() );
    
        if ( is_admin() or ! $query->is_main_query() ) 
            return;
    
        if ( ! $query->is_post_type_archive( 'your_post_type_name' ) )
            return;
    
        // only top level posts
        $query->set( 'post_parent', 0 );
    }
    

Comments are closed.