使用数组排除页面

时间:2014-02-22 23:13:35

标签: php arrays wordpress

对于我的生活,我不明白为什么这不起作用。

我正在尝试使用此选择列表来显示除了要排除的一对页面之外的所有页面。我这样做只需要按标题获取页面,然后从中获取ID。

<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>

如果我回显$ page1和$ page2,会显示页面的ID,因此$ excludeThese数组应该使用它们(是吗?)。

如果我将ID硬编码到$ excludeThese数组中而不是像这样...

$excludeThese = array(1, 2);

...然后一切正常。所以$ excludeThese数组似乎无法正常工作。

我很想知道我在这里做错了什么。

欢呼你们。

3 个答案:

答案 0 :(得分:1)

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

您应该使用它而不是:

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

答案 1 :(得分:0)

您不需要将参数连接到array()

$excludeThese = array($page1->ID, $page2->ID);

答案 2 :(得分:0)

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

由于字符串连接,您的$excludeThese would be数组('1,2');`

应该是:

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