1

I am using the following code to display my custom taxonomy slugs. However it is only displaying the first category and not all the related categories. I know this is fairly simple and is to do with [0] but I can't figure out how to change it.

$getslugid = wp_get_post_terms( $post->ID, 'opd_taggallery' ); 
$getslug = $getslugid [0]->slug;
echo $getslug;

3 Answers 3

4

This is more of a PHP question, but the solution is simple - you need to use a foreach-loop on $getslug, because you just echo the slug of the first taxonomy.

The function wp_get_post_terms() does not return a single object, but an array of objects. You are right with the [0], this indicates that you are checking the first entry of said array.

Your function should look something like this:

$getslugid = wp_get_post_terms( $post->ID, 'opd_taggallery' ); 
foreach( $getslugid as $thisslug ) {

    echo $thisslug->slug . ' '; // Added a space between the slugs with . ' '

}
0
6

The WordPres Core function wp_list_pluck() should make this fairly easy.

$getslugid = wp_get_post_terms( $post->ID, 'opd_taggallery' ); 
$slugs = implode(', ',wp_list_pluck($getslugid,'slug'));
echo $slugs;
4
  • +1, did not even know about this function. As it also uses the foreach (talking performance), I still prefer my solution, as I have fine control and could use multiple fields of the object.
    – fischi
    Commented Mar 14, 2014 at 17:57
  • Yes, performance wise... probably not much difference. It is just a convenient shortcut if you only need one value.
    – s_ha_dum
    Commented Mar 14, 2014 at 18:21
  • 1
    @s_ha_dum Didn't know about wp_list_pluck(), thank you.
    – Nypam
    Commented Aug 27, 2017 at 8:31
  • @s_ha_dum Same. Haven't heard about this function wp_list_pluck. Life saving :)
    – melvin
    Commented Jul 5, 2019 at 12:18
1

In newer WordPress versions it is possible to directly query only the taxonomy slugs. I think this came with the introduction of the WP_Term_Query class in WP version 4.6.0.

$slugs = wp_get_post_terms( $post->ID, 'opd_taggallery', array( 
    'fields' => 'id=>slug',
) );
echo implode( " ", $slugs );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.