2017-08-07 98 views
0

我的例如 要求 - 我有20个职位(WordPress的) - 我需要10后从升序(从自定义元键排序) - 然后我需要显示随机从已经1个员额模板页面排序(10个)的数据WordPress的排序随机数据已经排序升序

我在function.php

add_filter('the_posts', function($posts, WP_Query $query) 
{ 
    if($pick = $query->get('_shuffle_and_pick')) 
    { 
     shuffle($posts); 
     $posts = array_slice($posts, 0, (int) $pick); 
    } 
    return $posts; 
}, 10, 2); 

代码

$args =array('post_type' => 'products', 
        'posts_per_page'  => 10, 
        'meta_key' => '_showoption_', 
        'orderby' => 'meta_value', 
        'order'     => 'asc', 
        'no_found_rows'   => 'true', 
        '_shuffle_and_pick'  => 1 , 
       ); 
       $my_query = new WP_Query($args); 

我的结果:从10上升后1周后:但我需要1个随机从这个10后

回答

0

解决了这个问题,我已经加入function.php

function flatten_array($arg) 
{ 
    return is_array($arg) 
     ? 
     array_reduce($arg, function ($c, $a) 
      { 
       return array_merge($c, flatten_array($a)); 
      }, array()) 
     : 
     array($arg); 
} 

// The the_posts filter 
add_filter('the_posts', function ($posts, $q) 
{ 
    // First we need remove our filter 
    remove_filter(current_filter(), __FUNCTION__); 

    // Check if our custom parameter is set and is true, if not, bail early 
    if (true !== $q->get('wpse_custom_sort')) 
     return $posts; 

    // Before we do any work, and to avoid WSOD, make sure that the flatten_array function exists 
    if (!function_exists('flatten_array')) 
     return $posts; 

    // Our custom parameter is available and true, lets continue 
    // Loop through the posts 
    $major_array = array(); 
    foreach ($posts as $p) { 
     $meta = get_post_meta(
      $p->ID, 
      '_shuffle_and_pick', 
      true 
     ); 

     // Bail if we do not have a $meta value, just to be safe 
     if (!$meta) 
      continue; 

     // Sanitize the value 
     $meta = filter_var($meta, FILTER_SANITIZE_STRING); 

     // Lets build our array 
     $major_array[$meta][] = $p; 
    } 

    // Make sure we have a value for $major_array, if not, bail 
    if (!$major_array) 
     return $posts; 

    // Lets randomize the posts under each custom field 
    $sorted = array(); 
    foreach ($major_array as $field) 
     $sorted[] = shuffle($field); 

    // Lets flatten and return the array of posts 
    $posts = flatten_array($sorted); 

    return array_values($posts); 
}, 10, 2); 

和模板页面下面的代码

$args =array('post_type' => 'products', 
        'posts_per_page'  => 10, 
        'meta_key' => '_showoption_', 
        'wpse_custom_sort' => true, 
        'orderby' => 'meta_value', 
        'order'     => 'asc', 
        'no_found_rows'   => 'true', 
        '_shuffle_and_pick'  => 1 , 
       ); 
       $my_query = new WP_Query($args); 

源:https://wordpress.stackexchange.com/questions/226229/random-sort-within-an-already-sorted-query