I try to order result by custom field value when I use this:
// Search product distance
foreach( $productArrayShop as $id ) {
$pdistance = $product_obj['current_distance']=get_post_meta($id,'current_distance');
echo ' Distance = '.$pdistance[0].', ';
$arrayDistance[] = $pdistance[0];
}
//echo '<b> Founded '.count($arrayDistance).' distance</b> ';
// Orderby distance
foreach ($arrayDistance as $d)
{
$productd = array
(
'post_type' => 'product',
'posts_per_page'=> -1,
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_key' => 'current_distance',
'fields' => 'ids',
'meta_query' => array
(
array(
'key' => 'current_distance',
'value' => $d,
'type' => 'NUMERIC',
'compare'=> '<'
)
)
);
//Get product id
$product_post = get_posts($productd);
//echo $product_post[0].', ';
//echo count($product_post);
$a[] = $product_post[0];
}
//echo ' Founded '.count($a).' ID';
$resultD = implode(",", $a);
echo ' ID of product '.$resultD.', ';
Result is: Distance = 62.717, Distance = 726.727, ID of product yes,81322,81322 and only first product appear on screen, make sense because same ID... I don't understand why.
the dump of
$a[]: array(3) { ["map"]=> string(3) "yes" [0]=> int(81322) [1]=> int(81322) }
Why I have two same ID 81322,81322 ?
If I don't use query ordering, my two product appear (not ordered of course) on screen.
When I trace :
foreach ( $productArrayShop as $id ) {
$pdistance = $product_obj['current_distance']=get_post_meta($id,'current_distance');
echo ' Distance = '.$pdistance[0].', ';
$arrayDistance[] = $pdistance[0];
}
I have 2 distance of my 2 products.
The working code is :
$productd = array(
'post_type' => 'product',
'posts_per_page'=> -1,
'order' => 'ASC',
'orderby' => 'meta_value',
'meta_key' => 'current_distance',
'post__in' => $productArrayShop // Here we get all the posts by the IDs with the right order.
);
$product_post = get_posts($productd);
foreach($product_post as $p) {
$arrp[] = $p->ID;
}
$result = implode(",", $arrp);
echo ' ID of product '.$result.', ';
// View list of product based on road distance of user position
echo do_shortcode('[products ids="' . $result . '" per_page="8" columns="4" pagination="true" orderby="meta_value" order="ASC"]');
Thanks to @Shibi to help me a lot !