上一篇/下一篇文章链接显示的类别错误

时间:2017-02-23 作者:finamf92

我想要我的single.php 为帖子下方的上一篇和下一篇帖子显示相同类别的帖子。问题是,我的每个帖子都属于多个类别,它们通过其他类别(24)中的一个显示,而我希望它们从(27)中显示出来。这有意义吗?

示例类别:

字符(父类别)(下面列出的子类别ID:)

24(改为显示此类别ID。)

  • 27(这是我要显示的类别ID。)

        <?php
        if (is_single() && in_category(\'stories\')) {
            $post_id = $post->ID;
            $cat = get_the_category(); //I\'ve tried changing this to my category (both ID and slug)
            $current_cat_id = $cat[0]->cat_ID;  //Also tried plugging ID and slug
    
            $args = array(
                \'category\' => $current_cat_id, //Also tried plugging ID and slug
                \'orderby\' => \'post_date\',
                \'order\' => \'DESC\'
            );
            $posts = get_posts($args);
    
            $ids = array();
            foreach ($posts as $thepost) {
                $ids[] = $thepost->ID;
            }
    
            $thisindex = array_search($post_id, $ids);
            $previd = $ids[$thisindex - 1];
            $nextid = $ids[$thisindex + 1];
    
            if (!empty($nextid)) {
                ?><div class="double-grid"><a rel="next" href="<?php echo get_permalink($nextid) ?>"><div class="image-tile tile-on-archive-page" style="background-image: url(\'<?php echo get_the_post_thumbnail_url($nextid); ?>\'"> <div class="gold-button">LAST STORY >></div></div></a></div><?php
            }
            if (!empty($previd)) {
                ?><div class="double-grid"><a rel="prev" href="<?php echo get_permalink($previd) ?>"><div class="image-tile tile-on-archive-page" style="background-image: url(\'<?php echo get_the_post_thumbnail_url($previd); ?>\'"> <div class="gold-button">NEXT STORY >></div></div></a></div><?php
            }
        }
        ?>
    

  • 2 个回复
    最合适的回答,由SO网友:finamf92 整理而成

    哈札!我想我会把它贴在这里,但我在Wordpress的开发论坛上与某人合作过。他们实际上为我解决了这个问题。

    您可以在此处看到解决方案和调整:WordPress.org Forum Topic

    SO网友:Max Yudin

    你的代码问题是你只能得到帖子的第一个类别,因为$cat[0] 是第一个,不是当前的。

    回路内部:

    <?php
    previous_post_link( // prints the formatted link
        \'<span>&laquo; %link</span>\',  // beautifying around
        \'Prev in this cat\',            // the text (%link) to be used in the span above
        true,                          // confirm that you want only this category
        \'\',                            // no categories to exclude
        \'category\'                     // taxonomy name
    );
    
    echo " | "; // just a separator between next and prev
    
    /* The same setup here, not shown to keep the answer clean */
    next_post_link();
    
    请参见previous_post_link() 用于参数。

    如果您在循环之外,请告诉我,我将更新答案并提供其他代码和注释。