如果您想要开始开发自己的 WordPress 主题,那么本指南将为您提供一些基本的入门知识和技巧。
一个 WordPress 主题通常由下列文件和文件夹组成:
style.css
- 主题样式表index.php
- 主页模板single.php
- 单篇文章页面模板page.php
- 页面模板header.php
- 主题头部模板footer.php
- 主题尾部模板sidebar.php
- 侧边栏模板functions.php
- 主题功能文件在此基础上,您还可以创建其他页面模板、自定义页面模板、自定义分类目录模板等,并将它们包含在主题中。
在主题目录中新建一个 style.css 文件,并添加下列基本样式信息:
/*
Theme Name: your-theme-name
Theme URI: http://your-theme-uri.com
Author: your-name
Author URI: http://your-author-uri.com
Description: your-theme-description
Version: 1.0
License: GNU General Public License v2 or later
License URI: http://www.gnu.org/licenses/gpl-2.0.html
Tags: your-theme-tags, separated by commas
Text Domain: your-theme-textdomain
*/
接着,您可以在样式表中添加您自己的 CSS 样式规则。
页面模板通常由 HTML 和 PHP 代码组成,用于定义页面的结构和内容。
例如,一个基本的 index.php 页面模板可以是这样的:
<?php get_header(); ?>
<div id="content">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="post">
<h2><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h2>
<div class="post-meta"><?php the_time('F j, Y'); ?> <?php _e('by', 'your-theme-textdomain'); ?> <?php the_author(); ?></div>
<div class="post-content">
<?php the_content(); ?>
</div>
</div>
<?php endwhile; else: ?>
<p><?php _e('Sorry, no posts matched your criteria.', 'your-theme-textdomain'); ?></p>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
您可以在 functions.php 文件中编写自定义函数,以扩展主题的功能。
例如,下面的代码可以添加一个自定义小工具:
function your_theme_widget_init() {
register_sidebar( array(
'name' => __( 'Sidebar', 'your-theme-textdomain' ),
'id' => 'sidebar-1',
'description' => __( 'Add widgets here to appear in your sidebar.', 'your-theme-textdomain' ),
'before_widget' => '<div class="widget %2$s">',
'after_widget' => '</div>',
'before_title' => '<h2 class="widgettitle">',
'after_title' => '</h2>',
) );
}
add_action( 'widgets_init', 'your_theme_widget_init' );
本指南提供了一些 WordPress 主题开发的基础知识和技巧。如果您想了解更多信息,请查阅 WordPress 开发文档。