【问题标题】:How to pull custom field data into Wordpress shortcodes如何将自定义字段数据提取到 Wordpress 简码中
【发布时间】:2014-03-21 11:50:10
【问题描述】:

我正在创建一系列短代码,这些短代码链接到名为 heroes 的自定义帖子类型上的页面。我想知道如何将我的简码中的信息链接到该自定义帖子类型的帖子,以便我可以将自定义字段数据拉入简码中使用。

这是我正在使用的简码

add_shortcode('illidan', 'illidan');

function illidan($args) {
    $default = array('icon' => 'true');
    $args = wp_parse_args($args, $default);

    $herotip = '';
    if ($args['icon']) {
        $herotip.= '<img src="http://stormable.com/img/heroes/illidan/illidan-ab1.png">';
    }

    $herotip.= '<a href="http://stormable.com/heroes/illidan/">Illidan</a>
    This is where I would like to pull in custom field data from the post illidan
    For example <?php echo get_post_meta($post->ID, "health-lvl1", true); ?>
    ';

    return $herotip;
}

所以在链接下,我希望能够在自定义帖子类型heroes 下的帖子Illidan 中提取自定义字段中的数据,尽管我不确定如何将其链接到该页面.

【问题讨论】:

  • global $post 是您访问当前帖子所需的全部内容。
  • 谢谢,但问题是这不会出现在当前帖子中,它将是整个网站的其他帖子。
  • 然后您需要根据您的要求创建一个新查询,然后执行正常的循环迭代。 if($posts-&gt;have_posts(); while($posts-&gt;have_posts()): $posts-&gt;the_post(); // endwhile; endif;
  • 如何将其添加到我的简码中?把php直接放进去?
  • 所以,Illidan 帖子的 URL 如下:http://stormable.com/heroes/illidan/? URL 会改变吗?还是帖子 ID?

标签: php wordpress custom-fields shortcode


【解决方案1】:

这会从帖子元返回自定义字段值

 // returns the value of health-gain
 $health_gain = get_post_meta( 11, 'health-gain', true); 


 $herotip.= '<a href="http://stormable.com/heroes/illidan/">Illidan</a>
This is where I would like to pull in custom field data from the post illidan
For example '. $health_gain;

查看此链接get_post_meta(),将其实施到您想要的任何地方的简码函数中。

我建议你看看这篇文章http://wp.smashingmagazine.com/2012/05/01/wordpress-shortcodes-complete-guide/,告诉你创建短代码的更健壮和正确的方法。

【讨论】:

  • 谢谢,我一直使用那篇文章作为指导,虽然我还不是 PHP 方面的佼佼者。如何回显 get_post_meta(11, 'health-gain');在我与链接一起拥有的 '' 中,因为看起来我放在那里的任何东西都显示为 HTML
  • 谢谢你,效果很好,最后一个问题。在 get_post_meta 下而不是使用 post id 号有没有办法使用 post slug 代替?
  • @Greenhoe 为此,您必须使用 WP_Query,并且必须进行查询以在特定 post_type(heroes) 下找到特定的帖子名称 (illidan),这将返回您该特定的帖子 ID发布。
  • @Greenhoe 但如果您在每个帖子中都有相同的自定义字段,那么您必须使用 $post-&gt;ID 而不是 WP_Query 与全局 $post;
猜你喜欢
  • 1970-01-01
  • 2019-08-21
  • 2023-03-04
  • 1970-01-01
  • 2014-02-06
  • 2019-04-18
  • 1970-01-01
  • 2018-07-12
  • 2012-06-26
相关资源
最近更新 更多