0

「動画」と「場所」の2種類のカスタム投稿タイプを作成しました。
次に、「Video_Categories」というカスタム分類法を作成しました。
このカスタム分類法を両方のカスタム投稿タイプに割り当てました。

私がやりたいのは、ロケーションに互いに同じ用語を持つビデオを表示することです。

例えば:

ビデオ投稿:

  • 名前:ビデオ1; Video_Category:クイーンズランド州ブリスベン;
  • 名前:ビデオ2; Video_Category:クイーンズランド州ゴールドコースト;
  • 名前:ビデオ3; Video_Category:クイーンズランド州サンシャインコースト;

ロケーション投稿:

  • 名前:ブリスベン; Video_Category:ブリスベン;

この投稿の分類法を調べ、同じ分類法を持つビデオ投稿を返す[場所]ページからクエリを作成したいと思います。

上記の例では、「ビデオ1」のビデオ投稿が返され、ロケーションページに表示されます。

4

1 に答える 1

3

良い質問です。これは、関連するカテゴリやタグを取得する場合とは少し異なりますが、同様の前提を使用しています。これを行う方法はいくつかありますが、最も簡単な方法の1つは、を利用するカスタム関数を使用することWP_Queryです。次のコードをファイルに追加しfunctions.phpます。

// Create a query for the custom taxonomy
function related_posts_by_taxonomy( $post_id, $taxonomy, $args=array() ) {
    $query = new WP_Query();
    $terms = wp_get_object_terms( $post_id, $taxonomy );

    // Make sure we have terms from the current post
    if ( count( $terms ) ) {
        $post_ids = get_objects_in_term( $terms[0]->term_id, $taxonomy );
        $post = get_post( $post_id );
        $post_type = get_post_type( $post );

        // Only search for the custom taxonomy on whichever post_type
        // we AREN'T currently on
        // This refers to the custom post_types you created so
        // make sure they are spelled/capitalized correctly
        if ( strcasecmp($post_type, 'locations') == 0 ) {
            $type = 'videos';
        } else {
            $type = 'locations';
        }

        $args = wp_parse_args( $args, array(
                'post_type' => $type,
                'post__in' => $post_ids,
                'taxonomy' => $taxonomy,
                'term' => $terms[0]->slug,
            ) );
        $query = new WP_Query( $args );
    }

    // Return our results in query form
    return $query;
}

もちろん、この関数で何でも変更して、探している正確な結果を得ることができます。詳細については、http://codex.wordpress.org/Class_Reference/WP_Queryをご覧ください。

related_posts_by_taxonomy()これで、関連する投稿を検索する分類法を渡すことができる関数にアクセスできるようになりました。したがって、single.phpカスタム投稿タイプに使用されているテンプレートまたはテンプレートで、次のような操作を行うことができます。

<h4>Related Posts</h3>
<ul>
<?php $related =  related_posts_by_taxonomy( $post->ID, 'Video_Categories' );
    while ( $related->have_posts() ): $related->the_post(); ?>
        <li><?php the_title(); ?></li>
    <?php endwhile; ?>
</ul>
于 2012-09-04T06:30:50.043 に答える