2014-02-07 98 views
0

我使用下面的函数目前不包括在我的主页循环“特色”的类别的所有讯息:仅使用pre_get_posts排除Wordpress主循环中类别的最新帖子?

function main_loop_excludes($query){ 
    if($query->is_main_query() && $query->is_home()){ 
    //'featured' cat ID = 531 
    $query->set('cat','-531'); 
    } 
} 

add_action('pre_get_posts','main_loop_excludes'); 

这工作完全,但我想只筛选出最近张贴而不是所有帖子从'精选'类别。这可能吗?

我已经看到了使用WP_Query来过滤特定帖子的方法,但我正在寻找一种方法在主要的Wordpress循环中执行此操作。 pre_get_posts感觉是最好的起点。我在正确的轨道上吗?


编辑:

我用下面的代码保存在特定的文章中,我要排除的ID(保存为变量$post_to_exclude_ID):

$post_ids = get_posts(array(
    'numberposts' => -1, // get all posts. 
    'category_name' => 'featured', 
    'fields'  => 'ids', // Only get post IDs 
)); 
// post ID = 2162 
$post_to_exclude_ID = $post_ids[0]; // Save ID of most recent post 

现在我可以使用原始main_loop_excludes函数来过滤主循环,以显示只有有问题的帖子,但我似乎无法逆转过程。在ID打破功能之前添加一个减号(该循环会显示全部帖子)。

新功能:

function main_loop_excludes($query){ 
    if($query->is_main_query() && $query->is_home()){ 
    // Make sure the var is accessible 
    global $post_to_exclude_ID; 
    // Set the filter 
    $query->set('p', $post_to_exclude_ID); 
    } 
} 
add_action('pre_get_posts','main_loop_excludes'); 

这并不工作:

$query->set('p', '-2162'); 

但同样的代码风格确实为类别工作:

$query->set('cat','-531'); 

NB:谢谢到Valerius用于提示找到帖子ID并将其注入$query->set...的想法。

回答

1

您可以使用wp_get_recent_posts()找到特定类别的最新帖子。

这样,我们可以做到以下几点:

function main_loop_excludes($query){ 
    $latest_featured = wp_get_recent_posts(array('numberposts' => 1, 'category' => 531)); 
    if($query->is_main_query() && $query->is_home()){ 
    //'featured' cat ID = 531 
    $query->set('post__not_in',array($latest_featured[0]['ID'])); //exclude queries by post ID 
    } 
} 

add_action('pre_get_posts','main_loop_excludes'); 
+0

我无法获得此代码的工作:不断得到死亡的白色屏幕。 'wp_get_recent_posts'确实让我发现了我用来查找所需ID的'get_posts'数组方法,所以感谢:主要问题被编辑以显示我现在在哪里。越来越近,我希望... –

+0

对我而言混乱,对不起。 'p'参数不可用。但是,post__not_in是(注意:名称中的双下划线)。它需要一个包含post ID的整数排除。上面更新了我的代码示例。 – Valerius

+0

'post__not_in'解决了问题!然而,不是马上:'wp_get_recent_posts(...'部分不断给我提供死亡的白色屏幕,使用问题中概述的'get_posts'方法*工作,并通过'post__not_in'传递完美! –

1

这里,不只是一个函数:

​​

用法:说我的类别编号为22,则:

$last_post_ID = get_lastest_post_of_category(22); 

你也可以传递一个类别数组到这个函数。

相关问题