I’m am working on a WordPress custom template and I’m filtering post by their classes.
Since WordPress displays a LOT of unnecessary classes when I put <?php post_class(); ?>
in a page,
( here is what it gives me class="post-54 post type-post status-publish format-standard hentry category-3d category-web"
)
I’m trying to simplify that by echoing only the categories that relate to the post.
EDIT:
This is what calls the post in my page <?php query_posts( 'showposts=99' ); ?>
Then this piece of code
<li class="<?php if ( in_category('category-3d')) { echo "3d"; }
if ( in_category('category-animation')) { echo "animation"; }
if ( in_category('category-motion')) { echo "motion"; }
if ( in_category('category-shortfilm')) { echo "shortfilm"; }?>"></li>
give me this <li class="motion"></li>
if my post is in the “motion” category.
The problem is that if my post is in several categories, only the first is echoed… How can I tell WP to echo ALL the names of the categories my post is affected to, while adding a space between them?
Since I am a beginner in php syntax, I’m still learning how to get such a simple thing working in a clean and effective way (i.e. without writing 16 lines of code !)…
Can someone help me on this one?
SECOND EDIT:
Ok I’m still trying to figure out why, but today, my piece of code (above) is working and echoes all my listed classes, but without space between them… So to make my classes work, I’m adding a space at the end of the echo part like this { echo "3d "; }
. But I feel like it’s a dirty way to make things work…
How to add a space between each class tag in the proper way? I’m aiming for something like this foreach $categories as $cat { echo $cat . " "; }
but where $categories and $cat would refer to each “if” statement.
I’m not familiar with WP but if you get your categories with some function like
get_categories()
then you can use implode to make a string from all categories.Could you provide what is returning
get_categories()
?EDIT:
Also note that
3d
is not a valid class name, you can use something likemovie3d
orfilm3d
.Alternative way is to create your class value a little bit earlier and then
echo
it:As of the code you’ve posted, it should add all the categories if the product is in all the four specified ones. You could add the space between the quotes after each
echo
, e.g.:echo ' motion'
.I would use another approach, adding really all categories, without the need to check them by name:
See: http://codex.wordpress.org/Function_Reference/get_categories on how to filter the output of the function
get_categories()
.I would suggest instead you use this function from the WordPress API – something you should read a lot of.
Something like this should work: