【问题标题】:Make Featured column sortable in Woocommerce admin products list在 Woocommerce 管理产品列表中使特色列可排序
【发布时间】:2020-08-28 00:54:33
【问题描述】:

在产品列表上的 WooCommerce 后端,我们可以通过点击星号来制作特色产品。

但是,如果您有很多产品,并且您想在之后查看哪些产品有特色,我们必须搜索所有产品。

所以我想让这个列可排序,以便在排序过程中所有特色产品都显示在前面或后面

使用我目前的代码,可以对列进行排序,但是排序过程中结果为空,导致结果为0

// 'featured' column sortable on the 'product' page
function sc_sortable_column( $columns ) {
     $columns['featured'] = 'featured';

     return $columns;
}
add_filter( 'manage_edit-product_sortable_columns', 'sc_sortable_column' );


// Orderby 'featured' (product)
function filter_pre_get_posts( $query ) {
     if( ! is_admin() )
         return;

     $orderby = $query->get('orderby');

     // featured, product
     if( $orderby == 'featured') {
         $query->set( 'meta_key', '_featured' );
         $query->set( 'orderby', 'meta_value_num' );
     }
}
add_action( 'pre_get_posts', 'filter_pre_get_posts' );

【问题讨论】:

  • @LoicTheAztec 好的

标签: php wordpress woocommerce product custom-taxonomy


【解决方案1】:

自 WooCommerce 3 以来,特色产品现在由 product_visibility 自定义分类法处理,用于术语 featured。见:Get WooCommerce featured products in a WP_Query

通常分类法不允许对帖子进行排序,如以下 WordPress 开发 StackExchange 线程中所述:Using wp_query is it possible to orderby taxonomy?

但例如使用过滤器posts_clauses 可以按特色对产品进行排序。

所以要使用的代码是:

// Make Product "Featured" column sortable on Admin products list
add_filter( 'manage_edit-product_sortable_columns', 'products_featured_sortable_column' );
function products_featured_sortable_column( $columns ) {
     $columns['featured'] = 'featured';

     return $columns;
}

add_filter('posts_clauses', 'orderby_product_visibility', 10, 2 );
function orderby_product_visibility( $clauses, $wp_query ) {
    global $wpdb;

    $taxonomy  = 'product_visibility';
    $term      = 'featured';

    if ( isset( $wp_query->query['orderby'] ) && $term == $wp_query->query['orderby'] ) {
        $clauses['join'] .=<<<SQL
LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id
LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id)
LEFT OUTER JOIN {$wpdb->terms} USING (term_id)
SQL;
        $clauses['where']   .= " AND (taxonomy = '{$taxonomy}' OR taxonomy IS NULL)";
        $clauses['groupby']  = "object_id";
        $clauses['orderby']  = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) ";
        $clauses['orderby'] .= ( 'ASC' == strtoupper( $wp_query->get('order') ) ) ? 'ASC' : 'DESC';
    }
    return $clauses;
}

代码在您的活动子主题(或活动主题)的functions.php 文件中。经过测试和工作。

【讨论】:

  • 感谢您的回答,这很好用。可以说,差不多。分类时,特色产品确实显示在顶部或底部。但是,并非所有产品都在排序期间显示。例如,显示缺货(非特色)的可变产品。如果它们有库存,它们将不会在分拣过程中显示。我已禁用除 woocommerce 以外的所有插件,但问题仍然存在。我不知道这个问题是否与缺货或缺货有关。
  • 根本不起作用。是的,它使特色列可排序,但不按特色排序,而且还会出现不需要的过滤。
猜你喜欢
  • 2019-06-23
  • 2022-01-24
  • 2019-06-28
  • 1970-01-01
  • 1970-01-01
  • 2019-03-12
  • 1970-01-01
  • 2020-06-18
  • 1970-01-01
相关资源
最近更新 更多