Support

Account

Home Forums General Issues Issue displaying taxonomies names and links: not a string?

Solved

Issue displaying taxonomies names and links: not a string?

  • Hello, I am trying to display a simple list of custom taxonomies in my post via shortcode, but I get this warning:
    ltrim() expects parameter 1 to be string, object given

    In the backend i created an ACF form with Taxonomy field; main settings:
    name: custom_tax_fieldname
    appearance: checkboxes
    save terms: yes
    return value: term object

    In my php I added this code, borrowed and adapted from the documentation: https://www.advancedcustomfields.com/resources/taxonomy/

    $custom_taxonomies = get_field('custom_tax_fieldname');
    if( $custom_taxonomies ) {
    	foreach( $custom_taxonomies as $custom_taxonomy ){
            echo "<a href='" . esc_url( get_term_link( $custom_taxonomy ) ) . "'>" . esc_html( $custom_taxonomy->name ) . "</a>";
    		if (next( $custom_taxonomies )) {echo ', ';} 
     }
    }

    but I get this warning multiple times (one for every taxonomy I am supposed to see): Warning: ltrim() expects parameter 1 to be string, object given in home/wp-includes/formatting.php on line 4309

    I don’t know what am I doing wrong, can someone help?
    Thank you very much in advance

  • Update:
    if I try to echo only my term name it appers completely empty,
    if I try to echo only my term link, the warning “ltrim() expects parameter 1 to be string” appears

  • For anyone who needs it, my error was that I had to use
    get_term_link(term-slug, taxonomy-slug) with the term slug and the taxonomy slug, while I was using the ID and did not use the taxonomy slug.

    So the final code I used is:

    $terms = get_field('acf_tax_fieldname');
    if( $terms ) {
         foreach( $terms as $term ) {
    		 $term_name = get_term( $term )->name;
    		 $term_slug = get_term( $term )->slug;
    		 $term_link = get_term_link( $term_slug , 'wp_tax_slug' );
    		 echo "<a href='" . $term_link . "'>" . $term_name . "</a>";
    	}    
    }
Viewing 3 posts - 1 through 3 (of 3 total)

You must be logged in to reply to this topic.