I’m not quite sure what you want to do as frankly, your terminology is a bit scrambled, and you example shortcode is also quite a mess.
Before I start, you should start of by checking the following very important links
You should first start of by defining your attributes (and their defaults) which you need to use and pass to the shortcode. From your example, you can do something like this
$a = shortcode_atts(
array(
'posts_per_page' => 2,
'post_type' => 'product',
'taxonomy' => 'product_brand',
'term_id' => '',
'term_name' => '',
'term_slug' => '',
// Rest of attributes required
),
$atts );
You can set as many attributes as needed to suite your needs. From what I can understand, you want to pass either the term name or id to the shortcode, so I have set up the attributes accordingly. I have included the slug as well. To keep the shortcode dynamic, it will be best not to hardcode your arguments for the query. Set them as attributes with a default value. If you need to reuse the shortcode for another taxonomy or post type, you can change the values through the attributes passed
The next thing what you need to do is to adjust your tax_query
according to the term value passed in order to set the correct field
value. For this, you can try a condition like this
$term_id = $a['term_id'];
$term_name = $a['term_name'];
$term_slug = $a['term_slug'];
if ( $term_id ) {
$terms = $term_id;
$field = 'term_id';
} elseif ( $term_name ) {
$terms = $term_name;
$field = 'name';
} elseif ( $term_slug ) {
$terms = $term_slug;
$field = 'slug';
}
You can now just pass $terms
and $field
to your tax_query
'tax_query' => array(
array(
'taxonomy' => $a['taxonomy'],
'field' => $field,
'terms' => $terms,
'include_children' => false
)
),
You can now pass the term id, name or slug as required in your shortcode as follows
[my_shortcode posts_per_page="3" term_id=3]
Or
[my_shortcode posts_per_page="3" term_name="My term name"]
Or
[my_shortcode posts_per_page="3" term_slug='my-term-slug']
A FEW NOTES
-
This is a just a skeleton to set you on your way. Expand and abuse it as needed
-
You would want to sanitize and validate data coming from your attributes accordingly to avoid possible bugs, unexpected output and security loopholes. For instance, you would maybe first check if you have a term value and then checking if that term actually exists before passing it as an argument and building your query.