服务器与VPS
促销优惠信息

wordpress美化技巧:文章中添加自定义小工具模块

今天看到一篇文章,可以在wordpress文章中添加自定义模块,也就是把小工具功能应用到正文里面,根据需求站长可以自由的在里面添加广告代码、相关文章等内容。不过这个也有一个问题,那就是添加之后,在所有文章中显示的位置都是固定的,如果有兴趣的可以自己继续完善一下。

1、将下面代码添加到当前主题函数模板functions.php中:

// 添加小工具
if ( function_exists('register_sidebar') ) {
register_sidebar(array(
'name' => '正文小工具',
'id' => 'inline-content',
'description' => '用于在正文中添加小工具',
'before_widget' => '<aside id="%1$s" class="widget inline-content %2$s">',
'after_widget' => '<div class="clear"></div></aside>',
'before_title' => '<h3 class="widget-title">',
'after_title' => '</h3>',
));
}

// 添加到正文第二个段落下面,修改数字2可调整位置
add_filter( 'the_content', 'insert_content_filter' );
function insert_content_filter( $content ) {
ob_start();
$sidebar = dynamic_sidebar('inline-content');
$new_content = ob_get_clean();
if ( is_single() && ! is_admin() ) {
return insert_content( $new_content, 2, $content );
}
return $content;
}

// 添加到正文段落中
function insert_content( $new_content, $paragraph_id, $content ) {
$closing_p = '</p>';
$paragraphs = explode( $closing_p, $content );
foreach ($paragraphs as $index => $paragraph) {
if ( trim( $paragraph ) ) {
$paragraphs[$index] .= $closing_p;
}
if ( $paragraph_id == $index + 1 ) {
$paragraphs[$index] .= $new_content;
}
}
return implode( '', $paragraphs );
}

这段默认是添加到wordpress正文第二个段落下面,可以根据情况调整小工具插入位置,修改数字2,代码有注释。之后进入小工具设置页面会发现新增“正文小工具”,可以往里拉入各种各种小工具。

wordpress美化技巧:文章中添加自定义小工具模块

最后可以针对自己的主题进行wordpress美化,以下代码给这个小工具添加Css样式:

.inline-content {
border: 1px solid #666;
}

原文地址:https://zmingcx.com/add-widgets-to-wordpress-posts.html

赞(0) 打赏
版权声明:本文采用知识共享 署名4.0国际许可协议 [BY-NC-SA] 进行授权

文章名称:《wordpress美化技巧:文章中添加自定义小工具模块》

文章链接:https://www.chukuangren.com/wordpress-wenzhuang-xiaogongju.html

本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址