php - 按 WP_Query 中的自定义 Woocommerce 产品排序排序

标签 php wordpress sorting woocommerce product

我已经创建了一个短代码来使用以下查询按类别显示产品:

$atts = shortcode_atts( array (
        'type' => 'product',
        'posts' => -1,
        'category' => '',
    ), $atts, 'list_products' );

    $query = new WP_Query( array(
        'post_type' => $atts['type'],
        'posts_per_page' => $atts['posts'],
        'tax_query' => array( array(
             'taxonomy' => 'product_cat',
             'field' => 'slug',
             'terms' => $atts['category'],
        ) ),
    ) );

这一切都很好,但是当我使用自定义排序对产品进行排序时,我试图使用属性排序 shown here

我添加了:'orderby' => 'modified',尝试了 here 中的一些其他内容.

两个问题:

使用自定义排序需要使用哪个属性来排序

添加到上述查询后,我需要做什么才能使我的 orderby 属性起作用?因为无论我使用哪个属性值,它总是按发布的降序排序。

最佳答案

当您对 Woocommerce 产品使用自定义排序时,它会在 menu_order 列下的 wp_posts 数据库表中为每个产品设置一些值。

然后你只需要在你的 WP_Query 中添加 'orderby' => 'menu_order',,所以在你的代码中:

$atts = shortcode_atts( array (
    'type' => 'product',
    'posts' => -1,
    'category' => '',
), $atts, 'list_products' );

$query = new WP_Query( array(
    'post_type'      => $atts['type'],
    'posts_per_page' => $atts['posts'],
    'tax_query' => array( array(
         'taxonomy'  => 'product_cat',
         'field'     => 'slug',
         'terms'     => $atts['category'],
    ) ),
    'orderby'        => 'menu_order',
    // 'order'          => 'DESC',
) );

它将起作用(默认情况下 order 排序参数通常设置为 ASC)

关于php - 按 WP_Query 中的自定义 Woocommerce 产品排序排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50937078/

相关文章:

php - 尝试在大于和小于 mysql 表 php 内部时创建查询

php - 在 MySQL 查询中添加 PHP 变量的正确方法?

java - 在我的 quickSort 算法 java 中更改枢轴

c++ - 同一类中的多个 Operator() 重载

javascript - React dropzone 似乎没有将文件发送到我的 PHP 端点

php - WooCommerce 预购插件

wordpress - 模板如何在 WordPress 上工作?

mysql - 在 zend server 8.0 上设置 wordpress

php - 如何将变体库存状态添加到 Woocommerce 产品变体下拉列表

java - 通过 ArrayList 对象中的特定值对 ArrayList 进行排序?