提问人:BieberFantasy 提问时间:11/13/2023 最后编辑:BieberFantasy 更新时间:11/13/2023 访问量:32
使用 pre_get_posts 操作对 Elementor 的 WooCommerce 产品小部件进行自定义搜索查询
Custom search query for Elementor's WooCommerce Products widget, using the pre_get_posts action
问:
我正在尝试根据帖子 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
以前有人尝试过这种方法吗?可能吗?
答: 暂无答案
评论
$query->is_main_query()
$GLOBALS['wp_query']
$query->query_vars
post__in
[post__in] => Array ( [0] => 155348 [1] => 162360 [2] => 162444 [3] => 180967 [4] => 179510 [5] => 163383 [6] => 165519 [7] => 167079 )