我正在开发一个主题,在主循环帖子之前有一个特色帖子部分。凉爽清新,对吧?:)所有带有特色图片的贴子都必须显示在该部分,并从主循环中排除。简单的豌豆。在做研究时,我偶然发现了一个pretty old article 在这件事上我觉得很有用。它主张不要使用query_posts
, 这是我以前做过的,并提供了一种更优雅的方法:
/**
* Filter the home page posts, and remove any featured post ID\'s from it. Hooked
* onto the \'pre_get_posts\' action, this changes the parameters of the query
* before it gets any posts.
*
* @global array $featured_post_id
* @param WP_Query $query
* @return WP_Query Possibly modified WP_query
*/
function itheme2_home_posts( $query = false ) {
// Bail if not home, not a query, not main query, or no featured posts
if ( ! is_home() || ! is_a( $query, \'WP_Query\' ) || ! $query->is_main_query() || ! itheme2_featuring_posts() )
return;
// Exclude featured posts from the main query
$query->set( \'post__not_in\', itheme2_featuring_posts() );
// Note the we aren\'t returning anything.
// \'pre_get_posts\' is a byref action; we\'re modifying the query directly.
}
add_action( \'pre_get_posts\', \'itheme2_home_posts\' );
/**
* Test to see if any posts meet our conditions for featuring posts.
* Current conditions are:
*
* - sticky posts
* - with featured thumbnails
*
* We store the results of the loop in a transient, to prevent running this
* extra query on every page load. The results are an array of post ID\'s that
* match the result above. This gives us a quick way to loop through featured
* posts again later without needing to query additional times later.
*/
function itheme2_featuring_posts() {
if ( false === ( $featured_post_ids = get_transient( \'featured_post_ids\' ) ) ) {
// Proceed only if sticky posts exist.
if ( get_option( \'sticky_posts\' ) ) {
$featured_args = array(
\'post__in\' => get_option( \'sticky_posts\' ),
\'post_status\' => \'publish\',
\'no_found_rows\' => true
);
// The Featured Posts query.
$featured = new WP_Query( $featured_args );
// Proceed only if published posts with thumbnails exist
if ( $featured->have_posts() ) {
while ( $featured->have_posts() ) {
$featured->the_post();
if ( has_post_thumbnail( $featured->post->ID ) ) {
$featured_post_ids[] = $featured->post->ID;
}
}
set_transient( \'featured_post_ids\', $featured_post_ids );
}
}
}
// Return the post ID\'s, either from the cache, or from the loop
return $featured_post_ids;
}
除了瞬变之外,一切都很好。如果sticky\\u帖子已经更新,我不知道如何重置瞬态。可能使用
updated_option
钩非常感谢您的帮助。
最合适的回答,由SO网友:Drupalizeme 整理而成
您可以尝试:
add_action(\'update_option_sticky_posts\', function( $old_value, $value ) {
$featured_args = array(
\'post__in\' => $value,
\'post_status\' => \'publish\',
\'no_found_rows\' => true
);
// The Featured Posts query.
$featured = new WP_Query( $featured_args );
// Proceed only if published posts with thumbnails exist
if ( $featured->have_posts() ) {
while ( $featured->have_posts() ) {
$featured->the_post();
if ( has_post_thumbnail( $featured->post->ID ) ) {
$featured_post_ids[] = $featured->post->ID;
}
}
set_transient( \'featured_post_ids\', $featured_post_ids );
}
}, 10, 2);
我想你在
sticky_posts
选项,这就是您在
WP_Query