【问题标题】:WC_Product_Query return empty in functions.php but working in archive-product.phpWC_Product_Query 在functions.php 中返回空,但在archive-product.php 中工作
【发布时间】:2020-01-30 18:00:45
【问题描述】:

我正在使用 WooCommerce 3.6.5。

我需要我的functions.php文件中的所有变量产品,因此我想在我的functions.php文件中使用WC_Product_Query,但它总是返回空数据。但是在 WooCommerce 模板文件 (archive-product.php) 中工作的相同代码并返回正确的数据。

这是我的代码

$query = new WC_Product_Query(array(
            'limit'=>-1,
            'type' => 'variable',
            'return' => 'ids'
        ));
        $variableproducts = $query->get_products();
        echo '<pre>';
echo 'print from functions.php';
print_r($variableproducts);
echo '</pre>';

谁能帮助我为什么WC_Product_Query 类在functions.php 中没有返回正确的数据,或者有没有其他方法可以在functions.php 文件中获取所有可变产品ID?

【问题讨论】:

    标签: php wordpress woocommerce e-commerce product


    【解决方案1】:

    这是使用 wc_get_products 的另一种方法:

    $args = array(
    'type' => 'variable',
    'limit' => -1,
    'return' => 'ids',
    );
    $variable_products_ids = wc_get_products( $args );
    

    您的代码也应该可以工作。问题可能是您正在使用的钩子。你也应该调试它。 此代码将所有变量 id 添加到所有帖子内容。

    add_filter('the_content' , function ($cnt){
        $args = array(
    'type' => 'variable',
    'limit' => -1,
    'return' => 'ids',
    );
    $variable_products_ids = wc_get_products( $args );
    $str = '';
    foreach($variable_products_ids as $id){
        $str .= $id . ' ';
    }
    return $cnt .' '. $str;
    }
    );
    

    【讨论】:

    • 我也试过 wc_get_products,但结果是一样的。
    猜你喜欢
    • 2013-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-14
    • 1970-01-01
    相关资源
    最近更新 更多