How do I go about making custom query filter posts by current tag?

[ad_1]

Hi everyone, I would like to create a custom query that filters posts by current tag.

So I’ve got 2 custom post types (therapists and services) and on each service page I would like to show the therapists that provide said service. So I wanted to add matching tag to both therapist and service and filter the posts by this tag. Because there are loads of services and therapists, I created a template that applies to each service page, that’s why getting posts with current tag would be the best option in my opinion.

For the minute I do have a custom query that filters posts by current category:

add\_action( ‘elementor/query/km\_specialists\_query’, function( $query ) {

//get ID of current post

$id = get\_queried\_object\_id();

// get current taxonomy – in this case the category

$tax = get\_the\_terms( $id, ‘category’);

​

$tax\_query = array(

array(

‘taxonomy’ => ‘category’,

‘field’ => ‘slug’,

‘terms’ => $tax\[0\]->slug,

),

);

​

$query->set( ‘tax\_query’, $tax\_query );

​

} );

[ad_2]
1 Comment
  1. [https://wordpress.stackexchange.com/questions/278128/wp-query-related-posts-by-current-page-tag-id])

 

This site will teach you how to build a WordPress website for beginners. We will cover everything from installing WordPress to adding pages, posts, and images to your site. You will learn how to customize your site with themes and plugins, as well as how to market your site online.

Buy WordPress Transfer