admin管理员组

文章数量:1122846

I would like to display a list of all children pages of parent page ID #2. I exclude one of child page which is ID #4 :

<?php $args = array( 'post_type' => 'page', 'posts_per_page' => -1, 'post_parent' => '2', 'post__not_in' => array(4), 'order' => 'ASC', 'orderby' => 'menu_order' ); $childrens = new WP_Query( $args ); if ( $childrens->have_posts() ) : ?>
<?php while ( $childrens->have_posts() ) : $childrens->the_post(); ?>
<p><?php the_title(); ?></p>
<?php endwhile; ?>
<?php endif; wp_reset_query(); ?>

But I also would like to exclude the current page where I am.

Do you know how I could modify my code ? Probably include this current page in the 'post__not_in', but I don't know how (?)

Thanks in advance for your help ! :)

I would like to display a list of all children pages of parent page ID #2. I exclude one of child page which is ID #4 :

<?php $args = array( 'post_type' => 'page', 'posts_per_page' => -1, 'post_parent' => '2', 'post__not_in' => array(4), 'order' => 'ASC', 'orderby' => 'menu_order' ); $childrens = new WP_Query( $args ); if ( $childrens->have_posts() ) : ?>
<?php while ( $childrens->have_posts() ) : $childrens->the_post(); ?>
<p><?php the_title(); ?></p>
<?php endwhile; ?>
<?php endif; wp_reset_query(); ?>

But I also would like to exclude the current page where I am.

Do you know how I could modify my code ? Probably include this current page in the 'post__not_in', but I don't know how (?)

Thanks in advance for your help ! :)

Share Improve this question edited Apr 16, 2024 at 8:24 fuxia 107k38 gold badges255 silver badges459 bronze badges asked Apr 15, 2024 at 17:39 HelloooHellooo 31 bronze badge
Add a comment  | 

1 Answer 1

Reset to default 0

You can use get_the_ID() to retrieve the current page's ID.

$current_page_id = get_the_ID();

$args = array(
    'post_type' => 'page',
    'posts_per_page' => -1,
    'post_parent' => '2',
    'post__not_in' => array( 4, $current_page_id ),
    'order' => 'ASC',
    'orderby' => 'menu_order'
); 

This kind of ID exclusion may cause query performance issues, especially when you have a great number of posts. So another option is to do a simple if check within the posts loop and skip certain post(s).

if ( $children->have_posts() ) {
    $current_page_id = get_the_ID(); // ID of the page you're on
    
    while ( $children->have_posts() ) {
        $children->the_post();
        // compare loop iteration child page ID to the page ID
        if ( get_the_ID() === $current_page_id ) {
            continue;
        }
        ?>
        <p><?php the_title(); ?></p>
        <?php
    }
}

本文标签: wp queryExclude page ID AND current page from wpquery of a Parent page