WP - get_template_part 基于匹配的分类术语
WP - get_template_part based on matching taxonomy term(s)
我正在尝试根据分配给 post.
的自定义分类术语显示一些片段(通过 get_template_part() 加载)
到目前为止,我可以使用
获得分配给 post 的分类术语
$term_list = wp_get_post_terms($post->ID, 'sidebar_snippets', array("fields" => "all"));
print_r($term_list);
这会生成一个对象数组,如下所示:
(
[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
)
)
我正在考虑迭代一组指定的术语并加载适当的片段。片段的名称与分类术语 'slug' 相同。
$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' );
}
我有两个问题。一个是它甚至不输出 $term[slug]。其次,我将如何添加一些验证,例如。在尝试 get_template_part?
之前先检查文件是否存在
谢谢
您正在尝试以数组形式访问对象值,因此它不会回显该值。正确使用以下代码回显。
foreach($term_list as $key => $term) {
$term_slug = $term->slug; // does not out put anything.
get_template_part( 'modules/'.$term_slug.'.php' );
}
如需更多帮助,请参阅此 link:Click Here
谢谢
我正在尝试根据分配给 post.
的自定义分类术语显示一些片段(通过 get_template_part() 加载)到目前为止,我可以使用
获得分配给 post 的分类术语$term_list = wp_get_post_terms($post->ID, 'sidebar_snippets', array("fields" => "all"));
print_r($term_list);
这会生成一个对象数组,如下所示:
(
[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
)
)
我正在考虑迭代一组指定的术语并加载适当的片段。片段的名称与分类术语 'slug' 相同。
$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' );
}
我有两个问题。一个是它甚至不输出 $term[slug]。其次,我将如何添加一些验证,例如。在尝试 get_template_part?
之前先检查文件是否存在谢谢
您正在尝试以数组形式访问对象值,因此它不会回显该值。正确使用以下代码回显。
foreach($term_list as $key => $term) {
$term_slug = $term->slug; // does not out put anything.
get_template_part( 'modules/'.$term_slug.'.php' );
}
如需更多帮助,请参阅此 link:Click Here 谢谢