订购wordpress post_meta - 从最低到最高

时间:2013-08-05 13:48:54

标签: wordpress metadata

我目前正在遍历所有帖子并显示如下的post_meta值:

global $wpdb;
$table =  $wpdb->prefix . 'postmeta';
$theid = get_the_id();
$getLowestPrice = $wpdb->get_results("SELECT * FROM $table WHERE meta_value = '$theid'");
foreach ( $getLowestPrice as $post ){

get_post_meta( $post->post_id, '_wholesale_price', false );

}

有没有办法订购结果,最低 - >最高?目前,它们随机显示,或者在输入时显示。

2 个答案:

答案 0 :(得分:0)

使用以下代码

<?php 
 global $wpdb;
 $table =  $wpdb->prefix . 'postmeta';
 $theid = get_the_id();
 $getLowestPrice = $wpdb->get_results("SELECT * FROM $table WHERE meta_value = '$theid'");
$all_post = array();
foreach ( $getLowestPrice as $post ){
   $all_post[] = $post->post_id; 

}
$query = new WP_Query( array( 'post__in' => $all_post, 'orderby' => 'meta_value', 'meta_key' => '_wholesale_price','order' => 'ASC') );

// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
    $query->the_post();
    echo '<div>' . get_post_meta( $get_the_ID(), '_wholesale_price', false );() . '</div>';
}
 } else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
?>`

答案 1 :(得分:0)

这对我来说有点不对劲。如果你试图通过元键的值来订购帖子(除非我弄错了,这就是你正在做的事情),那么我通常会使用WP_Query()

来解决这个问题。
global $wp_query;

$args = array(
  'post_type' => '[YOUR POST TYPE]', 
  'meta_key' => '_wholesale_price', 
  'orderby' => 'meta_value meta_value_num', // meta_value_num for value
  'order' => 'ASC' // or DSC for low/high
);

$wp_query - new WP_Query( $args );

if ( $wp_query->have_posts() ) {
  while ( $wp_query->have_posts() ) {
    $wp_query->the_post(); 

    // Your loop

  }
}