0

I want to create a shortcode to return a string of values, which are the term names. So I can use it to pass data inside a plugin. Anyone cracked this one before?

/**
 * Custom shortcode to get terms for the Formidable plugin
 */

function ALC_post_terms_by_id( $term, $atts ) {
    global $post;

    $alc_Terms = wp_get_post_terms( $post->ID, $term, 'orderby=name&hide_empty=0' );

    $term_array = array();
    foreach ($alc_Terms as $alc_Term) {
        $term_array[] = $alc_Term->name;
    }

    // $atts = shortcode_atts( $term_array() ), $atts );

    return $term_array();
}
add_shortcode( 'term_by_id', 'ALC_post_terms_by_id' );

New attempt

This is the shortcode I use:

[get_terms_by_taxonomy taxonomy="bouwjaar"]

This is the new function after suggestion in the comment by TheDeadMedic

/**
 * Custom shortcode to get terms for the Formidable plugin
 */

function ALC_post_terms_by_taxonomy( $atts ) {

    // return $atts['taxonomy'];

    $taxonomyTerms = wp_get_post_terms( $post->ID, $atts['taxonomy'], 'orderby=name&hide_empty=0' );

    $term_array = array();
    foreach ($taxonomyTerms as $taxonomyTerm) {
        $term_array[] = $taxonomyTerm->name;
    }

    return $term_array; // returns "Array"

    // return implode( ', ', $term_array );
    // implode returns "nothing"
}
add_shortcode('get_terms_by_taxonomy', 'ALC_post_terms_by_taxonomy');
3
  • 1
    Have you tried return implode( ', ', $term_array ); instead? Commented May 6, 2014 at 12:33
  • hm almost there. Tried what you suggested, but the implode returns nothing after I pass the array trough it. I'll re-edit te code above.
    – Remi
    Commented May 6, 2014 at 12:48
  • Found it. Your solution did work, I forgot to add the global $post inside the function:). Thanks for the help! Should I add the full function for future reference?
    – Remi
    Commented May 6, 2014 at 12:56

1 Answer 1

-1

This is the solution to get post terms by taxonomy by shortcode:

/**
 * Custom shortcode to get terms
 */

function ALC_post_terms_by_taxonomy( $atts ) {

    global $post;

    $taxonomyTerms = wp_get_post_terms( $post->ID, $atts['taxonomy'], 'orderby=name&hide_empty=0' );

    $term_array = array();
    foreach ($taxonomyTerms as $taxonomyTerm) {
        $term_array[] = $taxonomyTerm->name;
    }

    return implode( ', ', $term_array );
}
add_shortcode('get_terms_by_taxonomy', 'ALC_post_terms_by_taxonomy');

And you can use it by this shortcode:

[get_terms_by_taxonomy taxonomy="taxonomyname"]
1

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.