Exclude pages using an array

For the life of me I can’t see why this isn’t working.

I am trying to get this selection list to show all pages except for a couple that I want to exclude. I’m doing this by simply getting the page by title and then it’s ID from that.

Read More
<select>
<?php
// Get these pages by their title
$page1 = get_page_by_title('My First Page');
$page2 = get_page_by_title('My Second Page');

// The pages to be excluded
$excludeThese = array(
$page1->ID . ',' . 
$page2->ID
);

// Args for WP_Query   
$args = array(
'post__not_in' => $excludeThese, 
'post_type' => 'page', 
'posts_per_page' => -1, 
'order' => 'asc'
);

$pages_query = new WP_Query($args);
while ($pages_query->have_posts()) : $pages_query->the_post();?>
<option value="<?php the_permalink(); ?>"><?php the_title(); ?></option>
<?php endwhile; wp_reset_query(); ?>
</select>

If I echo $page1 and $page2, the ID’s of the pages are shown, so therefore the $excludeThese array should be using them (yes?).

If I hardcode the ID’s into the $excludeThese array instead like this…

$excludeThese = array(1, 2);

…then it all works fine. So it appears the $excludeThese array isn’t working properly.

I’d love to know what I’m doing wrong here.

Cheers y’all.

Related posts

Leave a Reply

3 comments

  1. // The pages to be excluded
    $excludeThese = array(
        $page1->ID,
        $page2->ID
    );
    

    You should use that instead of this:

    // The pages to be excluded
    $excludeThese = array(
        $page1->ID . ',' . 
        $page2->ID
    );
    
  2. // The pages to be excluded
    $excludeThese = array(
    $page1->ID . ',' .  // there is a concatenation of string here
    $page2->ID
    );
    

    Because of the string concatenation, your $excludeThese would bearray(‘1,2’);`

    It should be:

    // The pages to be excluded
    $excludeThese = array(
    $page1->ID , 
    $page2->ID
    );