当前位置: 首页 > news >正文

【WP|9】深入解析WordPress [add_shortcode]函数

add_shortcode 是 WordPress
中一个非常强大的函数,用于创建自定义的短代码(shortcodes)。短代码是一种简洁的方式,允许用户在内容中插入动态的、可重用的功能。通过
add_shortcode,开发者可以定义自己的短代码,然后用户可以在帖子、页面、小工具或其他内容区域中使用这些短代码来显示特定的内容或功能。

在这里插入图片描述

add_shortcode 的语法

add_shortcode( $tag, $callback );
  • $tag(字符串):这是短代码的名称,用户在内容中使用的标签。
  • $callback(回调函数):这是一个函数,当短代码被使用时将被调用。该函数应该返回短代码的输出内容。

使用示例

以下是一个简单的示例,展示如何创建和使用短代码。

  1. 定义短代码
    在你的主题的 functions.php 文件或插件文件中添加以下代码:

    function my_custom_shortcode($atts, $content = null) {// 提取和处理短代码属性$attributes = shortcode_atts(array('attr1' => 'default_value1','attr2' => 'default_value2',), $atts);// 返回短代码的输出内容return '<div class="custom-shortcode">' . $attributes['attr1'] . ' - ' . $attributes['attr2'] . '</div>';
    }// 注册短代码
    add_shortcode('my_shortcode', 'my_custom_shortcode');
    
  2. 使用短代码
    在帖子或页面中,你可以使用以下语法插入短代码:

    [my_shortcode attr1="value1" attr2="value2"]
    

    这将被解析为:

    <div class="custom-shortcode">value1 - value2</div>
    

更高级的用法

1. 短代码的嵌套

短代码可以包含嵌套内容。下面是一个处理嵌套内容的示例:

function my_nested_shortcode($atts, $content = null) {return '<div class="nested-shortcode">' . do_shortcode($content) . '</div>';
}add_shortcode('nested_shortcode', 'my_nested_shortcode');

在帖子或页面中使用:

[nested_shortcode]这里是嵌套内容,可以包含其他短代码,比如 [my_shortcode attr1="value1"][/nested_shortcode]
2. 复杂的回调函数

回调函数可以非常复杂,包含条件逻辑、数据库查询等。例如:

function my_complex_shortcode($atts) {global $wpdb;$attributes = shortcode_atts(array('category' => 'default',), $atts);$category = $attributes['category'];// 查询数据库$results = $wpdb->get_results($wpdb->prepare("SELECT * FROM wp_posts WHERE post_category = %s",$category));$output = '<ul class="category-posts">';foreach ($results as $post) {$output .= '<li>' . $post->post_title . '</li>';}$output .= '</ul>';return $output;
}add_shortcode('complex_shortcode', 'my_complex_shortcode');

在帖子或页面中使用:

[complex_shortcode category="news"]

总结

add_shortcode 是 WordPress 提供的一个非常有用的工具,允许开发者创建自定义的短代码,提供灵活的内容展示方式。通过合理使用短代码,可以极大地增强 WordPress 站点的功能和用户体验。

http://www.lryc.cn/news/368637.html

相关文章:

  • Qt QStackedWidget类详细分析
  • Java数据结构与算法(leetcode热题881. 救生艇)
  • react+wijmo所遇问题
  • 手撕设计模式——克隆对象之原型模式
  • LangChain基础知识入门
  • Objective-C的初始化方法中,应该如何读写属性
  • 基于Python+Flask框架实现的新冠疫情可视化的设计与实现
  • 大学生如何学习C语言编程?
  • python小tips
  • 分布式版本控制工具软件——Git概述
  • 【一百零八】【算法分析与设计】P1908 逆序对,P1637 三元上升子序列,树状数组区间和应用
  • 【RK3568】制作Android11开机动画
  • chrony内网同步服务器时间
  • SSM物流管理系统的设计与实现-计算机毕业设计源码44323
  • STM32CubeIDE使用过程记录
  • angular2开发知识点
  • 【机器学习】机器学习与智能交通在智慧城市中的融合应用与性能优化新探索
  • 走的人多了,也便成了路(七)
  • UE5中在地形中加入湖、河
  • 【280个shell脚本】----提示运维工作效率
  • 从零开始搭建Electron项目之运行例程
  • MySQL逻辑备份
  • python 获取网页链接图片
  • Leetcode 力扣114. 二叉树展开为链表 (抖音号:708231408)
  • 文刻ai工具跟绘唐AI工具有什么区别
  • 手写kNN算法的实现-用欧几里德空间来度量距离
  • IGraph使用实例——线性代数计算(blas)
  • 【MySQL】(基础篇五) —— 排序检索数据
  • C++ C_style string overview and basic Input funcitons
  • VS2022+Qt雕刻机单片机马达串口上位机控制系统