将数组传递给相关帖子的WPDB查询

时间:2013-01-29 21:39:43

标签: arrays wordpress

我在下面有以下代码。我知道这不是抓住相关帖子的最有效方式。我是新来查询数据库,有没有办法在那里抛出一个数组来查询可以选择的多个术语?而不是我现在正在做什么,只是抓住数组的第一个键。

<?php
// Get The Related Term
$terms = array();
foreach(wp_get_object_terms($post->ID, 'series') 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 = 'sermon' 
    AND $wpdb->posts.post_status = 'publish'
    AND $wpdb->term_taxonomy.taxonomy = 'series'
    AND $wpdb->terms.slug = '$related_term'
    AND $wpdb->posts.ID <> $post->ID
    ORDER BY $wpdb->posts.post_date DESC
    "
);
foreach ($related_posts as $related) {
    echo '<li><a href="'.get_permalink($related->ID).'">'.get_the_title($related->ID).'</a></li>';
};
?>

1 个答案:

答案 0 :(得分:0)

实际上,有一种方法可以通过更合适的方式从不同的术语中获取帖子。看看这个简单的例子

$related_posts = get_posts(array(
    'posts_per_page' => -1, // all posts
    'post_type' => 'sermon',
    'post_status' => 'publish',
    'post__not_in' => array($post->ID),
    'tax_query' => array(
            array(
                'taxonomy' => 'series',
                'field' => 'slug', // or id
                'terms' => $term1->slug // or id
                'include_children' => false // do no include the posts in the child terms
            ),
            array(
                'taxonomy' => 'series',
                'field' => 'slug', // or id
                'terms' => $term2->slug // or id
                'include_children' => false // do no include the posts in the child terms
            ), //etc...
    )
));

您需要做的就是获取当前帖子和循环的所有条款,并将它们推送到get_posts tax_query数组。