wordpress 通过WP_Query中的menu_order对特定的Woocommerce产品变体进行排序

nzrxty8p  于 2022-11-22  发布在  WordPress
关注(0)|答案(1)|浏览(115)

我有一个WP_Query来拉和显示一个由全局属性过滤的WooCommerce产品变体列表。这是可行的,但我想通过'menu_order'自定义排序结果。
但这对'post_type' => 'product_variation'不起作用。可能是因为'menu_order'是在产品级别上设置的。('post_type' => 'product'确实起作用,但我需要变体)

$wc_query_params = array(
     'post_type' => 'product_variation',
     'posts_per_page' => -1,
     'numberposts'   => -1,
     'post_status'   => 'publish',
     'meta_query'     => array(array(
         //filter variations on attribute name
         'key'  => 'attribute_pa_color',
         'value'     => 'blue', 
     )),
     'order'         => 'ASC',
     'orderby'       => 'menu_order',
 );
 $wc_query = new WP_Query($wc_query_params);

 if ($wc_query->have_posts()) :
     while ($wc_query->have_posts()) :
         $wc_query->the_post();

     //results

     endwhile;
     wp_reset_postdata();
 endif;

是否有一种方法可以根据父产品'menu_order'对产品变体进行排序?或者是否有其他方法可以对产品变体进行自定义排序?

e0bqpujr

e0bqpujr1#

使用the answer from this question,我设法在与父变量产品相同的menu_order中显示产品变量。

  • 注意:此代码还按产品类别(我需要的)筛选结果。*

在下面的函数中,我添加了ORDER by p.menu_order,以便按照menu_order对变体父id进行排序。

function get_variation_parent_ids_from_term( $term, $taxonomy, $type ){
global $wpdb;

return $wpdb->get_col( "
    SELECT DISTINCT p.ID
    FROM {$wpdb->prefix}posts as p
    INNER JOIN {$wpdb->prefix}posts as p2 ON p2.post_parent = p.ID
    INNER JOIN {$wpdb->prefix}term_relationships as tr ON p.ID = tr.object_id
    INNER JOIN {$wpdb->prefix}term_taxonomy as tt ON tr.term_taxonomy_id = tt.term_taxonomy_id
    INNER JOIN {$wpdb->prefix}terms as t ON tt.term_id = t.term_id
    WHERE p.post_type = 'product'
    AND p.post_status = 'publish'
    AND p2.post_status = 'publish'
    AND tt.taxonomy = '$taxonomy'
    AND t.$type = '$term'
    ORDER by p.menu_order 
" );
}

我使用这个排序顺序按父产品对product_variations进行排序。使用'orderby' => 'post_parent__in'使用post_parent__in中给出的相同顺序。

$cat_name = 't-shirt';  // Product category name

$wc_query = new WP_Query( array(
    'post_type'      => 'product_variation',
    'posts_per_page' => -1,
    'numberposts'    => -1,
    'post_status'    => 'publish',
    'meta_query'     => array( array(
        'key'   => 'attribute_pa_color',
        'value' => 'blue', 
    ) ),
    'post_parent__in' => get_variation_parent_ids_from_term( $cat_name, 'product_cat', 'name' ), 
    'orderby'         => 'post_parent__in', //orderby = same order as their parent products
) );

也许对其他人有用。

相关问题