Wordpress:多站点帖子查询的过滤类别

时间:2014-09-09 09:27:12

标签: php mysql sql wordpress

我的情况

首先,我没有做过任何自定义SQL查询,所以请耐心等待..

我有一个包含多个博客的多站点安装。以下函数查询所有博客的最新帖子,并且工作正常。

工作代码,取自https://gist.github.com/mhulse/5718743

function recent_ms_posts($count = 10, $cat, $ignore = array('')) {

    global $wpdb, $table_prefix;

    $ignore = implode(', ', array_map('absint', $ignore));
    $rows = NULL;
    $tables = array();
    $query = '';
    $i = 0;
    $posts = array();
    $post = NULL;

    $rows = $wpdb->get_results($wpdb->prepare("SELECT blog_id FROM $wpdb->blogs WHERE blog_id NOT IN ($ignore) AND public = '1' AND archived = '0' AND mature = '0' AND spam = '0' AND deleted = '0'", 0), ARRAY_A);

    if ($rows) {

        foreach ($rows as $row) {
            $tables[$row['blog_id']] = $wpdb->get_blog_prefix($row['blog_id']) . 'posts';
        }

        if (count($tables)) {
            foreach ($tables as $blog_id => $table) {
                if ($i)
                    $query .= ' UNION ';

                $query .= " (SELECT ID, post_date, $blog_id as `blog_id` FROM $table WHERE post_status = 'publish' AND post_type = 'post')";
                $i++;
            }

            $query .= " ORDER BY post_date DESC LIMIT 0, $count;";
            $rows = $wpdb->get_results($query);

            if ($rows) {
                foreach ($rows as $row) {
                    $post = get_blog_post($row->blog_id, $row->ID);
                    $post->blog_id = $row->blog_id;
                    $post->row_id =$row->ID;
                    $post->permalink = get_blog_permalink($row->blog_id, $row->ID);
                    $posts[] = $post;
                }

                return $posts;
            }
        }
    }
}

我的问题

我现在要做的是过滤掉某个类别的帖子,我尝试稍微修改一下查询字符串:

修改后的代码

$query .= " (SELECT ID, post_date, $blog_id as `blog_id` FROM $table WHERE post_status = 'publish' AND post_type = 'post' AND term_taxonomy.taxonomy = 'category' AND terms.slug = '$cat')";

我的问题

如何让term_taxonomy.taxonomy = 'category'terms.slug = '$cat'正常工作?

1 个答案:

答案 0 :(得分:0)

好的,所以我通过改变$query字符串并添加一些变量来解决问题:

$table_posts = $table . 'posts';
$table_term_relationships = $table . 'term_relationships';
$table_term_taxonomy = $table . 'term_taxonomy';
$table_terms = $table . 'terms';

if ($i)
    $query .= ' UNION ';

$query .= " (
    SELECT 
    $table_posts.ID, 
    $table_posts.post_date, 
    $blog_id as `blog_id` 
    FROM 
    $table_posts 
    LEFT JOIN $table_term_relationships ON ($table_posts.ID = $table_term_relationships.object_id) 
    LEFT JOIN $table_term_taxonomy ON ($table_term_relationships.term_taxonomy_id = $table_term_taxonomy.term_taxonomy_id) 
    LEFT JOIN $table_terms ON ($table_term_relationships.term_taxonomy_id = $table_terms.term_id) 
    WHERE 
    post_status = 'publish' 
    AND 
    post_type = 'post'
    AND
    $table_term_taxonomy.taxonomy = 'category' 
    AND
    $table_terms.slug LIKE '$cat'
    )";