Search code examples
phpwordpressshortcodecustom-taxonomy

Shortcode meant to output custom taxonomy instead outputting the word 'array'


Attempting to output a custom post type taxonomy (property_type) as a shortcode. At the moment where it should output the taxonomy it simply outputs the word Array. Quite new to php, so possibly something simple I'm missing, or completely barking up the wrong tree.

Code is:

function prop_type_shortcode() { 

 $terms = wp_get_post_terms($post->ID, 'property_type');
    if ($terms) {
        $out = array();
        foreach ($terms as $term) {
            $out[] = '<a class="' .$term->slug .'" href="' .get_term_link( $term->slug, 'property_type') .'">' .$term->name .'</a>';
        }
        echo join( ', ', $out );
    } 
    
 

return $terms;
} 

add_shortcode('type', 'prop_type_shortcode');

Thanks in advance for any help.


Solution

  • You are returning the array from wp_get_post_terms(). Instead you should be returning your processed text.

    function prop_type_shortcode() {
        global $post;
    
        $terms = wp_get_post_terms($post->ID, 'property_type');
    
        if (!$terms) {
            return '';
        }
    
         $out = array();
    
         foreach ($terms as $term) {
            $out[] = '<a class="' .$term->slug .'" href="' .get_term_link( $term->slug, 'property_type') .'">' .$term->name .'</a>';
         }
    
        return join( ', ', $out );
    }