获取自定义帖子类型上的相关子分类帖子

时间:2016-05-16 作者:ajguitars

我有一个自定义职位类型[学校]和一个自定义税[地点]。

每个学校都属于一个位置类别。

我想在侧边栏中显示附近的学校。到目前为止,我已经想出了如何展示其他5所学校,但它们并不总是在附近,这是无用的!如何在自定义单页上显示该类别中的5所学校?

下面显示3篇随机帖子,但不在同一类别中。我希望它可以很容易地调整,为我工作?!

<?php
// You might need to use wp_reset_query(); 
// here if you have another query before this one

global $post;

$current_post_type = get_post_type( $post );

// The query arguments
$args = array(
\'posts_per_page\' => 3,
\'order\' => \'DESC\',
\'orderby\' => \'ID\',
\'post_type\' => $current_post_type,
\'post__not_in\' => array( $post->ID )
);
// Create the related query
$rel_query = new WP_Query( $args );

// Check if there is any related posts
if( $rel_query->have_posts() ) : 
?>
<h1 id="recent">Related</h1>
<div id="related" class="group">
   <ul class="group">
<?php
// The Loop
while ( $rel_query->have_posts() ) :
    $rel_query->the_post();
?>
    <li>
    <a href="<?php the_permalink() ?>" title="<?php the_title() ?>" rel="bookmark">
        <article>
            <h1 class="entry-title"><?php the_title() ?></h1>
            <div class="name-date"><?php the_time(\'F j, Y\'); ?></div>
            <div class="theExcerpt"><?php the_excerpt(); ?></div>
        </article>
    </a>
    </li>
<?php
endwhile;
?>
 </ul><!-- .group -->
</div><!-- #related -->
<?php
endif;

// Reset the query
wp_reset_query();

?>

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

您可以使用tax query! 此代码段还利用了wp_list_pluck, 一个超级方便的函数,用于从对象数组中“提取”属性(在本例中,从术语对象数组中获取术语ID数组):

// Get current posts location term(s)
$locations = get_the_terms( null, \'location_taxonomy\' );

if ( $locations && ! is_wp_error( $locations ) /* Can\'t be too careful */ ) {
    $schools = new WP_Query([
        \'posts_per_page\' => 5,
        \'no_found_rows\'  => true,
        \'post_type\'      => \'school_post_type\',
        \'tax_query\'      => [
            [
                \'taxonomy\' => \'location_taxonomy\',
                \'terms\'    => wp_list_pluck( $locations, \'term_id\' ),
            ]
        ]
    ]);
}
Update: 要与当前代码集成,请执行以下操作:

$current_post_type = get_post_type( $post );
$locations         = get_the_terms( $post, \'location_taxonomy\' );

// The query arguments
$args = array(
    \'posts_per_page\' => 3,
    \'order\'          => \'DESC\',
    \'orderby\'        => \'ID\',
    \'post_type\'      => $current_post_type,
    \'post__not_in\'   => array( $post->ID ),
    \'no_found_rows\'  => true, // Performance boost
);

if ( $locations && ! is_wp_error( $locations ) ) {
    $args[\'tax_query\'] = array(
        array(
            \'taxonomy\' => current( $locations )->taxonomy,
            \'terms\'    => wp_list_pluck( $locations, \'term_id\' ),
        )
    );
}

// Create the related query
$rel_query = new WP_Query( $args );

相关推荐