`
baiyuxiong
  • 浏览: 175290 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

【转载】wordpress源代码分析之the_meta函数和get_post_meta函数

    博客分类:
  • php
阅读更多
http://www.hzynh.cn/html/wordpress-source-code-analysis-the_meta-function-and-get_post_meta-function.html

在这篇wordpress源代码分析里,我将介绍the_meta函数和 get_post_meta函数。

很多时候你除了wordpress默认的功能外,还有很多奇思妙想,但是又没有精力去修改代码,怎么办呢?在你编写帖子的时候会在edit下面看见 custom fields,就是自定义字段,你可以在这里很方便的增加你自己的新特性。

当你输入这些自定义字段的时候,这些字段会以名值对(key-value)的形式储存起来并发布到你的帖子中,然后用the_meta()函数去显 示这些数值。

the_meta是个模板函数,没有参数,直接调用就会把所有你的特性现实出来。

当然,如果你想控制的更细致一些,你可以用get_post_meta()来做。

get_post_meta的格式是:

get_post_meta($post_id, $key, $single = true)

其中post_id是帖子id,key就是meta的名,而single如果为true则只显示单个结果,否则可以显示一个数组的返回集合。

example:

如果你又一个类似discuz论坛那样的法帖心情字段,你可以这样:

get_post_meta($post->ID, “feeling″, $single = true);

而更进一步你有图片表示你的心情,可以这样

<img src=”/uploads/<?php echo get_post_meta($post->ID, “feeling”, $single = true); ?>.gif” alt=”feeling” />

如果你返回值是多个,那么将$single = false 就可以了



一个比较简单的使用实例就是:在首页提取文章的缩略图

当添加文章的时候,使用一个自定义字段如:thumbnail,同时给这个字段的value为一张图片,然后再在首页调用,就OK了.

<div class="thumbnail">

        <?php if ( get_post_meta($post->ID, ‘thumbnail’, true) ) : ?>
               
            <?$image = get_post_meta($post->ID, ‘thumbnail’, true); ?>

            <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php echo $image; ?>" alt="<?php the_title(); ?>"/></a>
        <?php else: ?>
                <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php the_title(); ?>"><img src="<?php bloginfo(‘template_directory’); ?>/images/random/tb<?php echo rand(1,15)?>.jpg" alt="<?php the_title(); ?>" /></a>
        <?php endif; ?>
           
    </div>

此文章就是添加了一个字段thumbnail,然后再给一张图片,就可以了.详细见首页或者分类页.
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics