我正在尝试在索引中添加一个框。php在何处显示最新的3篇特色帖子。根据this tutorial, 我已将以下内容添加到functions.php:
add_theme_support( \'featured-content\', array(
\'filter\' => \'magdeleine_get_featured_posts\',
\'max_posts\' => 3,
) );
function magdeleine_get_featured_posts() {
return apply_filters( \'magdeleine_get_featured_posts\', array() );
}
function magdeleine_has_featured_posts( $minimum = 1 ) {
if ( is_paged() )
return false;
$minimum = absint( $minimum );
$featured_posts = apply_filters( \'magdeleine_get_featured_posts\', array() );
if ( ! is_array( $featured_posts ) )
return false;
if ( $minimum > count( $featured_posts ) )
return false;
return true;
}
然后我创建了一个
featured.php 模板如下:
<?php
// Get our Featured Content posts
$featured = magdeleine_get_featured_posts();
// If we have no posts, our work is done here
if ( empty( $featured ) )
return;
foreach ( $featured as $post ) : setup_postdata( $post );
?>
[...post code...]
<?php endforeach; ?>
<?php wp_reset_postdata(); ?>
最后,我调用了内部的模板
index.php 这样做:
<!-- Editor\'s picks -->
<?php if ( magdeleine_has_featured_posts( 1 ) ) : ?>
<?php get_template_part( \'featured\' ); ?>
<?php endif; ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
...
但是。。。如何避免在循环中重复相同的帖子?
最合适的回答,由SO网友:panos 整理而成
一种简单的方法是使用全局数组,在其中存储在特色查询中选择的帖子。您可以在函数中设置此数组。php或索引。php:$featured\\u post\\u array=array();然后在你的特写中。php文件首先在开头的某个地方调用全局数组:
global $featured_post_array;
在foreach循环中添加:
$featured_post_array[] = $post->ID;
索引中的最后一个。php在查询参数中使用post\\u not\\u in参数:
$query = new WP_Query( array( \'post_type\' => \'post\', \'post__not_in\' => $featured_post_array ) );
另一种方法是通过使用tag\\uu not\\u in或category\\uu not\\u in参数来忽略带有标记(或分类法)“featured”的帖子