I am currently using HivePress and working on creating a search results page that displays items based on tags specified by vendors. Specifically, I would like to create a page with a URL structure similar to the following example: https://example.com/vendor/kenken/?tags=music
While I have successfully created a page that specifies tags, I am stuck on how to modify the search query via code. Additionally, if there is any available code example for the tag-specified page implementation, I would appreciate it if you could share that as well.
Could you please advise on how to write the code to modify the query so that the desired behavior can be achieved?
If I understand correctly, you want to filter listings from the same vendor (on the single vendor page) by tags?
If you already created some kind of filter UI or a list of links like https://example.com/vendor/kenken/?tags=music then I recommend using pre_get_posts WordPress hook. This way you can check if it’s a query for “hp_listing” post type, and if “post_parent” is set (this means that listings are filtered by vendor), and add filter by tag if available in the URL (using $_GET parameters).
function filter_vendor_listings_by_tag($query) {
if (!is_admin() && $query->is_main_query()) {
// Apply only for 'hp_listing' query
if ($query->get('post_type') === 'hp_listing') {
// Check and get 'vendor' from $_GET
$vendor_slug = isset($_GET['vendor']) ? sanitize_text_field($_GET['vendor']) : '';
if (!empty($vendor_slug)) {
// Get the ID of 'hp_vendor'
$vendor = get_posts([
'name' => $vendor_slug,
'post_type' => 'hp_vendor',
'numberposts' => 1,
]);
if (!empty($vendor)) {
$vendor_id = $vendor[0]->ID;
// Set 'post_parent' to filter listings by a specific vendor
$query->set('post_parent', $vendor_id);
}
}
}
}
}
add_action('pre_get_posts', 'filter_vendor_listings_by_tag');
I would like to use a similar approach to filter listings by tags on the vendor’s page as well.
Could you advise how I can modify the code to make it work on the vendor page?
Please try using the same approach, just with different conditions, e.g. you can check if it’s a listing query by vendor ($query->get('post_type') is "hp_listing and $query->get('post_parent') is not empty), then add a tag condition to the tax_query. You can get it via $tax_query=$query->get('tax_query'), add conditions and then set it via $query->set('tax_query', $tax_query).