【问题标题】:WooCommerce woocommerce_product_query get IDSWooCommerce woocommerce_product_query 获取 IDS
【发布时间】:2020-05-05 09:51:36
【问题描述】:

我正在尝试在钩子“woocommerce_product_query”中获取 WooCommerce 主查询的 IDS

我试图做这样的事情

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 个产品,此打印始终“无帖子”。

如果我这样做了

print_r($q);

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

[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 Query 的 IDS?

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

【问题讨论】:

  • 钩子 woocommerce_product_query 用于操作现有的 WooCommerce 产品查询,但不能在其中设置查询循环……请参阅带有此钩子的 some StackOverFlow existing examples……
  • 动作“woocommerce_product_query”的问题在于它是从 WordPress 动作“pre_get_posts”调用的,这意味着此时查询尚未完成,这意味着 $q 没有帖子。

标签: php wordpress woocommerce hook-woocommerce


【解决方案1】:

不建议这样做,但这可能会为您提供所需的输出。

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';
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-07-17
    • 2019-09-11
    • 1970-01-01
    • 2021-01-10
    • 2020-02-07
    • 1970-01-01
    • 2022-01-06
    相关资源
    最近更新 更多