0
votes

I'm trying to display some snippets (loaded via get_template_part()) based on a custom taxonomy terms assigned to a post.

So far I can get taxonomy terms assigned to the post with

$term_list = wp_get_post_terms($post->ID, 'sidebar_snippets', array("fields" => "all"));
print_r($term_list);

Which produces an array of objects like that:

(
    [0] => WP_Term Object
        (
            [term_id] => 11
            [name] => Future Events
            [slug] => future_events
            [term_group] => 0
            [term_taxonomy_id] => 11
            [taxonomy] => sidebar_snippets
            [description] => 
            [parent] => 0
            [count] => 2
            [filter] => raw
        )

)

I was thinking of iterating over an array of assigned terms and load the appropriate snippets. The snippets' names are identical with the 'slug' of taxonomy term.

$term_list = wp_get_post_terms($post->ID, 'sidebar_modules', array("fields" => "all"));
print_r($term_list);  // works fine - outputs three terms (like above)

foreach($term_list as $term) {
  echo $term['slug']; // does not out put anything.
  get_template_part( 'modules/' . $term['slug]  . '.php' );
}

I have two problems. One that it doesn't not even output the $term[slug]. Secondly, how would I add some validation, eg. check if the file exists first before trying to get_template_part?

Thank you

1

1 Answers

1
votes

You are trying to access object value as array so it not echo the value. Use the below code for echo correctly.

foreach($term_list as $key => $term) {
  $term_slug =  $term->slug; // does not out put anything.
  get_template_part( 'modules/'.$term_slug.'.php' );
}

For more help see this link : Click Here Thanks