WordPress二次开发中常用函数的详细说明
wordpress 2025年7月26日 8
WordPress 二次开发中常用函数的 详细说明(按功能分类,含参数、返回值、使用场景和示例):
1. 主题模板标签
get_header() / get_footer() / get_sidebar()
作用:加载模板文件 header.php、footer.php、sidebar.php。
参数:(string $name = null) 可加载自定义模板(如 header-custom.php)。
示例:
get_header('custom'); // 加载 header-custom.php
the_title()
作用:输出当前文章的标题。
参数:(string $before = ”, string $after = ”, bool $echo = true)。
示例:
the_title('<h1>', '</h1>'); // 输出 <h1>文章标题</h1>
the_content()
作用:输出文章正文(自动解析短代码和换行符)。
参数:(string $more_link_text = null, bool $strip_teaser = false)。
示例:
the_content('阅读更多...'); // 添加“阅读更多”链接
the_excerpt()
作用:输出文章摘要(默认 55 字,可通过 excerpt_length 钩子修改)。
示例:
the_excerpt(); // 输出摘要
the_permalink()
作用:输出当前文章的固定链接(URL)。
示例:
<a href="<?php the_permalink(); ?>">查看详情</a>
the_post_thumbnail()
作用:输出文章特色图片(缩略图)。
参数:(string|array $size = ‘post-thumbnail’, string|array $attr = ”)。
示例:
the_post_thumbnail('full', ['class' => 'img-fluid']); // 输出原图并添加 CSS 类
the_time()
作用:输出文章发布时间。
参数:(string $format = ”)(默认使用 WordPress 后台设置的日期格式)。
示例:
the_time('Y-m-d H:i'); // 输出格式如 2025-07-26 14:30
the_category() / the_tags()
作用:输出文章所属分类或标签。
参数:(string $separator = ‘, ‘, string $parents = ”, int $post_id = 0)。
示例:
the_category(', '); // 输出分类,用逗号分隔
the_tags('标签:', ', ', ''); // 输出标签,前缀为“标签:”
comments_template()
作用:加载评论模板(comments.php)。
参数:(string $file = ‘/comments.php’, bool $separate_comments = false)。
示例:
comments_template('/custom-comments.php'); // 加载自定义评论模板
2. 循环相关函数
have_posts() / the_post()
作用:在循环中检查是否有文章并设置当前文章的全局变量 $post。
示例:
if (have_posts()) {
while (have_posts()) {
the_post();
the_title(); // 输出标题
}
}
wp_reset_postdata()
作用:重置全局 $post 变量,避免自定义查询(如 WP_Query)影响主循环。
示例:
$query = new WP_Query(['post_type' => 'product']);
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
the_title();
}
wp_reset_postdata(); // 必须重置
}
3. 插件开发函数
add_action() / add_filter()
作用:将自定义函数挂载到 WordPress 钩子(动作或过滤器)。
参数:(string $hook, callable $callback, int $priority = 10, int $args = 1)。
示例:
// 在文章保存时执行自定义函数
add_action('save_post', 'my_custom_save', 10, 2);
function my_custom_save($post_id, $post) {
// 保存逻辑
}
// 修改文章内容
add_filter('the_content', 'add_custom_text');
function add_custom_text($content) {
return $content . '<p>The content to be displayed wodepress</p>';
}
do_action() / apply_filters()
作用:在代码中触发钩子,允许其他开发者扩展功能。
示例:
do_action('my_custom_hook', $data); // 触发动作钩子
$filtered = apply_filters('my_custom_filter', $data); // 触发过滤器钩子
get_option() / update_option()
作用:读取或更新 WordPress 选项(存储在 wp_options 表中)。
参数:
get_option(string $option, mixed $default = false)。
update_option(string $option, mixed $value, bool $autoload = true)。
示例:
$email = get_option('admin_email');
update_option('my_custom_option', 'new_value');
4. 媒体处理函数
wp_get_attachment_url()
作用:获取附件文件的完整 URL。
参数:(int $attachment_id)。
示例:
$image_url = wp_get_attachment_url(123); // 获取 ID 为 123 的图片 URL
wp_get_attachment_image()
作用:生成带有 srcset 响应式属性的<img>标签。
参数:(int $attachment_id, string|array $size = ‘thumbnail’, bool $icon = false, array $attr = [])。
示例:
echo wp_get_attachment_image(123, 'medium', false, ['class' => 'custom-img']);
media_handle_upload()
作用:处理上传的文件并创建附件(需配合表单使用)。
参数:(string $file_id, int $post_parent = 0, array $post_data = [], array $overrides = [])。
示例:
// 处理上传文件
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attachment_id = media_handle_upload('my_file', 0);
5. 安全相关函数
wp_nonce_field() / wp_verify_nonce()
作用:生成和验证 CSRF 令牌(防止表单伪造)。
示例:
// 生成 nonce 字段
wp_nonce_field('my_action', 'my_nonce');
// 验证 nonce
if (!wp_verify_nonce($_POST['my_nonce'], 'my_action')) {
wp_die('非法请求!');
}
esc_html() / esc_attr() / esc_url()
作用:转义输出,防止 XSS 攻击。
示例:
echo '<div title="' . esc_attr($title) . '">' . esc_html($content) . '</div>';
echo '<a href="' . esc_url($url) . '">链接</a>';
sanitize_text_field() / wp_kses()
作用:清理用户输入数据(wp_kses 可指定允许的 HTML 标签)。
示例:
$safe_text = sanitize_text_field($_POST['user_input']);
$safe_html = wp_kses($html, ['a' => ['href' => []], 'p' => []]);
6. 其他实用函数
home_url() / site_url() / admin_url()
作用:生成首页、站点或后台的 URL。
示例:
echo '首页'; // 输出 https://wodepress.com/
wp_redirect()
作用:重定向到指定 URL(需在 template_redirect 钩子前调用)。
示例:
wp_redirect(home_url('/success/'));
exit;
is_admin() / is_front_page() / is_single()
作用:判断当前页面类型。
示例:
if (is_admin()) {
// 后台逻辑
} elseif (is_single()) {
// 单篇文章逻辑
}
wp_enqueue_script() / wp_enqueue_style()
作用:安全加载 CSS/JS 文件(自动处理依赖和版本号)。
示例:
// 在 functions.php 中注册资源
function my_theme_scripts() {
wp_enqueue_style('main-css', get_stylesheet_uri());
wp_enqueue_script('main-js', get_template_directory_uri() . '/js/main.js', ['jquery'], '1.0', true);
}
add_action('wp_enqueue_scripts', 'my_theme_scripts');
7. 条件标签(详细参数)
函数 | 说明 | 示例 |
---|---|---|
is_single() | 是否单篇文章 | is_single(123) 或 is_single(['slug-1', 'slug-2']) |
is_page() | 是否单页面 | is_page('about') |
is_category() | 是否分类归档 | is_category('tech') |
is_tag() | 是否标签归档 | is_tag('wordpress') |
is_archive() | 是否任何归档页 | 无参数 |
is_search() | 是否搜索结果页 | 无参数 |
is_404() | 是否 404 错误页 | 无参数 |
comments_open() | 当前文章是否开放评论 | if (comments_open()) comments_template(); |
8. 模板文件
文件 | 用途 |
---|---|
index.php | 默认首页模板(无其他匹配模板时使用) |
single.php | 单篇文章模板 |
page.php | 单页面模板 |
archive.php | 归档页模板(分类、标签、日期等) |
category.php | 特定分类模板(如 category-tech.php ) |
tag.php | 特定标签模板 |
author.php | 特定作者模板 |
search.php | 搜索结果模板 |
404.php | 404 错误页模板 |
说明
优先使用官方函数:如 WP_Query 替代 query_posts()。
安全优先:所有用户输入和输出均需转义(如 esc_html())。
性能优化:避免在循环中直接查询数据库,使用 WP_Cache 或 transients 缓存数据。