I am using WordPress’s default Gallery and adding categories to them. I now created a shortcode with a loop to get the Galleries to a page:
if(! function_exists('test_shortcode')){
function lv_gallery_style_one_shortcode($atts, $content = null){
extract(shortcode_atts( array(
'title'=>'',
), $atts) );
$port=array('post_type' => 'gallery', 'category_name' => 'beach', 'showposts' => -1 );
$loop=new WP_Query($port);
while ( $loop->have_posts() ) : $loop->the_post();
// HERE IS THE LOOP
return $html;
}
add_shortcode('gallery_test', 'test_shortcode' );
I know that the loop worked just fine because when I remove 'category_name' => 'beach'
it displays all the categories.
—————EDIT:—————–
The Gallery I am using has the following icon and option:
I thought this is the standard WP gallery, am I wrong?
When I create a new Gallery, there is a Category section on the right side:
What is this used for if I cannot use them? I don’t understand.
—————End EDIT:————-
This is just an example code. In the complete version, the category name will be a parameter to enter in the shortcode, that is why I would like to do it like this.
Any ideas on how to get this to work?
Any suggestions are appreciated :).
Thanks.
2 Answers
What I suspect is that those Gallery Categories
are not the category
taxonomy. They are probably a registered taxonomy, registered by the same script which added the gallery post type.
To find out, click on the Gallery Categories
( in the provided image ) and you will be redirected to a URL such as this:
http://example.com/wp-admin/edit-tags.php?taxonomy=my-taxonomy&post_type=gallery
Check the taxonomy
argument. If it is anything other than category
, then you are on a custom taxonomy, and you need to add a tax_query
to your WP_Query
. Here’s how to do it:
Your args would simply change from this:
$port=array('post_type' => 'gallery', 'category_name' => 'beach', 'showposts' => -1 );
To this:
$port = array(
'post_type' => 'gallery',
'showposts' => -1,
'tax_query' => array (
array(
'taxonomy' => 'my-taxonomy',
'field' => 'slug',
'terms' => 'beach',
)
)
);
Side Note:
Make sure you use wp_reset_postdata();
just before the return $html;
. This will reset the query and makes sure your shortcode won’t affect any other queries in the page.
All done.