How to display posts that are common in Category A and Tag A, and I want to display posts by shortcode so that the Shortcode can be used on multiple locations with different category Ids and Tags.
I found the below code by google but don’t know how to implement it in functions.php and not sure how to use it in the shortcode. I want to display Post Title, And Some Custom Field Value [For Example – Value A, Value B] in a table structure.
$args = array(
'category__and' => 'category', //must use category id for this field
'tag__in' => 'post_tag', //must use tag id for this field
'posts_per_page' => -1); //get all posts
$posts = get_posts($args);
foreach ($posts as $post) :
//do stuff
endforeach;```
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
function common_cats($att){
$args = array(
'category__and' => $att['category'], //must use category id
'tag__in' => $att['tag'], //must use tag id for this field
'posts_per_page' => $att['posts_per_page']); //get all posts
$posts = get_posts($args);
$output = "<ul>";
foreach ($posts as $post) :
$output .= "<li>".get_the_title(). "</li>";
endforeach;
$output .= "</ul>";
return $output;
}
add_shortcode('commoncats', 'common_cats');
use [commoncats] where you like to show the output of the above code.
above code will return a list of titles.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0