🔁 Loop 循环查询标签
核心WordPress 的 Loop(循环)是核心机制,几乎所有内容展示都基于此。以下是循环中最常用的函数标签。
have_posts()Loop
判断是否还有文章可循环,是 while 循环的条件判断
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>使用实例
<?php if ( have_posts() ) : ?>
<ul class="post-list">
<?php while ( have_posts() ) : the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; ?>
</ul>
<?php else : ?>
<p>暂无文章</p>
<?php endif; ?>the_post()Loop
设置全局 $post 对象,必须在 while 内第一个调用
<?php the_post(); ?>使用实例
<?php while ( have_posts() ) : the_post(); ?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><?php the_title(); ?></h2>
</article>
<?php endwhile; ?>WP_QueryLoop
自定义查询类,可按分类、标签、作者、日期、自定义字段等筛选
<?php $query = new WP_Query($args); ?>使用实例
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 5,
'category_name' => 'news',
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while ( $query->have_posts() ) : $query->the_post();
?><h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3><?php
endwhile;
wp_reset_postdata();
endif;
?>get_posts()Loop
返回文章数组,适合简单列表,不修改全局查询
<?php $posts = get_posts($args); ?>使用实例
<?php
$posts = get_posts( array(
'numberposts' => 5,
'category' => 3,
'post_status' => 'publish',
) );
foreach ( $posts as $post ) :
setup_postdata( $post );
?><li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li><?php
endforeach;
wp_reset_postdata();
?>query_posts()Loop
修改主查询(不推荐,应使用 pre_get_posts 或 WP_Query)
<?php query_posts('cat=5&posts_per_page=10'); ?>使用实例
<?php
// 修改主查询(不推荐,优先用 pre_get_posts)
query_posts( 'cat=5&posts_per_page=3' );
while ( have_posts() ) : the_post();
?><h3><?php the_title(); ?></h3><?php
endwhile;
wp_reset_query();
?>wp_reset_postdata()Loop
自定义查询结束后,恢复全局 $post 对象,避免数据污染
<?php wp_reset_postdata(); ?>使用实例
<?php
$q = new WP_Query( array( 'post_type' => 'product' ) );
while ( $q->have_posts() ) : $q->the_post();
?><p><?php the_title(); ?></p><?php
endwhile;
wp_reset_postdata(); // 恢复全局 $post 为主查询数据
?>wp_reset_query()Loop
配合 query_posts() 使用,重置主查询
<?php wp_reset_query(); ?>使用实例
<?php
query_posts( 'cat=2' );
while ( have_posts() ) : the_post();
?><h4><?php the_title(); ?></h4><?php
endwhile;
wp_reset_query(); // 与 query_posts() 配对使用
?>setup_postdata()Loop
在 get_posts() 中手动设置全局 $post,以便使用 the_title() 等
<?php global $post; setup_postdata($post); ?>使用实例
<?php
$posts = get_posts( array( 'numberposts' => 3 ) );
foreach ( $posts as $post ) :
setup_postdata( $post ); // 使模板标签在循环外正常工作
?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><?php
endforeach;
wp_reset_postdata();
?>📄 文章字段标签
Postthe_title()Post
输出当前文章标题(直接回显)
<?php the_title(); ?>使用实例
<h1 class="entry-title"><?php the_title(); ?></h1>
<!-- 在链接中使用,带属性 -->
<a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>">
<?php the_title(); ?>
</a>get_the_title()Post
返回文章标题字符串,可传入 ID 参数
<?php echo get_the_title($post_id); ?>使用实例
<?php
// 获取标题字符串,用于拼接或传参
$title = get_the_title(); // 当前文章
$other = get_the_title( 42 ); // 指定文章 ID
echo '<meta property="og:title" content="' . esc_attr( $title ) . '">';
?>the_content()Post
输出文章正文,执行过滤器(包括短代码解析)
<?php the_content('查看更多'); ?>使用实例
<article>
<?php
the_content(
'<a class="read-more" href="' . esc_url( get_permalink() ) . '">继续阅读</a>'
);
?>
</article>the_excerpt()Post
输出摘要,自动截取或使用手工摘要
<?php the_excerpt(); ?>使用实例
<div class="card">
<h3><?php the_title(); ?></h3>
<p class="excerpt"><?php the_excerpt(); ?></p>
<a href="<?php the_permalink(); ?>">阅读全文</a>
</div>get_the_excerpt()Post
返回摘要字符串,可在输出前处理
<?php echo get_the_excerpt(); ?>使用实例
<?php
$excerpt = get_the_excerpt();
// 截取前 80 个字符作摘要
echo '<p>' . esc_html( mb_substr( $excerpt, 0, 80 ) ) . '...</p>';
?>the_permalink()Post
输出文章固定链接 URL
<a href="<?php the_permalink(); ?>"></a>使用实例
<!-- 文章卡片链接 -->
<a href="<?php the_permalink(); ?>" class="post-link">
<?php the_title(); ?>
</a>
<!-- 缩略图包裹链接 -->
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( 'medium' ); ?>
</a>get_permalink()Post
返回文章链接,可传 ID
<?php echo get_permalink($post_id); ?>使用实例
<?php
// 获取指定 ID 文章的永久链接
$url = get_permalink( 123 );
echo '<a href="' . esc_url( $url ) . '">查看详情</a>';
// 用于 Open Graph
echo '<meta property="og:url" content="' . esc_url( get_permalink() ) . '">';
?>the_date()Post
输出文章发布日期,格式可自定义
<?php the_date('Y-m-d'); ?>使用实例
<time class="entry-date" datetime="<?php echo get_the_date('c'); ?>">
<?php the_date( 'Y年m月d日' ); ?>
</time>get_the_date()Post
返回日期字符串
<?php echo get_the_date('Y年m月d日'); ?>使用实例
<?php
$date = get_the_date( 'Y-m-d' );
echo '<span class="date">发布于 ' . esc_html( $date ) . '</span>';
?>the_time()Post
输出发布时间
<?php the_time('H:i'); ?>使用实例
<!-- 显示发布时间 -->
<span>发布时间:<?php the_time( 'H:i' ); ?></span>
<!-- 完整日期+时间 -->
<time><?php the_time( 'Y-m-d H:i:s' ); ?></time>the_modified_date()Post
输出文章最后修改日期
<?php the_modified_date('Y-m-d'); ?>使用实例
<p class="updated">
最后更新:<?php the_modified_date( 'Y年m月d日' ); ?>
</p>the_ID()Post
输出当前文章 ID
<?php the_ID(); ?> <!-- 或 get_the_ID() 返回值 -->使用实例
<!-- 用于文章 ID 锚点 / DOM 操作 -->
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<h2><?php the_title(); ?></h2>
</article>the_author()Post
输出文章作者显示名
<?php the_author(); ?>使用实例
<p class="byline">
作者:<a href="<?php echo esc_url( get_author_posts_url( get_the_author_meta('ID') ) ); ?>">
<?php the_author(); ?>
</a>
</p>get_the_author_meta()Post
获取作者字段(user_login / email / description 等)
<?php echo get_the_author_meta('email'); ?>使用实例
<?php
$author_id = get_the_author_meta( 'ID' );
$name = get_the_author_meta( 'display_name' );
$bio = get_the_author_meta( 'description' );
$avatar = get_avatar( $author_id, 64 );
echo $avatar . '<strong>' . esc_html( $name ) . '</strong>';
echo '<p>' . esc_html( $bio ) . '</p>';
?>comments_number()Post
输出评论数,支持无/1条/多条文本自定义
<?php comments_number('无评论','1条','%条'); ?>使用实例
<a href="<?php comments_link(); ?>">
<?php comments_number( '0 条评论', '1 条评论', '% 条评论' ); ?>
</a>get_post_meta()Post
获取自定义字段值(ACF 等插件也通过此函数存储)
<?php echo get_post_meta(get_the_ID(),'key',true); ?>使用实例
<?php
// 获取单个自定义字段
$price = get_post_meta( get_the_ID(), 'product_price', true );
if ( $price ) {
echo '<span class="price">¥' . esc_html( $price ) . '</span>';
}
// 获取多值字段(数组)
$images = get_post_meta( get_the_ID(), 'gallery_images', false );
foreach ( $images as $img_id ) {
echo wp_get_attachment_image( $img_id, 'thumbnail' );
}
?>get_post_type()Post
返回当前文章类型(post/page/自定义类型)
<?php echo get_post_type(); ?>使用实例
<?php
$type = get_post_type();
if ( 'product' === $type ) {
echo '<span class="badge">商品</span>';
} elseif ( 'post' === $type ) {
echo '<span class="badge">文章</span>';
}
?>post_class()Post
输出文章 CSS 类名(包含分类、状态等)
<article <?php post_class(); ?>>使用实例
<!-- 自动输出 post-N, category-X, format-X 等 class -->
<article <?php post_class( 'card my-article' ); ?>>
<h2><?php the_title(); ?></h2>
</article>🏷️ 分类 / 标签 / 分类法
Taxonomythe_category()Tax
输出文章所属分类链接列表
<?php the_category(', '); ?>使用实例
<div class="post-cats">
分类:<?php the_category( ' / ' ); ?>
</div>get_the_category()Tax
返回分类对象数组,可遍历处理
<?php $cats = get_the_category(); foreach($cats as $cat) echo $cat->name; ?>使用实例
<?php
$cats = get_the_category();
if ( $cats ) {
$first = $cats[0];
echo '<a href="' . esc_url( get_category_link( $first->term_id ) ) . '">'
. esc_html( $first->name ) . '</a>';
}
?>get_categories()Tax
获取所有分类列表,支持 parent/orderby 等参数
<?php $cats = get_categories(['parent'=>0]); ?>使用实例
<?php
$cats = get_categories( array(
'parent' => 0, // 只取顶级分类
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false,
) );
echo '<ul class="cat-list">';
foreach ( $cats as $cat ) {
echo '<li><a href="' . esc_url( get_category_link( $cat->term_id ) ) . '">'
. esc_html( $cat->name ) . ' (' . $cat->count . ')</a></li>';
}
echo '</ul>';
?>the_tags()Tax
输出文章标签链接
<?php the_tags('标签:',', '); ?>使用实例
<div class="post-tags">
<?php the_tags( '标签:', ' · ', '' ); ?>
</div>get_the_tags()Tax
返回标签对象数组
<?php $tags = get_the_tags(); foreach($tags as $tag) echo $tag->name; ?>使用实例
<?php
$tags = get_the_tags();
if ( $tags ) {
echo '<ul class="tags">';
foreach ( $tags as $tag ) {
echo '<li><a href="' . esc_url( get_tag_link( $tag->term_id ) ) . '">#'
. esc_html( $tag->name ) . '</a></li>';
}
echo '</ul>';
}
?>get_terms()Tax
获取任意分类法的词条(通用,推荐)
<?php $terms = get_terms(['taxonomy'=>'category','hide_empty'=>false]); ?>使用实例
<?php
// 获取自定义分类法的所有项
$brands = get_terms( array(
'taxonomy' => 'brand',
'hide_empty' => false,
'orderby' => 'count',
'order' => 'DESC',
) );
if ( ! is_wp_error( $brands ) ) {
foreach ( $brands as $brand ) {
echo '<option value="' . esc_attr( $brand->slug ) . '">'
. esc_html( $brand->name ) . '</option>';
}
}
?>wp_list_categories()Tax
直接输出 HTML 格式的分类列表
<?php wp_list_categories(['show_count'=>1,'title_li'=>'']); ?>使用实例
<?php
// 在侧边栏输出分类列表
wp_list_categories( array(
'title_li' => '文章分类',
'orderby' => 'name',
'show_count' => true,
'depth' => 2,
) );
?>get_category_link()Tax
获取指定分类的 URL
<?php echo get_category_link($cat_id); ?>使用实例
<?php
$cat_id = 5;
$url = get_category_link( $cat_id );
echo '<a href="' . esc_url( $url ) . '">查看该分类所有文章</a>';
?>is_category()Tax
判断是否在分类归档页
<?php if (is_category('news')) { ... } ?>使用实例
<?php
// 分类页才显示分类描述
if ( is_category() ) {
$cat = get_queried_object();
$desc = category_description( $cat->term_id );
if ( $desc ) echo '<div class="cat-desc">' . $desc . '</div>';
}
?>in_category()Tax
判断当前文章是否属于某分类
<?php if (in_category(5)) { ... } ?>使用实例
<?php
// 当前文章属于"精选"分类才显示角标
if ( in_category( 'featured' ) ) {
echo '<span class="badge-featured">精选</span>';
}
?>👤 用户相关标签
Useris_user_logged_in()User
判断当前用户是否已登录
<?php if (is_user_logged_in()) { ... } ?>使用实例
<?php if ( is_user_logged_in() ) : ?>
<a href="<?php echo esc_url( admin_url() ); ?>">后台管理</a>
<a href="<?php echo esc_url( wp_logout_url( home_url() ) ); ?>">退出登录</a>
<?php else : ?>
<a href="<?php echo esc_url( wp_login_url() ); ?>">登录</a>
<?php endif; ?>wp_get_current_user()User
返回当前登录用户对象
<?php $user = wp_get_current_user(); echo $user->display_name; ?>使用实例
<?php
$user = wp_get_current_user();
if ( $user->ID ) {
echo '<p>欢迎,' . esc_html( $user->display_name ) . '!</p>';
echo '<p>邮箱:' . esc_html( $user->user_email ) . '</p>';
}
?>get_current_user_id()User
返回当前用户 ID,未登录返回 0
<?php $uid = get_current_user_id(); ?>使用实例
<?php
$user_id = get_current_user_id();
if ( $user_id ) {
// 获取该用户的自定义字段
$vip = get_user_meta( $user_id, 'is_vip', true );
echo $vip ? '<span class="vip-badge">VIP</span>' : '';
}
?>current_user_can()User
检查当前用户是否拥有某权限
<?php if (current_user_can('edit_posts')) { ... } ?>使用实例
<?php
// 仅管理员可见的编辑入口
if ( current_user_can( 'edit_posts' ) ) {
echo '<a href="' . esc_url( get_edit_post_link() ) . '">编辑文章</a>';
}
?>get_avatar()User
返回用户头像 img 标签(Gravatar)
<?php echo get_avatar($user_id, 80); ?>使用实例
<div class="author-card">
<?php echo get_avatar( get_the_author_meta( 'ID' ), 80, '', get_the_author() ); ?>
<span><?php the_author(); ?></span>
</div>wp_loginout()User
输出登录/注销链接
<?php wp_loginout(); ?>使用实例
<nav class="user-nav">
<?php
// 已登录显示「退出」,未登录显示「登录」
wp_loginout( home_url(), true );
?>
</nav>🖼️ 媒体 / 图片标签
Mediathe_post_thumbnail()Media
输出特色图片 img 标签,可指定尺寸
<?php the_post_thumbnail('medium'); ?>使用实例
<!-- 单篇文章页:显示大尺寸特色图 -->
<?php if ( has_post_thumbnail() ) : ?>
<figure class="post-cover">
<?php the_post_thumbnail( 'large', array( 'class' => 'cover-img', 'loading' => 'lazy' ) ); ?>
</figure>
<?php endif; ?>get_the_post_thumbnail_url()Media
返回特色图片 URL 字符串
<?php $url = get_the_post_thumbnail_url(get_the_ID(),'full'); ?>使用实例
<?php
$thumb = get_the_post_thumbnail_url( get_the_ID(), 'medium' );
if ( $thumb ) {
echo '<div class="card-bg" style="background-image:url(' . esc_url($thumb) . ')"></div>';
}
// 用于 Open Graph
echo '<meta property="og:image" content="' . esc_url( get_the_post_thumbnail_url( get_the_ID(), 'full' ) ) . '">';
?>has_post_thumbnail()Media
判断文章是否设置了特色图片
<?php if (has_post_thumbnail()) { the_post_thumbnail(); } ?>使用实例
<?php if ( has_post_thumbnail() ) : ?>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( 'thumbnail' ); ?>
</a>
<?php else : ?>
<img src="<?php echo esc_url( get_template_directory_uri() . '/img/default.jpg' ); ?>" alt="">
<?php endif; ?>wp_get_attachment_image()Media
通过附件 ID 返回图片标签
<?php echo wp_get_attachment_image($att_id, 'thumbnail'); ?>使用实例
<?php
// 在图集循环中输出响应式图片
$image_ids = array( 101, 102, 103 );
foreach ( $image_ids as $id ) {
echo wp_get_attachment_image( $id, 'medium', false, array( 'class' => 'gallery-img', 'loading' => 'lazy' ) );
}
?>wp_get_attachment_url()Media
返回附件文件 URL
<?php echo wp_get_attachment_url($att_id); ?>使用实例
<?php
$attachment_id = 56;
$file_url = wp_get_attachment_url( $attachment_id );
echo '<a href="' . esc_url( $file_url ) . '" download>下载文件</a>';
?>add_image_size()Media
在 functions.php 注册自定义图片尺寸
<?php add_image_size('banner', 1200, 400, true); ?>使用实例
<?php
// 在 functions.php 中注册自定义尺寸
add_theme_support( 'post-thumbnails' );
add_image_size( 'hero-banner', 1440, 600, true ); // 裁剪
add_image_size( 'card-thumb', 400, 300, false ); // 等比缩放
// 模板中使用
the_post_thumbnail( 'hero-banner' );
?>🔗 URL / 路径标签
URLget_template_directory_uri()URL
返回当前主题目录 URL(用于引用 CSS/JS/图片)
<?php echo get_template_directory_uri(); ?>/images/logo.png使用实例
<!-- 在模板中引用主题资源 -->
<img src="<?php echo esc_url( get_template_directory_uri() . '/images/logo.png' ); ?>" alt="Logo">
<link rel="stylesheet" href="<?php echo esc_url( get_template_directory_uri() . '/css/custom.css' ); ?>">get_stylesheet_directory_uri()URL
子主题时返回子主题目录 URL,父主题则与 get_template_directory_uri 相同
<?php echo get_stylesheet_directory_uri(); ?>/style.css使用实例
<?php
// 子主题中引用子主题自己的资源(父主题用 get_template_directory_uri)
$icon_url = get_stylesheet_directory_uri() . '/icons/star.svg';
echo '<img src="' . esc_url( $icon_url ) . '" alt="star">';
?>home_url()URL
返回站点首页 URL
<?php echo home_url('/about'); ?>使用实例
<!-- 网站首页链接 -->
<a href="<?php echo esc_url( home_url( '/' ) ); ?>">
<img src="logo.png" alt="首页">
</a>
<?php
// 登录后跳回首页
wp_login_url( home_url() );
?>site_url()URL
返回 WordPress 安装根目录 URL
<?php echo site_url('/wp-login.php'); ?>使用实例
<?php
// 构造绝对路径 URL(常用于 AJAX 接口或 REST API)
$api = site_url( '/wp-json/wp/v2/posts' );
echo '<script>var API_BASE = "' . esc_js( $api ) . '";</script>';
?>admin_url()URL
返回后台管理 URL
<?php echo admin_url('edit.php?post_type=page'); ?>使用实例
<?php
// 带权限判断的后台链接
if ( current_user_can( 'manage_options' ) ) {
echo '<a href="' . esc_url( admin_url( 'options-general.php' ) ) . '">网站设置</a>';
}
// ajax-admin URL(前端 AJAX 请求用)
$ajax_url = admin_url( 'admin-ajax.php' );
?>includes_url()URL
返回 wp-includes 目录 URL
<?php echo includes_url('js/jquery/jquery.js'); ?>使用实例
<?php
// 引用 wp-includes 目录内的脚本(通常无需直接用)
$js = includes_url( 'js/tinymce/tinymce.min.js' );
echo '<script src="' . esc_url( $js ) . '"></script>';
?>plugins_url()URL
返回插件文件 URL
<?php echo plugins_url('images/icon.png', __FILE__); ?>使用实例
<?php
// 在插件内引用自身资源
function my_plugin_assets() {
wp_enqueue_script(
'my-plugin-js',
plugins_url( 'js/main.js', __FILE__ ),
array('jquery'),
'1.0.0',
true
);
}
add_action( 'wp_enqueue_scripts', 'my_plugin_assets' );
?>get_bloginfo()URL
返回站点信息(name/description/url 等)
<?php echo get_bloginfo('name'); ?>使用实例
<!-- 页面标题和描述 -->
<title><?php echo esc_html( get_bloginfo( 'name' ) ); ?> – <?php bloginfo( 'description' ); ?></title>
<meta name="description" content="<?php echo esc_attr( get_bloginfo( 'description' ) ); ?>">⚙️ 其他常用标签
Miscis_front_page()Misc
判断是否在首页
<?php if (is_front_page()) { ... } ?>使用实例
<?php
// 首页显示大 Banner,其他页显示普通头图
if ( is_front_page() ) {
get_template_part( 'template-parts/hero-banner' );
} else {
get_template_part( 'template-parts/page-header' );
}
?>is_single()Misc
判断是否在文章详情页
<?php if (is_single()) { ... } ?>使用实例
<?php
// 单文章页才加载评论
if ( is_single() ) {
comments_template();
}
// 判断特定文章
if ( is_single( array( 12, 'hello-world' ) ) ) {
echo '<div class="special-banner">特别专题</div>';
}
?>is_page()Misc
判断是否在页面,可传 slug/ID
<?php if (is_page('about')) { ... } ?>使用实例
<?php
// 关于页面特殊布局
if ( is_page( 'about' ) ) {
get_template_part( 'template-parts/team-section' );
}
// 联系页面隐藏侧边栏
if ( is_page( array( 'contact', 'about' ) ) ) {
$sidebar = false;
}
?>is_archive()Misc
判断是否在归档页(分类/标签/作者/日期)
<?php if (is_archive()) { ... } ?>使用实例
<?php
// 归档页显示归档标题
if ( is_archive() ) {
echo '<h1>' . esc_html( get_the_archive_title() ) . '</h1>';
$desc = get_the_archive_description();
if ( $desc ) echo '<div class="archive-desc">' . $desc . '</div>';
}
?>is_search()Misc
判断是否在搜索结果页
<?php if (is_search()) { ... } ?>使用实例
<?php if ( is_search() ) : ?>
<h1>搜索 “<?php echo esc_html( get_search_query() ); ?>” 的结果</h1>
<p>共找到 <?php echo $wp_query->found_posts; ?> 篇相关文章</p>
<?php endif; ?>get_search_query()Misc
获取当前搜索关键词
<?php echo get_search_query(); ?>使用实例
<!-- 在搜索框中回显关键词 -->
<form role="search" method="get" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input type="search" name="s"
value="<?php echo esc_attr( get_search_query() ); ?>"
placeholder="搜索...">
<button type="submit">搜索</button>
</form>wp_head()Misc
在 <head> 内输出钩子内容(CSS/JS/meta),必须调用
<?php wp_head(); ?>使用实例
<!-- 必须放在 </head> 之前,WordPress 核心、插件在此注入 CSS/JS/meta -->
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<?php wp_head(); ?>
</head>wp_footer()Misc
在 </body> 前输出钩子内容(JS),必须调用
<?php wp_footer(); ?>使用实例
<!-- 必须放在 </body> 之前,WordPress 在此注入 JS 文件 -->
<footer>
<p>© <?php echo date('Y'); ?> <?php bloginfo('name'); ?></p>
</footer>
<?php wp_footer(); ?>
</body></html>wp_enqueue_script()Misc
注册并引入 JS 文件(推荐方式)
<?php wp_enqueue_script('my-js', get_template_directory_uri().'/js/main.js', ['jquery'],'1.0',true); ?>使用实例
<?php
// functions.php 中正确加载脚本
function mytheme_scripts() {
wp_enqueue_script(
'my-slider', // 句柄
get_template_directory_uri() . '/js/slider.js',
array( 'jquery' ), // 依赖
'2.1.0', // 版本
true // 放在 footer
);
// 传递变量给 JS
wp_localize_script( 'my-slider', 'sliderConfig', array(
'autoplay' => true,
'speed' => 500,
) );
}
add_action( 'wp_enqueue_scripts', 'mytheme_scripts' );
?>wp_enqueue_style()Misc
注册并引入 CSS 文件
<?php wp_enqueue_style('my-style', get_stylesheet_uri()); ?>使用实例
<?php
function mytheme_styles() {
// 主样式(自动读取 style.css 版本号)
wp_enqueue_style(
'mytheme-style',
get_stylesheet_uri(),
array(),
wp_get_theme()->get('Version')
);
// 额外样式
wp_enqueue_style(
'google-fonts',
'https://fonts.googleapis.com/css2?family=Noto+Sans+SC&display=swap',
array(),
null
);
}
add_action( 'wp_enqueue_scripts', 'mytheme_styles' );
?>add_action()Misc
向钩子添加函数(WordPress 核心机制)
<?php add_action('wp_enqueue_scripts','my_scripts'); ?>使用实例
<?php
// 在文章内容后追加版权声明
function add_copyright( $content ) {
if ( is_single() && in_the_loop() ) {
$content .= '<p class="copyright">版权归本站所有,转载请注明出处。</p>';
}
return $content;
}
add_filter( 'the_content', 'add_copyright' );
// 注册侧边栏
add_action( 'widgets_init', function() {
register_sidebar( array( 'name' => '主侧边栏', 'id' => 'sidebar-1' ) );
} );
?>add_filter()Misc
过滤器钩子,修改数据后返回
<?php add_filter('the_content','my_func'); ?>使用实例
<?php
// 修改摘要长度
add_filter( 'excerpt_length', function( $length ) {
return 30; // 30 个字
} );
// 修改「阅读更多」文字
add_filter( 'excerpt_more', function() {
return '… <a href="' . esc_url( get_permalink() ) . '">阅读全文</a>';
} );
?>shortcode_atts()Misc
解析短代码属性,提供默认值
<?php $atts = shortcode_atts(['num'=>5],$atts); ?>使用实例
<?php
// 注册短代码 [my_button text="点击" color="blue" url="#"]
function my_button_shortcode( $atts ) {
$a = shortcode_atts( array(
'text' => '按钮',
'color' => 'primary',
'url' => '#',
), $atts, 'my_button' );
return '<a href="' . esc_url( $a['url'] ) . '" class="btn btn-' . esc_attr($a['color']) . '">'
. esc_html( $a['text'] ) . '</a>';
}
add_shortcode( 'my_button', 'my_button_shortcode' );
?>do_shortcode()Misc
解析并执行字符串中的短代码
<?php echo do_shortcode('[my_shortcode id="1"]'); ?>使用实例
<?php
// 在 PHP 中主动解析短代码(如在 Widget、自定义字段中)
$content = get_post_meta( get_the_ID(), 'custom_html', true );
echo do_shortcode( $content );
// 在侧边栏 Widget 文本中启用短代码
add_filter( 'widget_text', 'do_shortcode' );
?>esc_html() / esc_url() / esc_attr()Misc
输出转义函数,防 XSS(安全必备)
<?php echo esc_html($str); echo esc_url($url); echo esc_attr($val); ?>使用实例
<?php
$title = get_the_title(); // 可能含 HTML 特殊字符
$url = get_the_permalink();
$alt = get_post_meta( get_the_ID(), 'img_alt', true );
// esc_html:输出为纯文本(转义 < > & 等)
echo '<h2>' . esc_html( $title ) . '</h2>';
// esc_url:清理 URL,防止 javascript: 等危险协议
echo '<a href="' . esc_url( $url ) . '">';
// esc_attr:用于 HTML 属性值(双引号内)
echo '<img src="cover.jpg" alt="' . esc_attr( $alt ) . '">';
?>🔁 列表循环示例
示例代码主循环(The Loop)是 WordPress 最基本的展示机制,在 index.php / archive.php / single.php 等模板中直接使用。
PHP — 主循环(文章列表)
<?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <!-- 特色图 --> <?php if ( has_post_thumbnail() ) : ?> <a href="<?php the_permalink(); ?>"> <?php the_post_thumbnail( 'medium' ); ?> </a> <?php endif; ?> <header> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <time><?php the_date('Y-m-d'); ?></time> <span class="author"><?php the_author(); ?></span> </header> <div class="excerpt"> <?php the_excerpt(); ?> </div> <!-- 分类 & 标签 --> <footer> <?php the_category(' / '); ?> <?php the_tags('标签:', ', '); ?> </footer> </article> <?php endwhile; endif; ?>
WP_Query 是自定义查询的首选方案,不影响全局 $wp_query,记得最后调用 wp_reset_postdata()。
PHP — WP_Query 自定义查询
<?php $args = [ 'post_type' => 'post', // 文章类型 'posts_per_page' => 10, // 每页数量,-1 = 全部 'cat' => 5, // 分类 ID 'tag' => 'wordpress', // 标签 slug 'orderby' => 'date', // date/title/menu_order/rand 'order' => 'DESC', 'paged' => get_query_var('paged') ?: 1, // 翻页 'meta_query' => [ [ 'key' => 'featured', 'value' => 'yes', 'compare' => '=', ], ], ]; $query = new WP_Query( $args ); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <?php endwhile; wp_reset_postdata(); // 重置全局 $post,防数据污染 else : echo '<p>没有找到文章</p>'; endif; ?>
get_posts() 返回文章数组,不修改全局查询,适合小组件和侧边栏。需要 setup_postdata() 才能用 the_title() 等模板标签。
PHP — get_posts() 列表
<?php $posts = get_posts([ 'numberposts' => 5, 'category' => 3, 'orderby' => 'date', 'order' => 'DESC', ]); if ( $posts ) : global $post; echo '<ul>'; foreach ( $posts as $post ) : setup_postdata( $post ); // 激活模板标签 echo '<li><a href="' . get_permalink() . '">' . get_the_title() . '</a></li>'; endforeach; echo '</ul>'; wp_reset_postdata(); endif; ?>
自定义文章类型(CPT)查询只需修改 post_type 参数,结合 taxonomy_query 可实现精细筛选。
PHP — 自定义文章类型循环
<?php $query = new WP_Query([ 'post_type' => 'product', // 自定义文章类型 slug 'posts_per_page' => 12, 'tax_query' => [ [ 'taxonomy' => 'product_cat', // 自定义分类法 'field' => 'slug', 'terms' => 'electronics', ], ], 'meta_key' => 'price', 'orderby' => 'meta_value_num', 'order' => 'ASC', ]); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); $price = get_post_meta( get_the_ID(), 'price', true ); ?> <div class="product"> <?php the_post_thumbnail('medium'); ?> <h3><?php the_title(); ?></h3> <p class="price">¥<?php echo esc_html($price); ?></p> </div> <?php endwhile; wp_reset_postdata(); endif; ?>
📄 翻页 / 分页示例
示例代码posts_nav_link() 是最简单的上一页/下一页,paginate_links() 输出完整页码导航。
PHP — 主循环翻页(数字页码)
<!-- functions.php 中设置每页数量(可选,后台也能设置)--> <?php add_action( 'pre_get_posts', function( $q ) { if ( $q->is_main_query() && ! is_admin() ) { $q->set( 'posts_per_page', 10 ); } }); ?> <!-- 模板文件 (index.php / archive.php) --> <?php if ( have_posts() ) : ?> <!-- ... loop ... --> <?php endif; ?> <!-- 方式1:数字翻页(推荐)--> <div class="pagination"> <?php echo paginate_links([ 'prev_text' => '« 上一页', 'next_text' => '下一页 »', 'mid_size' => 2, // 当前页两侧显示页码数 ]); ?> </div> <!-- 方式2:简单上/下 --> <?php posts_nav_link( ' | ', '« 较旧文章', '较新文章 »' ); ?> <!-- 方式3:上一篇/下一篇(单篇文章页用)--> <?php the_post_navigation([ 'prev_text' => '%title', 'next_text' => '%title' ]); ?>
WP_Query 翻页必须手动传入 paged 参数,并将 max_num_pages 传给 paginate_links。
PHP — WP_Query 自定义查询翻页
<?php // 获取当前页码(兼容静态首页) $paged = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : ( get_query_var( 'page' ) ?: 1 ); $query = new WP_Query([ 'post_type' => 'post', 'posts_per_page' => 10, 'paged' => $paged, // 关键:传入页码 ]); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?><h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2><?php endwhile; wp_reset_postdata(); endif; ?> <div class="pagination"> <?php echo paginate_links([ 'base' => get_pagenum_link(1) . '%_%', 'format' => 'page/%#%/', 'current' => $paged, 'total' => $query->max_num_pages, // 总页数 'prev_text' => '«', 'next_text' => '»', ]); ?> </div>
PHP — functions.php(Ajax 翻页接口)
// functions.php add_action( 'wp_ajax_load_more_posts', 'ajax_load_posts' ); add_action( 'wp_ajax_nopriv_load_more_posts', 'ajax_load_posts' ); function ajax_load_posts() { $paged = intval( $_POST['page'] ); $query = new WP_Query([ 'post_type' => 'post', 'posts_per_page' => 10, 'paged' => $paged, ]); if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); get_template_part( 'template-parts/post', 'card' ); endwhile; endif; wp_die(); // 必须,防止额外输出 0 }
JavaScript — 加载更多按钮
// 通过 wp_localize_script 传入 ajaxurl
let page = 1;
document.getElementById('load-more').addEventListener('click', () => {
page++;
fetch(ajaxurl, {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `action=load_more_posts&page=${page}`
})
.then(r => r.text())
.then(html => {
document.getElementById('posts-container').insertAdjacentHTML('beforeend', html);
});
});
🔍 搜索示例
示例代码searchform.php 会覆盖 get_search_form() 的输出,放在主题根目录即可。
PHP — searchform.php(自定义搜索表单)
<form role="search" method="get" action="<?php echo esc_url( home_url('/') ); ?>" class="search-form"> <input type="search" name="s" value="<?php echo get_search_query(); ?>" placeholder="搜索..." aria-label="搜索" /> <button type="submit">搜索</button> </form> <!-- 在模板中调用 --> <?php get_search_form(); ?>
PHP — search.php(搜索结果模板)
<?php get_header(); ?> <main> <h1> 搜索:<span><?php echo esc_html( get_search_query() ); ?></span> <small>(共 <?php echo intval( $wp_query->found_posts ); ?> 条结果)</small> </h1> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <article> <h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2> <p class="url"><?php echo esc_url( get_permalink() ); ?></p> <p><?php the_excerpt(); ?></p> </article> <?php endwhile; ?> <!-- 分页 --> <div class="pagination"><?php echo paginate_links(); ?></div> <?php else : ?> <p>没有找到与 "<?php echo esc_html( get_search_query() ); ?>" 相关的内容。</p> <?php get_search_form(); ?> <?php endif; ?> </main> <?php get_footer(); ?>
通过 pre_get_posts 过滤器限制搜索范围(如只搜某文章类型),比修改模板更干净。
PHP — 限制搜索范围(functions.php)
// 只搜索 post 和 product,排除页面 add_action( 'pre_get_posts', function( $q ) { if ( $q->is_search() && $q->is_main_query() ) { $q->set( 'post_type', [ 'post', 'product' ] ); } }); // 自定义字段也参与搜索 add_filter( 'posts_search', function( $search, $q ) { global $wpdb; if ( ! $q->is_search() ) return $search; $s = $q->get( 's' ); if ( $s ) { $search .= $wpdb->prepare( " OR ({$wpdb->posts}.ID IN ( SELECT post_id FROM {$wpdb->postmeta} WHERE meta_value LIKE %s ))", '%' . $wpdb->esc_like($s) . '%' ); } return $search; }, 10, 2 );