用于列出帖子的自定义MySQL查询

时间:2013-01-10 作者:Rashy

我有以下疑问:

SELECT
  p.*
FROM
  orders_items oi
  INNER JOIN products pr
    ON pr.`post_id` = oi.`product_id`
  INNER JOIN posts p
    ON p.`ID` = pr.`post_id`
    AND p.`post_type` = \'product\'
GROUP BY oi.`product_id`
ORDER BY COUNT(oi.id) DESC;
我想根据上面的查询列出帖子。谁能告诉我如何更改以下代码以合并上述查询?

    $args = array(
        \'posts_per_page\' => \'10\',
        \'post_type\'      => \'product\',
        \'paged\'          => \'1\'
    );
    global $query_string;
    query_posts($args);
有人帮忙吗?

2 个回复
SO网友:Eugene Manuilov

您不需要使用query_posts 作用没有它也可以做到。使用setup_postdata 用于设置全局post数据的函数。

$sql = "
    SELECT
      p.*
    FROM
      orders_items oi
      INNER JOIN products pr
        ON pr.`post_id` = oi.`product_id`
      INNER JOIN posts p
        ON p.`ID` = pr.`post_id`
        AND p.`post_type` = \'product\'
    GROUP BY oi.`product_id`
    ORDER BY COUNT(oi.id) DESC
";

echo \'<ul>\';

$result = $wpdb->get_results( $sql );
foreach ( $result as $post ):
    setup_postdata( $post );
    ?><li>
        <a href="<?php the_permalink() ?>"><?php the_title() ?></a>
    </li><?php 
endforeach;

echo \'</ul>\';

SO网友:Arvind Pal
global $paged;
$temp = $wp_query;
$wp_query = null;

$wp_query = new WP_Query( array(\'post_type\' => \'product\',\'posts_per_page\' => 10, \'paged\' => $paged ) ); ?>
<?php while (have_posts()) : the_post();

/* Your product content data here */


<?php               
endwhile;
wp_reset_query();
?>
<?php echo paginate_links( $args ) ?>
<?php
global $wp_query;
$big = 999999999; // need an unlikely integer
echo paginate_links( array(
    \'base\' => str_replace( $big, \'%#%\', esc_url( get_pagenum_link( $big ) ) ),
    \'format\' => \'?paged=%#%\',
    \'current\' => max( 1, get_query_var(\'paged\') ),
    \'total\' => $wp_query->max_num_pages,
    \'prev_text\'    => __(\'Previous\'),
\'next_text\'    => __(\'Next\')
) );
?> 

i think this will solve ur problem. if u face any problem let me know
结束

相关推荐

为了减少CPU负载,我应该使用GET_POST还是wp_QUERY?

我有一个博客,主页上有3块帖子。所以,我用“get\\u post”获得这些帖子,我在页面上有3个类似的代码:global $post; $args = array( ... ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> ....... <?php endforeach; ?> 我的CPU负载很高,我想