获取同一类别中不起作用的帖子

时间:2015-06-16 作者:rebellion

我有一个带有自定义类别分类法的自定义帖子类型。在CPT single templae上,我想列出相同类别的其他帖子,但我无法让它发挥作用。

我的当前代码:

<?php
foreach ( Roots\\Sage\\Utils\\get_the_category_bytax( get_the_ID(), \'project_category\' ) as $cat )
  $category_ids[] = $cat->term_id;

  $projects = new WP_Query( array(
    \'post_status\'      => \'publish\',
    \'post__in\'         => get_post_meta( get_the_ID(), \'carbonlimits_project_related\', true ),
    \'post__not_in\'     => array( $current_post_id ),
    \'category__and\'    => $category_ids,
    \'post_type\'        => \'project\',
    \'caller_get_posts\' => 1,
    \'posts_per_page\'   => 4
  ) );

  while ( $projects->have_posts() ): $projects->the_post() ?>

    <div id="project-<?php the_ID() ?>" <?php post_class( \'col-sm-3\' ) ?>>
      <a href="<?php the_permalink() ?>">
        <?php
        $thumbnail = get_the_post_thumbnail( get_the_ID(), \'project-listing\' );
        if ( $thumbnail )
          echo $thumbnail;
        else
          echo \'<img src="/wp-content/themes/carbonlimits/dist/images/blank.gif" width="380" height="380">\';
        ?>
        <h3><?= $projects->post->post_title ?></h3>
        <span class="view-btn">View</span>
      </a>
    </div>

  <?php endwhile;
  // var_dump( $projects->request );
  wp_reset_postdata();
?>
是因为它是一种自定义的帖子类型和分类法吗?

1 个回复
SO网友:James Barrett

这应该适用于自定义分类法。

<?php
function get_related_posts() {

    global $post;

    $taxonomy = \'your_custom_taxonomy\';
    $terms = wp_get_post_terms( $post->ID, $taxonomy );

    if($terms) {
        $term_arr = \'\';
        foreach( $terms as $term ) {
            $term_arr .= $term->slug . \',\'; // create array of term slugs
        }

        $args = array(
          \'showposts\' => 5, // you can change this to whatever you need
          \'post__not_in\' => array($post->ID) // exlude current post from results
          \'tax_query\' => array(
            array(
              \'taxonomy\' => $taxonomy,
              \'field\' => \'slug\', // using \'slug\' but can be either \'term_id\', \'slug\' or \'name\'
              \'terms\' => $term_arr // array of ID values, slugs or names depending what \'field\' is set to
            )
          )
        );
        $related_posts = get_posts( $args );

        if($related_posts) {

          foreach ( $related_posts as $post ) : setup_postdata( $post ); 
            // output whatever you want here
            the_title(); // for example
          endforeach;

        } else {

          echo \'No Related Posts\';

        }

    }

    wp_reset_postdata();
}
?>

结束

相关推荐