Home » WordPress

WordPress的主循环及全局变量

19 04月 2010 Views: No Comment Tags:

 当我们制作 WordPress 插件的时候,首先必须要了解 WordPress 主循环全局变量。这样,我们在制作插件的时候,就可以知道可以访问哪个变量,不能访问哪个变量。

对于特定的 WordPress ActionFilters,你可以很容易知道它们在主循环中哪里执行了。然而有时你在主循环中不想使用 action 或者 filter 而只想调用模板函数(template tag )。这时候,你需要非常了解你想访问的全局变量和可能得到的结果。

下面我将讲解 WordPress 主循环,以便你能更好理解哪些全局变量可以被主循环中的模板函数调用。

WordPress 主循环 — The WordPress Loop

clip_image001

WordPress 主循环是用来在一些页面上显示日志列表和在单篇日志页面页显示留言列表的。

在默认主题的 index.php 中,主循环是以下面这些代码开始的:

<?php if (have_posts()) : ?>

<?php while (have_posts()) : the_post(); ?>

have_posts()the_post() 这两个函数都是属性函数,它们可以访问到类 WP_Query 中的方法。

have_posts 这个函数去查看当前显示的日志数是否达到了在 WordPress 后台设置的要显示的日志数,这个主循环将会继续直到达到为止。

如果你研究过 the_post 函数,你会发现它会搜索 $post 这个全局变量。 the_post 函数获取第一篇日志(随后的日志通过每次循环迭代获取),并设置日志的数据(如作者,多重-页面,等等),这些数据是 WordPress 全局的赋给 $post 这个变量,所以可以访问它。

the_post() 函数被调用之后,你就可以使用许多模板函数全局变量

下面就是现在可用的模板函数的一些例子:

下面是现在可用的全局变量:

  • 全局变量 authordata,你可以使用以下代码调用它:

· global $authordata;

echo $authordata->display_name;

通过 authordata 这个全局变量还可以让你获取:last_name,first_name,ID,user_email,user_url,user_login,description 和其他。

  • 全局变量 post,你可以使用以下代码调用它:

· global $post;

· echo $post->post_title;

通过post这个全局变量还可以让你获取:ID,post_author,post_date,post_excerpt,comment_count 和其他。

  • 全局变量 post ,你可以通过在一个函数中使用以下代码调用它:

· global $post;

· echo $post->post_content;

通过这种方法获取的日志内容是没有经过过虑的。如果你想按照你自己喜好去操纵日志的内容,比如自己设置日志内容的显示方式,通过这种方式获取的日志内容非常有用。

  • 虽然没有快速的全局访问,但是 the_permalink 这个函数作的就是输出函数 get_permalink 在 $id 这个变量已经被设定情况下的结果。
  • 全局变量 id ,你可以使用以下代码调用它:
global $id;
 
echo $id;

一个自定义模板函数的例子

假设你写了一个叫做 get_my_trackback 自定义的模板函数,它能够在留言循环中每次侦测到 trackback 的时候做出反应。我们将把这个函数放入 comment.php 模板文件的 foreach 留言循环中。

<!--p foreach ($comments as $comment) :-->
 
<!--p get_my_trackback()-->
 
<!--p endforeach; /* end for each comment */-->
 
get_my_trackback 函数代码如下:
 
<!--p function get_my_trackback() { global $comment; if (empty($comment)) return; if ($commen-->comment_type != 'comment') {
 
//do trackback stuff
 
}
 
}
 
?&gt;

clip_image002

comments 这个全局变量能够让你访问到当前留言的详细数据,所以可以让你对留言做任何事情。

结论

在这篇文章中,详细解析了 WordPress 主循环已和全局变量,所以在以后制作插件或者修改主题的时候可以非常灵活的使用它们。

翻译自:Global Variables and the WordPress Loop

转自:http://fairyfish.net/2007/07/07/global-variables-and-the-wordpress-loop/

原创文章如转载,请注明:转载自Xixis Blog [ http://www.xixis.net/ ]
本文链接地址:http://www.xixis.net/archives/wordpress-main-loop-and-the-global-variable.html

Leave your response!

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

This is a Gravatar-enabled weblog. To get your own globally-recognized-avatar, please register at Gravatar.