首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >WooCommerce woocommerce_product_query获取IDS

WooCommerce woocommerce_product_query获取IDS
EN

Stack Overflow用户
提问于 2020-05-05 17:51:37
回答 1查看 641关注 0票数 1

我正在尝试获取'woocommerce_product_query‘钩子内的WooCommerce主查询的IDS

我试着做这样的事情

代码语言:javascript
复制
add_action( 'woocommerce_product_query', 'custom_get_IDS' );
function custom_get_IDS( $q ) {
    if($q->have_posts()){
        while($q->have_posts()){
            $q->the_post();
            //get the id
            echo 'print the ID';
        }
    } else {
        echo 'no posts';
    }
}

但是这个打印总是“无帖子”,即使页面循环有2个产品。

如果我这样做了

代码语言:javascript
复制
print_r($q);

我得到了具有所有查询设置的WP_Query对象,例如

代码语言:javascript
复制
[query] => Array
    (
        [s] => my_query_word
        [post_type] => product
        [lang] => en
    )

[query_vars] => Array
    (
        [s] => my_query_word
        [post_type] => product
        [lang] => en
        [error] => 
        [m] => 
        [p] => 0
        [post_parent] => 
etc etc etc

如何在woocommerce_product_query钩子中获取$q查询的I?

我必须在woocommerce_product_query钩子中执行此操作。

EN

回答 1

Stack Overflow用户

发布于 2020-05-06 04:16:32

不推荐这样做,但这可能会得到您想要的输出。

代码语言:javascript
复制
add_action( 'woocommerce_product_query', 'custom_get_IDS' );

function custom_get_IDS( $q ) {
    remove_action( 'woocommerce_product_query', 'custom_get_IDS' );

    $posts = $q->get_posts();
    if ( $posts ) {
        foreach ( $posts as $post ) {
            //get the id
            echo 'print the ID=' . $post->ID;
        }
    } else {
        echo 'no posts';
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61610299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档