我有这段代码,
add_shortcode( 'parent-child', 'taxonomy_hierarchy' );
function taxonomy_hierarchy( $atts ){
extract( shortcode_atts( array(
'link' => true,
'taxonomy' => 'property_city'
), $atts, 'parent-child' ) );
global $post;
$terms = wp_get_post_terms( $post->ID, $taxonomy );
/* You can pass conditions here to override
* $link based on certain conditions. If it's
* a single post, current user is editor, etc.
*/
ob_start();
foreach( $terms as $term ){
if( $term->parent != 0 ){
$parent_term = get_term( $term->parent, $taxonomy );
echo ($link != false) ? sprintf( '%s, ', esc_url( get_term_link($parent_term) ), $parent_term->name ) : "{$parent_term->name}, " ;
}
echo ($link != false) ? sprintf( '%s', esc_url( get_term_link($term) ), $term->name ) : $term->name ;
}
return ob_get_clean();
}这将允许您获得以下结果:
**[parent-child]**
• New York
• New York, Manhattan
**[parent-child link="true"]**
• New York
• New York, Manhattan
**[parent-child link="false"]**
• New York
• New York, Manhattan
[parent-child link="false" taxonomy="some_other_taxonomy"]
• Top Level Term
• Top Level Term, Child Level Term一切正常工作,并显示如预期!just...my参数不起作用。
我没能得到的工作。在我研究短代码如何工作的过程中,我偶然发现了这些帖子,
他们都说永远不要在短代码中使用<#>提取和echo --这在wordpress代码中是非常糟糕的做法,而使用$atts和$ bad 是非常糟糕的做法。
这让人怀疑这段代码的有效性..。
My现在的问题是:如何使这个短代码与链接=false一起工作,并且在短代码中没有提取和回显。
如果您understood我所说的并且知道如何使它更符合wordpress标准,谢谢!
发布于 2021-01-07 15:42:25
如何使这个短代码与link=false一起工作,并且在短代码中没有提取。
您永远不能将布尔值作为短代码参数传递,而应该将其视为字符串。您对param link值false的比较应该用作'false' (string)。
add_shortcode( 'parent-child', 'taxonomy_hierarchy' );
function taxonomy_hierarchy( $atts ){
// Don't extract, rather parse shortcode params with defaults.
$atts = shortcode_atts( array(
'link' => 'true',
'taxonomy' => 'property_city'
), $atts, 'parent-child' );
// Check the $atts parameters and their typecasting.
var_dump( $atts );
global $post;
$terms = wp_get_post_terms( $post->ID, $atts['taxonomy'] );
/* You can pass conditions here to override
* $link based on certain conditions. If it's
* a single post, current user is editor, etc.
*/
ob_start();
foreach( $terms as $term ){
if( $term->parent != 0 ){
$parent_term = get_term( $term->parent, $taxonomy );
if ($atts['link'] !== 'false') {
printf( '%s, ', esc_url( get_term_link($parent_term) ), $parent_term->name );
} else {
echo $parent_term->name . ', ';
}
}
if ($atts['link'] !== 'false') {
printf( '%s', esc_url( get_term_link($term) ), $term->name );
} else {
echo $term->name;
}
}
return ob_get_clean();
}在短代码中没有回波
这不是关于使用echo,而是要求您不要在短代码中回显输出。相反,您应该返回它,因为WordPress将用您的输出值替换短代码。在这里,您正在使用ob_start()和ob_get_clean()函数缓冲输出并返回它。这很好,也是常用的技术。
https://wordpress.stackexchange.com/questions/381091
复制相似问题