We’ve got a file structure in place, now let’s start adding things to them!

First, we’re going to add some PHP functions to our theme. These functions will serve a variety of purposes, including:

  • adding support for WordPress features such as custom backgrounds, headers, post formats, etc
  • setting up theme defaults
  • acting as “containers” for code we can reuse throughout the theme

Files we’ll edit or create in this lesson

  • functions.php
  • inc/template-tags.php
  • inc/tweaks.php

If you’re new to PHP, then think of a function as a “machine” that performs a specific task, whenever we need it to, We define functions like this:

1
2
3
function my_function() {
  ...contents of the function
}

After we’ve defined a function, we can call it into our theme files wherever we need it to execute its magic. A function call can be as simple as writing the function name followed by a semicolon:

1
2
3
<div>
    <?php my_function(); ?>
</div>

Other function calls are a little more complex.

1
2
3
<div>
    <?php my_second_function( 'parameter 1', 'parameter 2' ); ?>
</div>

In the above example, we are passing parameters into our function. Parameters are a type of variable that you input, or pass, into the function. The function then uses it to produce the final output. It’s sort of like those penny press machines at zoos and museums.

We’ll be calling lots of functions into our theme!

Functions.php

Without delay, let’s get started. In the theme directory you created last lesson, open functions.php. At the top, paste the following:

1
2
3
4
5
6
7
<?php
/**
 * Shape functions and definitions
 *
 * @package Shape
 * @since Shape 1.0
 */

If you’re new to PHP, we start off the file with the opening PHP tag: <?php.

Next, we have a comment block with some inline documentation: a brief description of the file, followed by the PHPdoc Tags: “@package and @since”. You can read more about Inline Documentation on the WordPress Codex.

A word about PHP comments. You might be familiar with HTML comments: In PHP, you’ll find two types of comments, multi-line and single-line. Multi-line comments are wrapped between /* and */, while a single-line comment starts off with a double-slash (//). PHP will ignore the comments, so they’re great for inline documentation.

$content_width

$content_width is a global variable that sets the maximum width of content (such as uploaded images) in your theme. It prevents large images from overflowing the main content area. We should set the value of $content_width to match the width of our main content area. Thinking back to our HTML structure, this area is the #content div. We’ll use CSS to set the width of the div, however, we haven’t gotten to CSS yet. So for now, I’ll tell you that the div will be 654px wide, and we’ll revisit it later, during the CSS lesson.

In functions.php, skip a line after the last */, and paste this code:

1
2
3
4
5
6
7
/**
 * Set the content width based on the theme's design and stylesheet.
 *
 * @since Shape 1.0
 */
if ( ! isset( $content_width ) )
    $content_width = 654; /* pixels */

So, $content_width is set! PHP variables have a dollar sign (“$”) before their names, and a semi-colon (“;”) after the assigned value.

shape_setup()

Next, we’re going to create a function that sets up theme defaults and registers support for various WordPress features. Skip a line after the $content_width declaration, and add this.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
if ( ! function_exists( 'shape_setup' ) ):
/**
 * Sets up theme defaults and registers support for various WordPress features.
 *
 * Note that this function is hooked into the after_setup_theme hook, which runs
 * before the init hook. The init hook is too late for some features, such as indicating
 * support post thumbnails.
 *
 * @since Shape 1.0
 */
function shape_setup() {
 
    /**
     * Custom template tags for this theme.
     */
    require( get_template_directory() . '/inc/template-tags.php' );
 
    /**
     * Custom functions that act independently of the theme templates
     */
    require( get_template_directory() . '/inc/tweaks.php' );
 
    /**
     * Make theme available for translation
     * Translations can be filed in the /languages/ directory
     * If you're building a theme based on Shape, use a find and replace
     * to change 'shape' to the name of your theme in all the template files
     */
    load_theme_textdomain( 'shape', get_template_directory() . '/languages' );
 
    /**
     * Add default posts and comments RSS feed links to head
     */
    add_theme_support( 'automatic-feed-links' );
 
    /**
     * Enable support for the Aside Post Format
     */
    add_theme_support( 'post-formats', array( 'aside' ) );
 
    /**
     * This theme uses wp_nav_menu() in one location.
     */
    register_nav_menus( array(
        'primary' => __( 'Primary Menu', 'shape' ),
    ) );
}
endif; // shape_setup
add_action( 'after_setup_theme', 'shape_setup' );

This code is well-commented, so you can get a good idea of what it’s doing. Did you notice that it’s mostly function calls? Can you spot the functions that take parameters?

Let’s walk through it, function by function.

We’re calling in two files that will live in our inc/ directory, template-tags.php and tweaks.php. We’ll create these files a little bit later in the lesson.

Next, we call the load_theme_textdomain() function. This tells WordPress we want to make our theme available for translation and that translation files can be found in our theme folder in a folder called “languages”. If you’re going to create a WordPress Theme, you should always try your best to make sure everything is translatable. You never know when you or someone else is going to need hard-coded content available in another language. There are several ways to make text translatable, and I’ll point these out when we get to them. If you just can’t wait, I18n for WordPress Developers is a great introduction.

All right, moving right along. The next two functions add support for links to your RSS feeds in the header; and for the Aside Post Format, respectively. The last function registers one navigation menu location, which we’ll use for our main menu.

Next, we close the function with a right curly brace “}”, and call it into our theme by “hooking” it onto another WordPress function:

add_action( 'after_setup_theme', 'shape_setup' );

In simplest terms, we’re telling WordPress to run shape_setup() when it runs the after_setup_theme() function. Did you notice that add_action() is itself a function, and that we’ve fed it two parameters?

We’ll add more things to functions.php in later lessons, but for now, we’re done with it.

You might have noticed that functions.php has no closing PHP tag (“?>”). When a file is mostly PHP, it’s safer to omit the closing tag. Why? Because it helps us to avoid errors caused by trailing white space after the closing PHP tag.

Template-tags.php and Tweaks.php

Remember these lines from earlier in this lesson?

1
2
3
4
5
6
7
8
9
/**
     * Custom template tags for this theme.
     */
    require( get_template_directory() . '/inc/template-tags.php' );
 
    /**
     * Custom functions that act independently of the theme templates
     */
    require( get_template_directory() . '/inc/tweaks.php' );

Go ahead and create template-tags.php and tweaks.php in your inc directory. Why are we placing these custom functions in separate files? Mostly to keep our functions.php clean, and to keep our theme modular. If you don’t need these functions in your theme, simply remove these lines.

template-tags.php

First things first. What, exactly, is a template tag? A function, of course! (“Function” seems to be the magic word in this lesson). Specifically, they’re WordPress functions that you insert within your theme to display dynamic information. You can learn everything you want to know about template tags on the WordPress Codex.

Most of the time, we’ll add template tags to our theme wherever we want them. However, there will be times when we put multiple template tags together to output a symphony of data. And because we “play” some of these “symphonies” more than once in our theme, it’s a good idea to place all of those tags into a function that we can call whenever we want to use them. So, think of all of the functions we’re going to add to this file as “mini-symphonies” of template tags that work together to produce a block of information: a sentence that says when a post was published, and by whom; or a set of previous and next post links; or a list of comments. You get the idea. We “write” the symphony once, and “play” it many times. Or, in technical terms: we define the function once, and call it many times.

In order to keep this lesson from becoming too long, we’ll return totemplate-tags.php in later lessons to add functions as we need them. For now, let’s just add the basic documentation to the top of the file.

1
2
3
4
5
6
7
8
9
<?php
/**
 * Custom template tags for this theme.
 *
 * Eventually, some of the functionality here could be replaced by core features
 *
 * @package Shape
 * @since Shape 1.0
 */

One last thing to note: “Eventually, some of the functionality here could be replaced by core features”. The functions we add here represent functionality that would be great as core WordPress features. That’ll all make more sense after we’ve added the functions, I promise.

Now, we can safely omit the closing PHP tag from this file as well.

tweaks.php

The functions we’ll place in this file don’t involve template tags. Instead, they will enhance our theme by modifying existing WordPress core features. They perform background tasks to add a little extra “awesome” to our theme.

At the top of the file, paste the usual documentation information.

1
2
3
4
5
6
7
8
9
<?php
/**
 * Custom functions that act independently of the theme templates
 *
 * Eventually, some of the functionality here could be replaced by core features
 *
 * @package Shape
 * @since Shape 1.0
 */

Next, paste the following functions.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
 * Get our wp_nav_menu() fallback, wp_page_menu(), to show a home link.
 *
 * @since Shape 1.0
 */
function shape_page_menu_args( $args ) {
    $args['show_home'] = true;
    return $args;
}
add_filter( 'wp_page_menu_args', 'shape_page_menu_args' );
 
/**
 * Adds custom classes to the array of body classes.
 *
 * @since Shape 1.0
 */
function shape_body_classes( $classes ) {
    // Adds a class of group-blog to blogs with more than 1 published author
    if ( is_multi_author() ) {
        $classes[] = 'group-blog';
    }
 
    return $classes;
}
add_filter( 'body_class', 'shape_body_classes' );
 
/**
 * Filter in a link to a content ID attribute for the next/previous image links on image attachment pages
 *
 * @since Shape 1.0
 */
function shape_enhanced_image_navigation( $url, $id ) {
    if ( ! is_attachment() && ! wp_attachment_is_image( $id ) )
        return $url;
 
    $image = get_post( $id );
    if ( ! empty( $image->post_parent ) && $image->post_parent != $id )
        $url .= '#main';
 
    return $url;
}
add_filter( 'attachment_link', 'shape_enhanced_image_navigation', 10, 2 );

The first function, shape_page_menu_args, has to do with our main navigation menu. We registered support for navigation menus earlier, inshape_setup(). If no navigation menu has been configured, WordPress will instead display a list of Pages (controlled bywp_page_menu()). This function adds a home page link to this list of pages.

In the second function, shape_body_classes(), we’re adding a new CSS class, ‘group-blog’, to our theme’s tag. We’ll talk about body classes in the WordPress Header Template lesson, but for now, just understand that body classes give us a way to style parts of our theme based on various conditions (such as, the type of page we’re viewing, or the number of published authors we have).

Finally, the third function, shape_enhanced_image_navigation(), adds a “#main” to the end of the next/previous image links on attachment pages (which we’ll build in a later lesson). Recall that “#main” is the ID name of the div that wraps our content and widget areas. IDs are also anchors within the page. When people click on your next/previous image links, they won’t have to scroll down from the top of the page to view each image.

And that’s it for tweaks.php. Remember, no closing PHP tag is needed at the end of the file.

Whew! That’s a lot of functions. We’ve laid a lot of groundwork in this lesson! There’s still much more to come, so stay tuned.

WordPress 主题开发 - (六) 创建主题函数 待翻译的更多相关文章

  1. WordPress 主题开发 - (四) 创建WordPress的主题HTML结构 待翻译

    Now we're starting to get into the real meat of WordPress Theme development: coding the HTML structu ...

  2. WordPress 主题开发 - (二) 理解主题 待翻译

    What is “Theme Sense”? What is “Theme Sense”? Theme Sense is an intuitive understanding of WordPress ...

  3. WordPress 主题开发 - (七) 让主题更安全 待翻译

    We're just about ready to start building our theme's template files. Before we do this, however, it' ...

  4. 驱动开发之 创建线程函数PsCreateSystemThread

    PsCreateSystemThread 创建一个执行在内核模式的系统线程. 注意:创建线程必须用函数PsTerminateSystemThread强制线程结束.否则该线程是无法自动退出的. 函数原型 ...

  5. 从无到有开发自己的Wordpress博客主题---创建主题

    上一篇教程,我们已经安装了Wordpress,我们可以成功的登录到Wordpress后台,接下来的任务就是创建我们自己的主题. 要想创建一个Wordpress主题,就必须按照Wordpress的规则, ...

  6. 黄聪:《跟黄聪学WordPress主题开发》

    又一个作品完成!<跟黄聪学Wordpress主题开发>,国内最好的Wordpress主题模版开发视频教程!! 目录预览: WordPress官方源文件层式结构讲解 WordPress数据库 ...

  7. wordpress 主题开发

    https://yusi123.com/3205.html https://themeshaper.com/2012/10/22/the-themeshaper-wordpress-theme-tut ...

  8. WordPress 主题开发:从入门到精通(必读)

    本专栏介绍如何开发设计你自己的 WordPress 主题.如果你希望了解更多如何安装和应用主题的内容,请参阅应用主题文档.本文的内容不同于应用主题,因为所讨论的是编写代码去构建你自己的主题的技术内容, ...

  9. [转]WordPress主题开发:主题初始化

    本文转自:http://www.cnblogs.com/tinyphp/p/4391182.html 在最简单的情况下,一个WordPress主题由两个文件构成: index.php -------- ...

随机推荐

  1. Hibernate 实体关联关系映射【转】

    Hibernate关联关系映射目录│ ├─单向关联│  ├─  一对一外键单向关联│  ├─  一对一主键单向关联│  ├─  一对一连接表单向关联│  ├─  一对多外键单向关联│  ├─  一对多 ...

  2. 页面设计--CheckBoxList

    CheckBoxList 下拉多选控件 控件属性如下图: 取值设置:多选只能从数据库表中来获取:支持过滤条件设置(支持权限条件值.控件值条件.系统变量值等做为过滤条件) web效果显示:

  3. Network of Schools(强连通分量缩点(邻接表&矩阵))

    Description A number of schools are connected to a computer network. Agreements have been developed ...

  4. GoldenGate: Extract Abend with Detect Inconsistency in Pdata (文档 ID 1355067.1)

    APPLIES TO: Oracle GoldenGate - Version 10.4.0.0 and laterInformation in this document applies to an ...

  5. 尼姆博弈HDU1907

    HDU1907 http://acm.hdu.edu.cn/showproblem.php?pid=1907 两种情况1.当全是1时,要看堆数的奇偶性 2.判断是奇异局势还是非奇异局势 代码: #in ...

  6. 直接使用editbox.clear()清空时,有时会无法清除完全,此时有清空文本框的另一种方法

    editbox = driver.find_element_by_id("id") editbox.click() content = editbox.get_attribute( ...

  7. Unity Shader : Ghost(残影) v1

    前阵子组长给我提了个需求,要实现角色人物的残影.我百度google了一下,发现可以用两种方式实现这个效果:1.记录前几帧的人物位置,将其传入shader中,对每个位置进行一个pass渲染.2. 通过相 ...

  8. Unity3D 新人学习的一点感想

    想到那里写到那里吧 1.Unity3D的优点大家都知道:组件化.c#语言.可见即所得. 当初刚开始学习的是cocos2dx,c++的货,觉得还是写的不错的,也是国人开发的,真的代码很容易懂,直接看引擎 ...

  9. 天气预报API简单实现

    本人小白,觉得好玩,就注册了一个博客.一时也不知道写些什么,就把昨天做的一个简单的网页天气预报写一下吧,希望对各位看官有所帮助. 运行环境:php+mysql+WIN/Linux,框架什么的都无所谓了 ...

  10. [oracle] listener.ora 、sqlnet.ora 、tnsnames.ora

    路径 $ORACLE_HOME/network/admin sqlnet.ora(客户及服务器端) 作用类似于linux或者其他unix的nsswitch.conf文件,通过这个文件来决定怎么样找一个 ...