使用 pre_get_posts 操作对 Elementor 的 WooCommerce 产品小部件进行自定义搜索查询

Custom search query for Elementor's WooCommerce Products widget, using the pre_get_posts action

提问人:BieberFantasy 提问时间:11/13/2023 最后编辑:BieberFantasy 更新时间:11/13/2023 访问量:32

问:

我正在尝试根据帖子 ID 使用 WooCommerce 产品填充 Elementor 产品库。

Elementor 的产品和产品档案小部件不支持查询 ID(至少在我的版本中不支持),因此我正在尝试使用 Elementor 文档中用于自定义查询过滤器的替代方法:

// Hook into 'init' to check for the '/shop' endpoint
add_action('init', function() {
    if ($_SERVER['REQUEST_URI'] == '/shop') {
        if (!session_id()) {
            session_start();
        }
        // Add action to modify the main query on the 'shop' page, firing on the pre_get_posts hook
        add_action('pre_get_posts', 'modify_shop_page_query', 1);
    }
});

// Modify the main query on the '/shop' URI to display specific products
function modify_shop_page_query($query) {

    if (!is_admin() && $query->is_main_query()) {
        
        if (isset($_SESSION['searched_product_ids']) && !empty($_SESSION['searched_product_ids'])) {
            $product_ids = $_SESSION['searched_product_ids'];

            // When logging is enabled, this line proves on each request that the product ID array is correctly making it this far:
            error_log(json_encode($product_ids));
            // Example output: "[155348,162360,162444,180967,179510,163383,165519,167079]"

            $query->set('post_type', 'product');
            $query->set('post__in', $product_ids);
            $query->set('orderby', 'post__in');

        }
    }
}

Elementor 可能与 Astra 主题结合使用,不允许为 Product 和 Product Archive 小部件设置查询 ID,因为 Elementor 文档在其方法中要求这样做。但是,它确实提供了许多查询变体,包括当前查询、销售、最新产品、相关产品、手动选择等。当前查询似乎最有可能捕获“主要”查询,但产品库仅显示整个目录。这表明在更新时正在绕过或忽略它。$query

以前有人尝试过这种方法吗?可能吗?

PHP 会话 WooCommerce Elementor

评论

1赞 CBroe 11/13/2023
不确定“设置为”当前查询“的产品库应该是什么意思。听起来您可能一开始就没有针对正确的查询,...?$query->is_main_query()
0赞 BieberFantasy 11/13/2023
@CBroe Elementor,可能与 Astra 主题结合使用,不允许为 Product 和 Product Archive 小部件设置查询 ID,因为 Elementor 文档在其方法中要求。但是,它确实提供了许多查询变体,包括当前查询、销售、最新产品、相关产品、手动选择等。Current Query 似乎最有可能捕获“主要”查询,但您可能是对的。但是,如何测试这一点呢?
0赞 CBroe 11/13/2023
我会尝试将全局查询 () 转储到有问题的页面上,并检查它以查看它实际上是什么“类型”。$GLOBALS['wp_query']
0赞 BieberFantasy 11/14/2023
@CBroe,我之前也做过类似的事情,注销过。有趣的是,该数组同时位于以下位置:$query->query_varspost__in[post__in] => Array ( [0] => 155348 [1] => 162360 [2] => 162444 [3] => 180967 [4] => 179510 [5] => 163383 [6] => 165519 [7] => 167079 )
1赞 CBroe 11/14/2023
无法判断此查询的上下文是什么,如果您真的在这里定位正确的查询。我可能会安装一个插件,例如 Query Monitor,并检查为当前页面执行了哪些数据库查询。

答: 暂无答案