Skip to content

Instantly share code, notes, and snippets.

@Kenty
Last active November 10, 2016 07:21
Show Gist options
  • Save Kenty/f3e330ce916d833596ce to your computer and use it in GitHub Desktop.
Save Kenty/f3e330ce916d833596ce to your computer and use it in GitHub Desktop.
タクソノミーで関連している投稿の5件を取得する。カスタム投稿タイプでも使える。array_popで連想配列の最後を取得
<?php
if ( ! function_exists( 'dm_related_post' ) ) {
function dm_related_post() {
global $post;
$post_type = $post->post_type;
$taxonomies = get_object_taxonomies( $post_type );
if ( ! empty( $taxonomies ) && ! is_wp_error( $taxonomies ) ) {
$obj_terms = wp_get_object_terms( $post->ID, $taxonomies, array( 'fields' => 'all' ) );
$obj = array_pop( $obj_terms );
$term_name = $obj->name;
$taxonomy = $obj->taxonomy;
$term_id = $obj->term_id;
?>
<h3 class="related-title title-1">Related Posts: <?php echo esc_attr( $term_name ); ?></h3>
<?php
$args = array(
'post_type' => $post_type,
'post_status' => 'publish',
'post_per_page' => 5,
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'id',
'terms' => $term_id,
),
),
'post__not_in' => array( $post->ID ),
'no_found_rows' => true,
);
$related = new WP_Query( $args ); ?>
<?php if ( $related->have_posts() ) : ?>
<ul class="related-post small-block-grid-2 large-block-grid-5">
<?php while ( $related->have_posts() ) : $related->the_post(); ?>
<li class="related-post-item">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'rel_tmn' ); ?></a>
<h4 class="related-post-title"><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></h4>
</li>
<?php endwhile; ?>
</ul>
<?php else : ?>
<p>関連する記事はありません。</p>
<?php endif; ?>
<?php wp_reset_postdata();
// echo '<pre>';
// print_r( $obj );
// echo '</pre>';
?>
<?php }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment