相关帖子的帮助功能

时间:2013-02-06 作者:souporserious

我正在尝试编写一个函数,根据分类法的术语获取所有相关帖子。我在尝试查询多个术语时遇到了问题。

我现在的做法是使用第一个术语查询相关帖子。知道如何检查它是否是倍数吗?

function related_posts($related_type, $related_tax) {

    global $wpdb, $post;

    // Get The Related Term
    $terms = array();
    foreach(wp_get_object_terms($post->ID, $related_tax) as $term){
        $terms[] = $term->slug;
    };

    // Grab The First Term From The Array
    $related_term = array_shift(array_values($terms));

    // Query The Related Posts
    $related_posts = $wpdb->get_results( 
        "
        SELECT * 
        FROM $wpdb->posts
        LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)
        LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
        LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)
        WHERE $wpdb->posts.post_type = \'$related_type\' 
        AND $wpdb->posts.post_status = \'publish\'
        AND $wpdb->term_taxonomy.taxonomy = \'$related_tax\'
        AND $wpdb->terms.slug = \'$related_term\'
        AND $wpdb->posts.ID <> $post->ID
        ORDER BY $wpdb->posts.post_date DESC
        "
    );

    if($related_posts) {
        echo \'<ul>\';
            foreach ($related_posts as $post):setup_postdata($post);
                echo \'<li><a href="\'.get_permalink().\'">\'.get_the_title().\'</a></li>\';
            endforeach;
        echo \'</ul>\';
    } else {
        echo \'No related posts found\';
    }

}
我想这样:如果这个学期或这个学期或这个学期,然后显示所有相关的职位。

我以前使用过$wpdb->术语。插入(“$术语”),但这只会显示与此完全匹配的相关帖子。

1 个回复
SO网友:tobbr

您可以在获取帖子时使用Wordpress的tax\\u query arg来实现您的目标,这也可以通过多种分类法轻松扩展。

$query = array(
    \'post_type\' => $YOUR_POST_TYPE,
    \'posts_per_page\' => -1 // get all
    \'tax_query\' => array(
        \'relation\' => \'OR\'
    )
);

$query[\'tax_query\'][] = array(
    \'taxonomy\' => \'YOUR_TAXONOMY\',
    \'terms\' => $ARRAY_WITH_TERMS,
    \'field\' => \'ID\',
    \'operator\' => \'IN\'

$query[\'tax_query\'][] = array(
    \'taxonomy\' => \'YOUR_TAXONOMY_2\',
    \'terms\' => $ARRAY_WITH_TERMS_2,
    \'field\' => \'ID\',
    \'operator\' => \'IN\'

$posts = query_posts( $query );
这就是你要找的吗?

结束