Why wont this wp_query exclude certain pages?

I’m using the following wp_query snippet to show all pages on a single page while being able to select individual pages to exclude.

// This pulls a list of page ID's from a theme options multicheck field
$pages = of_get_option('exclude_pages' );
// This shows only those ID's that have been checked
$implode_pages = implode(', ',array_keys($pages, 1));
$args = array(
    'post_type' => 'page',
    'posts_per_page' => -1,
    'orderby' => 'menu_order',
    'order' => 'asc',
    'post__not_in' => array($implode_pages)
);
$page_query = new WP_Query($args);
while ($page_query->have_posts()) : $page_query->the_post();

If I simply echo the $implode_pages bit in a page it displays like this 12, 31 where 12 and 31 are page ID’s

Read More

But when I try and include it in the post__not_in argument as shown above it only excludes the first ID even though if I hard code 12, 31 in there it excludes both…

Am I doing something wrong?

Related posts

3 comments

  1. A hardcoded array( 12, 31 ) is not the same as array($implode_pages).

    The earlier is equivalent to
    array( 0 => 12, 1 => 31 )

    The latter is equivalent to
    array( 0 => '12, 31' )

    $implode_pages = implode(', ',array_keys($pages, 1)); makes $implode_pages a string – which is not what you want.
    Not only that, it’s an entirely redundant step.

    'post__not_in' => array_keys($pages, 1)
    

    should do…

  2. post__not_in takes an array:

    post__not_in (array) – use post ids. Specify post NOT to retrieve.

    Based on your code, of_get_option gives you an array with the keys set to the post IDs, so what you’d need is:

    $pages = of_get_option('exclude_pages' );
    // This shows only those ID's that have been checked
    $implode_pages = array_keys($pages, 1);
    $args = array(
        'post_type' => 'page',
        'posts_per_page' => -1,
        'orderby' => 'menu_order',
        'order' => 'asc',
        'post__not_in' => $implode_pages,
    );
    $page_query = new WP_Query($args);
    
  3. From the Codex page for WP_Query:

    post__not_in (array) – use post ids. Specify post NOT to retrieve.

    So instead of passing in $implode_pages, just use the $pages array that you get from of_get_option( 'exclude_pages' ).

    Edited to add Whoops, I should have double-checked your question before I posted — I misread array( $implode_pages ) as simply $implode_pages.

Comments are closed.