WordPress主题文件Functions.php介绍教程

cn4jd的头像

如果你是一个有抱负的Wordpress开发者,一个最重要的文件你必须要掌握的就是functions.php文件。

如果你在开发或修改一个Wordpress主题,你需要知道如何得到最有效的funcations.php文件。

我们开始教你11个常用函数的例子,你只需添加一小段代码。

介绍functions.php文件

tutuploadsmedia_1336691010658_f605698d1fa26c76c5620ede1645a30b.png
你的functions.php文件一般在 /wp-content/themes/your_theme_name/functions.php

为存在的主题修改的最佳选择就是使用它的子主题,这种方式当你更新你的主题,你更改不会被覆盖。如果你需要创建一个子主题请查看此教程: http://www.ostraining.com/blog/wordpress/child-theme/

注意:在wp-includes文件夹下也有一个functions.php文件,除非你是代码高手请不要使用修改它。

我们推荐的做法是粘贴你所有新的代码到funcations.php文件最底部,这里是如何做的:

  • 用脚本编辑器打开functions.php文件
  • 滚动到底部
  • 找到最后一行
  • 在最后一行之后粘贴代码
  • 保存文件
tutuploadsmedia_1337285401705.png

例 1: Google Analytics(谷歌分析)

tutuploadsmedia_1337285268007.png

粘贴它,你的php函数将添加代码到所有你拥有footer(页脚)的页面.

第一行add_action('wp_footer', 'add_googleanalytics'); 指定我将添加google analytics(谷歌分析)到使用的footer(页脚),这里叫做 "hook"钩子. 要使用它,从你的google analytics(谷歌分析) code from google and并替换这行 "// Paste your Google Analytics code here" 用你实际从谷歌得到的代码,确保你移除了//注释标记。

<?php
add_action('wp_footer', 'add_googleanalytics');
function add_googleanalytics() { ?>
// 粘贴你的Google Analytics代码到这里
<?php } ?>

例 2:在页面添加一个摘要

tutuploadsmedia_1337285426962.png

WordPress Excerpt(摘要)是一个可选的总结或一篇文章的描述; 简短, 文章总结。Excerpt(摘要)有两个主要作用: 在RSS订阅中替换全部内容当 Dashboard › Settings › Reading 显示总结选项选中时,根据WordPress主题,它可以显示在:想搜索结果,标签存档,分类存档,每月存档,和作者存档,快速总结替代全部内容

但是这只是在标准主题中的文章类型可以用,页面类型不可以。在WordPress页面中把摘要作为一项标准功能,现在已经消失。但是幸运的是可以很容易的用一行简单的代码把摘要框放置回 Add New Page(新建页面)编辑器中。

代码如下:

add_post_type_support( 'page', 'excerpt' );

你将看到一个摘要框显示在编辑页面(如果不可见,检查“显示选项”中选项是否选中)

例 3: 移除WordPress版本号

tutuploadsmedia_1337290638631.png

简单的使用浏览页面代码可以查看WordPress版本生产器产生的版本号,. 如果一些原因导致你必须使用旧版本的WordPress,这将给你带来一些风险。 最佳的防范就是保持运行最新版本,一些人建议没必要移除版本号因为黑客也有其他办法来找到你目前运行的版本,其他人则推荐你移除,如果你想这样做,这里有使用functions.php文件的正确的方法

1.function i_want_no_generators()
2.{
3.return '';
4.}
5.add_filter('the_generator','i_want_no_generators');
tutuploadsmedia_1337290759522.png

版本信息将不再生成并且在源代码中不可见

例 4: 添加一个Favicon(图标)到你的主题

tutuploadsmedia_1337291305748.png

大部分人想用自己的特色品牌代替小图标(favicon). It really lends a professional and finished look to a theme. First you'll have to create the icon. You can use one of the many free icon generators on the web. Just google "icon generator" and you'll find a good one. Then upload a copy of the icon to the main WordPress directory, and one to your theme's directory. Add the code to functions.php and you're good to go.

1.function blog_favicon() {
2.echo '<link rel="Shortcut Icon" type="image/x-icon" href="https://cn4jd.com/%27.get_bloginfo%28%27wpurl%27%29.%27http%3A/wordpress.dashhelp.com/favicon.ico" />';
3.}
4.add_action('wp_head', 'blog_favicon');

例 5: 始终更新版权日期

tutuploadsmedia_1337294458098.png

Above is a typical copyright notice. Usually people put the copyright somewhere in the footer, and its basically a static date, or could be a dynamic date showing just one year. But there's a way to make it more accurate and cover your entire career as a publisher. This function call will get the date of the first post and the date of the last post so you can publish them.

Working it into your functions.php file is just a little more difficult because you actually have to know how to write the function and it's a bit more complicated than our previous examples. Notice that you can name the function you create anything you want as long as it doesn't conflict with any other functions.

01.function copyright_function_of_mine() {
02.global $wpdb;
03.$copyright_dates = $wpdb->get_results("
04.SELECT
05.YEAR(min(post_date_gmt)) AS firstdate,
06.YEAR(max(post_date_gmt)) AS lastdate
07.FROM
08.$wpdb->posts
09.WHERE
10.post_status = 'publish'
11.");
12.$output = '';
13.if($copyright_dates) {
14.$copyright = "© " . $copyright_dates[0]->firstdate;
15.if($copyright_dates[0]->firstdate != $copyright_dates[0]->lastdate) {
16.$copyright .= '-' . $copyright_dates[0]->lastdate;
17.}
18.$output = $copyright;
19.}
20.return $output;
21.}

After you get this into your functions.php file, you just need to add this code to your footer.php or wherever you want the dates to show up.

1.<?php echo copyright_function_of_mine(); ?>
tutuploadsmedia_1337293791509.png

This is what I added to my footer.php file. You can add text and html or css to the footer to add style.

tutuploadsmedia_1337293738403.png

Here's what it looks like on the site. It shows the year of my first post and my last. The copyright is completely up to date.

例 6: 开启文章缩略图

tutuploadsmedia_1337300268164.png

Post thumbnails are a function of wordpress. But you need to let your theme know that you want to use the feature. Here's how you turn on the post thumbnails. It's very easy to add the function to the template. It becomes more complex when it comes to styling the pictures, though. We're only covering the functions.php file in this tutorial. We're just going to show you the first step.

First you activate the function with this line in functions.php

1.add_theme_support( 'post-thumbnails' );

Now, just like with the copyright example, you have to put some code into the site somewhere that will call the results of the function and display it. With the copyright example we placed the function call in the footer. With this, since it's something that is dynamically associated with each post, it goes in the Loop. You just need to add this one line to the Loop put the picture where you want it.

1.get_the_post_thumbnail($id, $size, $attr )

The Loop is used by WordPress to display each of your posts. Using The Loop, WordPress processes each of the posts to be displayed on the current page and formats them according to how they match specified criteria within The Loop tags. Any HTML or PHP code placed in the Loop will be repeated on each post. When WordPress documentation states "This tag must be within The Loop", such as for specific template tags or plugins, the tag will be repeated for each post. You can learn more about the Loop in the Codex.

The Loop is found inside the templates index.php file. You would need to place this code between the start and end of the post loop. The loop starts with:

1.<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>

and ends with:

1.<?php endwhile; else: ?>
2.<p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
3.<?php endif; ?>

You'd place your code anywhere between those two lines that doesn't interfere with any other code.

This will get the picture into the post. The terms $id, $size, and $attr will dictate how it displays and what it looks like. This involves creating arrays and some more advanced programming which is more advanced than we want to get with this introduction. Here's a complete reference to post thumbnails in the Codex.

Be sure to take our PHP, HTML, and CSS courses first if you don't have much experience with this. You will learn everything you need in those courses. Also watch for our soon to be released WordPress Theming course, which we will announce in our newsletter and on our site.

例 7:添加支持自定义文章格式

tutuploadsmedia_1337301989977.png

Something not often understood in WordPress is the difference between Post Formats and Post Types. There are 9 post formats built into WordPress, and you may even see them listed on your post edit page. But before they will be active in your theme, you need to add support for them in the functions.php file. If you want a complete explanation of post formats, read our tutorial How to Activate WordPress Post Formats.

1.add_theme_support('post-formats', array( 'aside', 'chat', 'gallery', 'image', 'link', 'quote', 'status', 'video', 'audio'));

You won't be able to use post formats without this line in functions.php.

例 8: Enable Threaded Comments in Your Theme

tutuploadsmedia_1337307417180.png

You can turn on threaded comments from your Wordpress control panel. But when you are developing themes, you still have to write the java script in the header.php file. To avoid clutter in your header file, use functions.php instead. If you are creating several themes, think how much easier it will be to have functions enabled from a single, reproducible functions file than to have to write extra code in header files and keep track of them all.

You will know if you are using threaded comments if you see a "Reply" link in each post.

1.// enable threaded comments
2.function enable_threaded_comments(){
3.if (!is_admin()) {
4.if (is_singular() AND comments_open() AND (get_option('thread_comments') == 1))
5.wp_enqueue_script('comment-reply');
6.}
7.}
8.add_action('get_header', 'enable_threaded_comments');

This may seem unnecessary when you are using a well known theme because it's already enabled in most. But if your starting from scratch, you have to make sure it's included.

例 9: 创建Adsense的代码

tutuploadsmedia_1337306212933.png

I inserted the adsense banner in the above illustration with a single short code. All I had to do was type [adsense] into my article. You can use functions.php to create your own shortcodes. Just paste the following code into functions.php and replace the specifics with your own Adsense numbers.

01.function showads() {
02.return '<div id="adsense"><script type="text/javascript"><!–
03.google_ad_client = "pub-XXXXXXXXXXXXXX";
04.google_ad_slot = "4668915978";
05.google_ad_width = 468;
06.google_ad_height = 60;
07.//–>
08.</script>
09.<script type="text/javascript"
10.src="http://pagead2.googlesyndication.com/pagead/show_ads.js";>
11.</script></div>';
12.}
13.add_shortcode('adsense', 'showads');

例 10: 启用PayPal捐赠代码

tutuploadsmedia_1337308172644.png

There are probably a lot of times you or your clients want to drop a donation button into a post or article. Pretty easy with this code Just put in your own account info. Just use [donate shortcode] to insert the donation link. This example is a little different because it includes the link text which actually shows on the post.

01.function donate_shortcode( $atts ) {
02.extract(shortcode_atts(array(
03.'text' => 'Make a donation',
04.'account' => 'REPLACE ME',
05.'for' => '',
06.), $atts));
07.global $post;
08.if (!$for) $for = str_replace(" "," ",$post->post_title);
09.return '<a class="donateLink" href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='.$account.'&item_name=Donation for '.$for.'">'.$text.'</a>';
10.}
11.add_shortcode('donate', 'donate_shortcode');

例 11: Style Odd and Even Posts with Alternate Styles

tutuploadsmedia_1337311950364.png

As a design element it's often desirable to create different styling for every other post. suppose you wanted to alternate gray and white backgrounds. Or possibly switch the thumbnail image from left to right on alternate posts. There would be two things to do. One is create the function. The second would be to create a different css class for each, one called odd, and one called even.

You can see in the illustration that each post class now contains the words odd and even.

function oddeven_post_class ( $classes ) {
global $current_class;
$classes[] = $current_class;
$current_class = ($current_class == 'odd') ? 'even' : 'odd';
return $classes;
}
add_filter ( 'post_class' , 'oddeven_post_class' );
global $current_class;
$current_class = 'odd';
 

All that remains is for you to use your design skills and css knowledge to make it beautiful.

This was just a short intro to the power of the functions.php file. It doesn't stop here. If you are planning on developing and designing your own themes, you need to get familiar with this file, creating functions using php, and mastering css. If you don't get serious about it, there is a probably a plugin that does the same thing. That's the beauty of WordPress.

作者: 
ostraining

评论

pggdt的头像
学习了!不知道有没有办法禁用父主题中的一段php
2013-9-10/14:41:27
cn4jd的头像
cn4jd

能举个例子么?不太理解你所说的情况

2013-9-11/21:32:05

添加新评论