Php wordpress中相同类别的上一个和下一个链接

Php wordpress中相同类别的上一个和下一个链接,php,wordpress,Php,Wordpress,在wordpress的single.php文件中,有一个导航部分链接下一篇或上一篇文章。 这是我在上一篇/下一篇文章中使用的代码。我希望这些链接能够打开相同类别的帖子(在我下面的示例中,“2”是该类别的ID): 第四个参数用于要排除的类别,因此在本例中排除类别2 删除第四个参数可以实现以下目的: <?php previous_post_link('%link', '<i class="icon-chevron-left pull-left"></i>', TRUE)

在wordpress的single.php文件中,有一个导航部分链接下一篇或上一篇文章。 这是我在上一篇/下一篇文章中使用的代码。我希望这些链接能够打开相同类别的帖子(在我下面的示例中,“2”是该类别的ID):


第四个参数用于要排除的类别,因此在本例中排除类别
2

删除第四个参数可以实现以下目的:

<?php previous_post_link('%link', '<i class="icon-chevron-left pull-left"></i>', TRUE); ?>
<?php next_post_link('%link', '<i class="icon-chevron-right pull-right"></i>', TRUE); ?>
这是
functions.php
文件的过滤函数:

<?php
    // set the category ID wanted
    $GLOBALS['just_this_category'] = 2;
    // add filter for navigation links
    add_filter('wp_get_object_terms', 'my_custom_post_navigation'); ?>
?>

<!-- navigation links -->
<?php previous_post_link('%link', '<i class="icon-chevron-left pull-left"></i>', TRUE); ?>
<?php next_post_link('%link', '<i class="icon-chevron-right pull-right"></i>', TRUE); ?>

<?php // remove filter just after navigation links
    remove_filter('wp_get_object_terms', 'my_custom_post_navigation');
?>
function my_custom_post_navigation($terms){
    global $just_this_category;

    if( array_search($just_this_category, (array)$terms) !== FALSE )

        return array($just_this_category);

    return array();

}
如您所见,我使用全局变量
$just_this_category
将类别ID传递给filter函数


显然,对于每一篇文章,您都需要设置不同的类别ID(您可以自动检索,但如何检索取决于您如何管理类别)。

第四个参数用于要排除的类别,因此在本例中,您排除的是类别
2

删除第四个参数可以实现以下目的:

<?php previous_post_link('%link', '<i class="icon-chevron-left pull-left"></i>', TRUE); ?>
<?php next_post_link('%link', '<i class="icon-chevron-right pull-right"></i>', TRUE); ?>
这是
functions.php
文件的过滤函数:

<?php
    // set the category ID wanted
    $GLOBALS['just_this_category'] = 2;
    // add filter for navigation links
    add_filter('wp_get_object_terms', 'my_custom_post_navigation'); ?>
?>

<!-- navigation links -->
<?php previous_post_link('%link', '<i class="icon-chevron-left pull-left"></i>', TRUE); ?>
<?php next_post_link('%link', '<i class="icon-chevron-right pull-right"></i>', TRUE); ?>

<?php // remove filter just after navigation links
    remove_filter('wp_get_object_terms', 'my_custom_post_navigation');
?>
function my_custom_post_navigation($terms){
    global $just_this_category;

    if( array_search($just_this_category, (array)$terms) !== FALSE )

        return array($just_this_category);

    return array();

}
如您所见,我使用全局变量
$just_this_category
将类别ID传递给filter函数


显然,对于每一篇文章,你都需要设置不同的类别ID(你可以自动检索,但如何检索取决于你如何管理你的类别)。

但它无论如何都不起作用。它显示所有的帖子,而不仅仅是一个类别的帖子。这些帖子是否属于多个类别?正如参考文献所说:“如果文章同时属于父类和子类,或者不止一个术语,那么下一篇文章链接将指向这些术语中的下一篇文章”。你是对的。它们属于不止一个类别。是否有可能只链接一个子类别?我已经更新了答案。再见!:)但它无论如何都不起作用。它显示所有的帖子,而不仅仅是一个类别的帖子。这些帖子是否属于多个类别?正如参考文献所说:“如果文章同时属于父类和子类,或者不止一个术语,那么下一篇文章链接将指向这些术语中的下一篇文章”。你是对的。它们属于不止一个类别。是否有可能只链接一个子类别?我已经更新了答案。再见!:)