wordpress 输出友情链接短代码 并配置 文本小工具支持插入shortcode

php 3年前 (2021) 筑路邦
788 0

有一些主题对友情链接的支持不太好,很多时候都使用的是手动插入html . 这不免有些麻烦。

可以通过下面代码对主题进行改造,让友链管理更方便。

下面代码只保留href剔除掉了ul、li标签,需要的可以自行添加。分享的这种方法要比直接使用 wp_list_bookmarks 更方便。

// 启用WP链接 
add_filter( 'pre_option_link_manager_enabled', '__return_true' );

// 文本工具支持短代码
// add_filter('widget_text', 'do_shortcode');

// 友链短代码
// 用法:短代码 [xm_link cat=0] 插入到 widget文本小工具

add_shortcode( 'xm_link ', 'output_link' );

function output_link( $atts){
    $atts = shortcode_atts( array(        'cat' => 0    ), $atts );    
    $args = array(
     'limit' => -1,//显示链接的数量
     'category' => 0,//显示链接的数量
     'exclude_category' => 11,//排除链接的分类ID
     'echo' => 0,//不输出
    );
    
    if( $atts['cat'] == 0  ) { }
    else {
        $args['category'] =  $atts['cat'];
    }
    
    $op = '';
    preg_match_all('/<a .*?>.*?<\/a>/', wp_list_bookmarks( $args ), $links);
    foreach($links[0] as $link){
        $op .= ''.$link.' |';
    }    
    return ''.$op.''; //echo ''.$op.'';
}