Wordpress主题:首页模板(index.php)
本文主要通过分析 Wordpress 官方主题 twentytwelve 的中的“首页模板”来了解 Wordpress 主题首页制作需要用到的函数。
首页大概可以分为四个个部分,头部,主体,侧边栏,底部。
<?php get_header(); ?>
get_header()
:获取头部模板(header.php)文件中的内容,头部模板主要包含的是首页中导航栏的代码,以后再详细分析。
接下来是首页主体内容的代码,主要获取文章相关的信息。
<div id="primary" class="site-content">
<div id="content" role="main">
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
<?php twentytwelve_content_nav( 'nav-below' ); ?>
have_posts()
:判断是否有文章,如果有则返回 true。the_post()
:获取当前文章对象。get_post_format()
:获取当前文章的类型,比如日志(aside)、图像(image)或链接(link)。get_template_part()
:获取指定模板文件的内容,有两个参数,$slug
(通用模板名称) 和 $name
(自定义名称),得到的模板文件名就是 $slug-$name.php
。这里的模板存储的是显示文章的详细代码。twentytwelve_content_nav()
:这个是在 function.php
中自定义的一个函数,获取分页导航。
首先判断是否有文章,如果有则循环获取文章对象并显示,如果没有,则执行下面的代码。
<?php else : ?>
<article id="post-0" class="post no-results not-found">
<?php if ( current_user_can( 'edit_posts' ) ) : ?>
<header class="entry-header">
<h1 class="entry-title"><?php _e( 'No posts to display', 'twentytwelve' ); ?></h1>
</header>
<div class="entry-content">
<p><?php printf( __( 'Ready to publish your first post? <a href="%s">Get started here</a>.', 'twentytwelve' ), admin_url( 'post-new.php' ) ); ?></p>
</div>
current_user_can()
:判断当前用户是否有某个权限,比如编辑文章(edit_posts)。
_e()
:简单理解为获取字符串在当前语言下显示的内容,一般你的主题不做多语言版本的话不会用这个。__()
:和上面作用一样,只不过只获取值,不打印出来。admin_url()
:获取当前站点 Wordpress 后台的地址,比如“http://sxlf.org/wp-admin/”,带一个参数代表后台的具体页面,这里 post-new.php
是新建文章的页面。
没有文章,如果你登录了且有编辑权限就显示一个新建文章的链接,否则执行下面的代码。
<?php else : ?>
<header class="entry-header">
<h1 class="entry-title"><?php _e( 'Nothing Found', 'twentytwelve' ); ?></h1>
</header>
<div class="entry-content">
<p><?php _e( 'Apologies, but no results were found. Perhaps searching will help find a related post.', 'twentytwelve' ); ?></p>
<?php get_search_form(); ?>
</div>
<?php endif; ?>
</article>
<?php endif; ?>
get_search_form()
:获取搜索表单的内容。如果想主题有搜索功能的话就用它。
主体部分到此结束,最后就是获取侧边栏模板(sidebar.php)和底部模板(footer.php)的内容了。
<?php get_sidebar(); ?>
<?php get_footer(); ?>
标签:模版