It looks like you’re not passing the shortcode attributes to the query arguments at all. Also the arguments array structure a bit wonky. The WP_Query parameter docs is your friend when creating a custom query. Your shortcode should also return its output to show anything.
Here’s a modified version of your code that should point you in the right direction.
function common_cats($attributes){
$args = array(
'post_type' => 'post',
'posts_per_page' => ! empty($attributes['posts_per_page']) ? absint($attributes['posts_per_page']) : 5,
);
/**
* Category parameters
* @source https://developer.wordpress.org/reference/classes/wp_query/#category-parameters
*/
if ( ! empty($attributes['category']) ) {
if ( is_numeric($attributes['category']) ) {
// Category ID
$args['cat'] = absint($attributes['category']);
} else {
// Category slug
$args['category_name'] = $attributes['category'];
}
}
/**
* Tag parameters
* @source https://developer.wordpress.org/reference/classes/wp_query/#tag-parameters
*/
if ( ! empty($attributes['tag']) ) {
if ( is_numeric($attributes['tag']) ) {
// Tag ID
$args['tag_id'] = absint($attributes['tag']);
} else {
// Tag slug
$args['tag'] = $attributes['tag'];
}
}
/**
* Custom taxonomy parameters
* @source https://developer.wordpress.org/reference/classes/wp_query/#taxonomy-parameters
*/
if (
! empty($attributes['taxonomy']) &&
! empty($attributes['tax_term'])
) {
$args['term_query'] = array(
array(
'taxonomy' => $attributes['taxonomy'],
'field' => 'term_id',
'terms' => absint($attributes['tax_term']),
),
);
}
// helper variable to hold the shortcode output
$output="";
// query posts
$query = new WP_Query( $args );
// You can check for posts directly from the query posts property (array)
if ( $query->posts ) {
// Setting up the Loop is not strictly necessary here
// you can use the WP_Post properties directly
foreach ($query->posts as $post) {
$output .= sprintf(
'<a href="%s">%s</a>',
esc_url( get_permalink( $post->ID ) ),
esc_html( $post->post_title )
);
}
}
// Shortcode should return its output
return $output;
}
add_shortcode('commonposts', 'common_cats');
If you want the category, tag, and custom taxonomy term to be required parameters, you could check that they are not empty in $args
, before passing it to WP_Query
, and just return empty string, if any of them is.