创建基于相似类别的相关帖子部分

时间:2017-03-07 作者:Samuel

这是我的当前代码single.php 文件它获取标签。但我想取而代之的是获取类别。我可以用$类别交换$标记吗。

        <div class="related-articles">
           <div class="related-articles-wrapper">

      <?php
            $orig_post = $post;
            global $post;
            $cats = wp_get_post_categories($post->ID);

            if ($cats) {
            $cat_ids = array();
            foreach($cats as $individual_cat) $cat_ids[] = $individual_cat->term_id;
            $args=array(
            \'category__in\' => $cat_ids,
            \'post__not_in\' => array($post->ID),
            \'posts_per_page\'=>3, // Number of related posts to display.
            \'ignore_sticky_posts\'=>1
            );

            $my_query = new wp_query( $args );

            while( $my_query->have_posts() ) {
              $my_query->the_post();
      ?>

<div class="posts__post" style="background-image: url(<?php echo get_the_post_thumbnail_url($post_id, \'thumbnail\'); ?> ) !important;">
                    <article>
                        <a class="posts__post--title" href="<?php the_permalink(); ?>"><h1><?php the_title(); ?></h1></a>
                        <div class="posts__post--meta">
                          <p class="posts__post__tag"><a href=""><?php the_category(\'&nbsp;/&nbsp;\'); ?></a></p>
                          <p class="posts__post__timestamp"><i class="fa fa-clock-o" aria-hidden="true"></i><?php echo time_ago(); ?></p>
                        </p>
                        </div>
                    </article>   
                </div>

                  <? }
                  }
                  $post = $orig_post;
                  wp_reset_query();
                  ?>
            </div>
        </div>

1 个回复
最合适的回答,由SO网友:Michael 整理而成

看看法典中对应类别而非标签的章节:https://developer.wordpress.org/reference/functions/wp_get_post_categories/https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters

您的代码可以重新写入:

<?php
      $orig_post = $post;
      global $post;
      $cats = get_the_category($post->ID);

      if ($cats) {
      $cat_ids = array();
      foreach($cats as $individual_cat) $cat_ids[] = $individual_cat->term_id;
      $args=array(
      \'category__in\' => $cat_ids,
      \'post__not_in\' => array($post->ID),
      \'posts_per_page\'=>3, // Number of related posts to display.
      \'ignore_sticky_posts\'=>1
      );

      $my_query = new wp_query( $args );

      while( $my_query->have_posts() ) {
        $my_query->the_post();
?>

相关推荐

无法在模板函数.php中使用IS_HOME

我试图在标题中加载一个滑块,但只在主页上加载。如果有帮助的话,我正在使用Ultralight模板。我正在尝试(在template functions.php中)执行以下操作:<?php if ( is_page( \'home\' ) ) : ?> dynamic_sidebar( \'Homepage Widget\' ); <?php endif; ?> 但这行不通。现在,通过快速的google,我似乎需要将请