如何减少查询次数?

时间:2014-01-01 作者:Jagst3r15

我有帖子的元键“到期”。。。。如果帖子已过期(超过当前日期或不等于当前日期),则它将不会显示在计数中。这是我的代码,它工作得很好。我唯一的问题是,它会创建100多个查询。有没有办法减少这个数字?我不知道如何优化它。。。。

/**
 * Function to list all category with thumbnail custom link, etc..
 *
 * How to use this function:
 * Add in template: <?php my_category_list(); ?>
 *
 */
function my_category_list(){

/* LIST OF CATS DATA */
$cats_data = array();

/**
 * Get Categories
 * @link http://codex.wordpress.org/Function_Reference/get_categories
 */
$cat_args = array(
    \'hide_empty\'    => 0,
    \'exclude\'       => \'13,1,1460\'
);
$categories = get_categories( $cat_args );

/* If category found, load list of category */
if ( !empty( $categories ) ) {
    $i = 0;

    /* Foreach category: display the data */
    foreach ( $categories as $cat) {

        /* ======= HTML CLASS ========= */
        /* dynamic class (?) need fix */
        $class = ( $i % 3 ) ? \'span4\' : \'span4\';
        $classes = $class . \' \' . \'category-\' . $cat->term_id;

        /* ======= POST COUNT ========= */
        /* Get all posts in category + in due date
         * this only to get the post count.
         * @link http://themehybrid.com/support/topic/issue-with-filtering-due-meta-key
         */
        $query_args = array(
            \'post_type\'       => \'post\',
            \'category_name\'   => $cat->slug,
            \'meta_query\' => array(
                array(
                    \'key\'        => \'Due\',
                    \'value\'      => date( \'Ymd\' ),
                    \'type\'       => \'DATE\',
                    \'compare\'    => \'>=\', // greater than or equal to
                )
            )
        );
        $my_query = new WP_Query( $query_args );
        $post_count = $my_query->found_posts;

        /* ====== CATEGORY THUMBNAIL ======== */
        $thumbnail_id = get_option(\'seamless_term_thumb_\' . $cat->term_id);
        $image = wp_get_attachment_url($thumbnail_id);

        /* ====== LINK TO SEARCH: no need fields ======= */
        $link_to = \'http://www.scholarships360.org/discover/?search_query=&orderby=blank&tax_category=\' . $cat->slug .\'&wpas=1\';

        /* MERGE DATA IN ARRAY */
        $cats_data[] = array(
            \'classes\'      => $classes,
            \'post_count\'   => $post_count,
            \'image\'        => $image,
            \'name\'         => $cat->name,
            \'link\'         => $link_to,
        );

        $i++;
    } // end foreach

    /**
     * NOW THE FUN PART
     * =================
     */

    /* Sort Cat Data by Post Count */
    usort($cats_data, \'my_sort_cat_data\');

    /* Cut only 6 item to display */
    $cats_data = array_slice( $cats_data, 0, 6 );

    /* Display it */
    foreach ($cats_data as $cat_data ){ ?>

        <div class="<?php echo $cat_data[\'classes\'];?>">
            <div class="thumb one">
                <a href="<?php echo $cat_data[\'link\'] ?>">
                    <div class="two"><?php echo  $cat_data[\'post_count\'] . \' Scholarships\' ?></div>
                </a>
                <a href="<?php echo $cat_data[\'link\'] ?>">
                    <img src="<?php echo $cat_data[\'image\']; ?>" alt="<?php echo esc_attr( $cat_data[\'name\'] ); ?>" class="item-image">
                </a>
            </div>  <!-- end .thumb -->
        </div>
    <?php 
    }
}
/* No category found */
else {
    echo \'<p>No category found...</p>\';
}
}

 /**
 * Sort Cat Data Helper Function
 * @link http://stackoverflow.com/questions/2699086/sort-multidimensional-array-by-value-2
 */
function my_sort_cat_data( $a, $b ){
 return $b[\'post_count\'] - $a[\'post_count\'];
}

1 个回复
SO网友:adelval

尝试以下操作:

global $wpdb; 
$num_cat = 6;
$query = "SELECT tt.term_taxonomy_id, t.name, COUNT( t.name ),
          GROUP_CONCAT( p.ID ) , GROUP_CONCAT(m.meta_value)
          FROM  {$wpdb->prefix}term_taxonomy tt
          NATURAL JOIN {$wpdb->prefix}terms t
          NATURAL JOIN {$wpdb->prefix}term_relationships tr
          JOIN {$wpdb->prefix}posts p ON ( tr.object_id = ID ) 
          JOIN {$wpdb->prefix}postmeta m ON ( post_id = ID ) 
          WHERE taxonomy = \'category\'
          AND post_type= \'post\'
          AND post_status= \'publish\'
          AND meta_key = \'Due\'
          AND meta_value > ".date(\'Ymd\').
          "GROUP BY name
           ORDER BY COUNT( name ) DESC LIMIT $num_cat";
 $top_cats = $wpdb->get_results($query);

 foreach ($top_cats as $key => $cat) {
     $thumbnail_id = get_option(\'seamless_term_thumb_\' . $cat->term_taxonomy_id);
     $image = wp_get_attachment_url($thumbnail_id);
    /* ...etc... */
 }
直观地说,查询“首先”从wp\\U terms\\u taxonomy和wp\\u terms中获取类别ID及其名称,“然后”使用wp\\U term\\u关系获取每个类别中的帖子,“然后”使用wp\\U postmeta按截止日期过滤帖子。“最后”,结果按类别分组和计数,并按计数排序。(我使用引号是因为db管理器可以按照它想要的任何方式执行查询,而不一定是按照这个顺序)。

为了方便和易于验证,使用mysql的GROUP\\u CONCAT将每个类别中的帖子ID及其相应的截止日期连接在一个字符串中。试试看!然后可以将其从代码中删除。

请注意,您应该使用$cat->term_taxonomy_id 而不是$cat->term_id (这也适用于您的代码),因为一个term\\u id可以与多个分类法关联(例如,在不同分类法中具有相同slug的术语)。这可能会导致非常模糊的错误,正是因为它经常被忽视。term\\u taxonomy\\u id表示这对(term\\u id,taxonomy),它保证是唯一的。

通过向每一行添加thumbnail\\u id,使用附加联接修改查询,实际上可以进一步减少查询的数量。类似这样(未经测试):

SELECT ..., o.meta_value as thumbnail_id 
FROM ... JOIN {$wpdb->prefix}options o 
         ON (o.meta_key = CONCAT(\'seamless_term_thumb_\', tt.term_taxonomy_id))
大概可以对缩略图的url执行类似的操作。

结束