我在WordPress中编写了一个自定义查询,循环浏览了4个不同的页面ID并提取了页面标题。我需要做的是检查正在查看的网页是否是其中一个ID,如果是,则不显示该特定标题。我知道我基本上需要检查当前页面ID和数组中的ID,因为它循环,但我将如何去做呢?
<?php
$service_args = array (
'post_type'=> 'page',
'post__in' => array(87,106,108,110), // The page ID's
'orderby' => 'ID',
'order' => 'ASC'
);
$servicesquery = new WP_Query( $service_args );
if ( $servicesquery->have_posts() ) {
while ( $servicesquery->have_posts() ) {
$servicesquery->the_post();
?>
<h4><?php echo the_title(); ?></h4>
<?php } wp_reset_postdata(); ?>
答案 0 :(得分:2)
您可以使用<?php get_the_ID(); ?>
获取当前页面/帖子ID。查找当前页面ID并将其从您正在准备的阵列中排除。
$posts_array = array(87,106,108,110);
$current_page_id = get_the_ID();
if ( ($key = array_search($current_page_id, $posts_array)) !== false) {
unset($posts_array[$key]);
}
$service_args = array (
'post_type'=> 'page',
'post__in' => $posts_array, // The page ID's array
'orderby' => 'ID',
'order' => 'ASC'
);
$servicesquery = new WP_Query( $service_args );
if ( $servicesquery->have_posts() ) {
while ( $servicesquery->have_posts() ) {
$servicesquery->the_post();
?>
<h4><?php echo the_title(); ?></h4>
<?php
}
wp_reset_postdata();
?>
答案 1 :(得分:0)
尝试在while循环之外声明页面ID,如下所示:
var thisPageId = get_the_ID();
while ( $servicesquery->have_posts() ) {
if ( $servicesquery->post->ID != thisPageId ) {
echo the_title();
}
}
答案 2 :(得分:0)
我使用array_diff
检查了ID https://wordpress.stackexchange.com/questions/108697/use-post-in-and-post-not-in-together
$this_post = $post->ID; // Get the current page ID
$exclude = array($this_post); // Exclude the current page ID from loop
$include = array(87,104,106,108,110); // ID's of pages to loop through
$service_args = array (
'post_type' => 'page',
'post__in' => array_diff($include, $exclude),
'orderby' => 'ID',
'order' => 'ASC'
);