【问题标题】:WordPress getting custom meta value outside of loopWordPress 在循环之外获取自定义元值
【发布时间】:2019-07-11 11:29:39
【问题描述】:

我正在尝试获取自定义字段'product_url' 的值,此代码位于functions.php 中,我在单个帖子中使用短代码。自定义字段'product_url' 存在于该帖子中且不为空。

 function metavalue() {
                    GLOBAL $post;
                    $meta = get_post_meta($post->ID, 'product_url', true);
                    echo $meta;


                    }
 add_shortcode('url_short', 'metavalue');

当我使用简码时没有显示任何内容。 var_dump($meta); 会输出

字符串(0) ""

【问题讨论】:

  • 你调试过@meta在函数内不为空的代码吗?
  • 不要使用echo使用return,有时短代码会在帖子内容完成并输出之前执行时打印在奇怪的地方。或者在输出之后调用 exit,这样在页面中更容易找到它。我不确定这是否只是显示问题,但代码对我来说看起来不错。
  • 我试过用 return $meta;它仍然没有输出任何东西。
  • @Jesses 我也更新了我的代码。请调试问题。确保有价值。

标签: php wordpress


【解决方案1】:

您需要将 $postid 传递给您的 get_post_meta 函数。

 function metavalue() {
    global $post;
    $meta = get_post_meta($post->ID, 'product_url', true);
    return $meta;
  }
 add_shortcode('url_short', 'metavalue');

如何调试:

  • 检查产品或帖子是否有 product_url 值。
  • 获取产品/帖子的ID,您可以通过管理员编辑帖子/页面获取。
  • 在短代码函数中将 ID 作为静态值传递。

    function metavalue() { global $post; $meta = get_post_meta(112, 'product_url', true); // 112 static postid return $meta; } add_shortcode('url_short', 'metavalue');

第 2 版:带参数的简码

将用户属性与已知属性结合起来,并在需要时填写默认值。

对应该被认为是调用者支持并作为列表给出的所有属性。返回的属性将只包含 $pairs 列表中的属性。

如果 $atts 列表具有不受支持的属性,那么它们将被忽略并从最终返回的列表中删除。

function metavalue($atts) {

 $atts = shortcode_atts(
        array(
            'postid' => 1,            
        ), $atts, 'url_short' );
  global $post;

  $meta = get_post_meta($atts['postid'], 'product_url', true); // 112 static postid
  return $meta;
  }
 add_shortcode('url_short', 'metavalue');

使用方法:

[url_short postid=1911]

【讨论】:

  • global $post 应该包含当前帖子的 ID。例如看到这个答案stackoverflow.com/questions/4893435/…这表示添加if(empty($atts['post_id']))等不是一个糟糕的选择。
  • 如果您需要自定义 id
  • ` 函数元值() { 全局 $post; $meta = get_post_meta(1911, 'product_url', true);回声 $post->ID;返回$元; } add_shortcode('url_short', 'metavalue');` 按预期工作。当我使用 echo $post->ID 时;它将输出 215,但在管理员中,帖子 ID 为 1911。
  • 这意味着您没有查看 1911 年的帖子。
  • 您可能会收到 pages 帖子 ID。
猜你喜欢
  • 1970-01-01
  • 2010-11-26
  • 1970-01-01
  • 2017-08-31
  • 1970-01-01
  • 2016-03-05
  • 2014-11-13
  • 2016-11-30
  • 2018-09-25
相关资源
最近更新 更多