wp plugin -16
Register Custom Shortcodes
shortcode 在wordpress中的作用与重要性不言而喻。主要从如下的几个方面考虑:
不同格式的shortcode
- 不同格式的shortcode: [book]
- 单模式下的shortcode,使用属性
- 闭合模式 [book 属性] content [/book]
- 多种嵌套shortcode
- 针对不同的custom type来应用 shortcode
- 在编辑器中点击即生成shortcode,即非手动嵌套shortcode
add_action( 'init', 'sanofi_register_shortcodes' );
function sanofi_register_shortcodes() {
//嵌套shortcode
add_shortcode( 'Tab', 'sanofi_get_tab' );
//单个shortcode,没有必要输入属性
add_shortcode( 'tf', 'add_twitter_feed_shortcode' );
//单模式下的shortcode,并且使用属性
add_shortcode( ‘youtube’, 'add_youtube_shortcode' );
add_shortcode( ‘url’, 'format_link_button' );
}
TIPS:一定要有$atts参数,即使它的值为空
function add_twitter_feed_shortcode' ( $atts ) {
$output = '<a href="http://twitter.com/ylefebvre">Twitter Feed</a>';
return $output;
}
//闭合模式下的链接应用
function format_link_button( $attr, $content ) {
$defaults = array(
'href' => '',
);
$sanitized_args = shortcode_atts( $defaults, $attr );
if ( !empty($sanitized_args['href']) )
{
$link_address = esc_url( $sanitized_args['href'] );
if (empty($content)){
return '<div class="link_button"><a href="'.$link_address.'">Lire la suite</a></div>';
} else {
return '<div class="link_button"><a href="'.$link_address.'">'.trim($content).'</a></div>';
}
} else {
return '';
}
}
//单模式与属性的应用
function add_youtube_shortcode( $atts ) {
extract( shortcode_atts( array(
'id' => ''
), $atts ) );
$output = '<iframe width="560" height="315" src="http://www.youtube.com/embed/' . $id . '" frameborder="0" allowfullscreen></iframe>';
return $output;
}
注意点
1.shortcode一定要有atts参数
2.enclose的shortcode一定要有content。
嵌套Shortcode
默认情况下,如果没有使用do_shortcode,嵌套shortcode是无法解析的,因此必须要使用do_shortcode
function sanofi_get_accordion($raw_args, $content=null)
{
$defaults = array(
'title' => '',
'id' => ''
);
// Unregister all shortcodes:
remove_all_shortcodes();
$sanitized_args = shortcode_atts( $defaults, $raw_args );
$result = '';
if ( !empty($raw_args['title']) )
{
$result = get_page_by_title( $sanitized_args['title'], 'OBJECT', 'Accordion' );
} else if ( !empty( $sanitized_args['id'])) {
$id = preg_replace( '/[^\d]/', '', $sanitized_args['id'] );
$result = get_page(intval($sanitized_args['id']));
} else {
return '';
}
// Sanitize content, or set default
if( !empty( $content ) ) {
$content = wp_strip_all_tags( $content );
}
add_shortcode( 'item', 'format_item' );
$show_content = do_shortcode( $result->post_content );
if ( $result )
{
return '<div class="accordion"><ul>'.$show_content.'</ul></div>';
}
}
注意(TIPS):
1. 对于嵌套的shortcode最好先remove all shortcode,然后再重新注册
2. 做好数据的过滤