【问题标题】:Cannot retrieve ACF fields from a custom plugin through get_post_meta()无法通过 get_post_meta() 从自定义插件中检索 ACF 字段
【发布时间】:2020-10-13 15:50:20
【问题描述】:

我正在开发一个插件来将自定义帖子数据添加到前端。我正在使用高级自定义字段插件向编辑器添加自定义字段。

更新帖子后,我应该通过get_post_meta() 获取所有自定义字段值,但它只显示默认元字段,而不是自定义字段。我有两个单独的组字段,每个字段都有 2 个文本字段。我期待得到一个数组或对象。

我尝试添加单个文本字段并向其中添加数据,只是为了查看组字段是否导致任何问题。但没有运气。

我尝试了 ACF 网站上的 get_field()the_field()get_sub_field() 函数,但没有一个能正常工作。

编辑: 这是使用get_post_meta()的代码

<?php
    global $post;
    $temp = get_post_meta($post->ID);
   
    /* PRINT THE ARRAY */
    echo "<pre>";
    print_r($temp);
    echo "</pre>";
?>

这是使用get_field()的代码

<?php
    $temp = get_field("field1"); // 'field1' is a one simple text field.
   
    /* PRINT THE ARRAY */
    echo "<pre>";
    print_r($temp);
    echo "</pre>";
?>

这是使用the_field()的代码

<?php
    $temp = the_field("field1"); // 'field1' is a one simple text field.
   
    /* PRINT THE ARRAY */
    echo "<pre>";
    print_r($temp);
    echo "</pre>";
?>

这是使用get_sub_field()的代码

<?php
    /* 'section_1' is a group consist of 2 text fields + another group with 2 
    text field. */
    $temp = the_field("section_1");
   
    /* PRINT THE ARRAY */
    echo "<pre>";
    print_r($temp);
    echo "</pre>";
?>

注意:以上代码位于主插件的子文件夹中的一个文件中。我想做的是改变默认博客页面的布局。在插件的 function.php 中,我使用自定义文件路径更改了默认布局路径。

这是function.php

add_filter('single_template', 'my_custom_template', 99);

function my_custom_template($single) {
    global $post;

    if ( $post->post_type == 'post' ) {
        if ( file_exists( plugin_dir_path(__FILE__)  . '/templates/style1/style1.php' ) ) {
            return plugin_dir_path(__FILE__)  . '/templates/style1/style1.php';
        }
    }

    return $single;
}

更新当我尝试var_dump(get_fields()); 时,它返回了bool(false)

【问题讨论】:

  • 向我们展示您的代码。你说你试过get_fields(),但后来你是怎么用的?
  • 编辑您的问题以显示您的代码。没有它,我们只能猜测你做了什么。
  • 您的代码仍未添加。只是放入您尝试过的功能并没有帮助。你是如何使用这些功能的?向我们展示一些上下文。在获得更多信息之前,我们无能为力。
  • 我遇到过类似的问题,即当从另一个插件调用时,函数挂钩的时间不够晚。您需要使用稍后的钩子,例如acf/init,或者您需要使用默认的get_post_meta() 函数(请记住,您需要将组键添加到组的子字段键:bohanintl.com/wptips/plugins/…)跨度>
  • 这不是你使用get_fields的方式。您不向其传递字段名称 - 默认情况下它会返回所有字段。做一个var_dump(get_fields());,让我们知道它显示了什么。

标签: wordpress advanced-custom-fields


【解决方案1】:

ACF 字段不保存为 post meta,它们在 WP 数据库中使用自己的自定义字段。因此,您需要使用 ACF 函数来获取值。

正如我们在 cmets 中所讨论的,如果您没有在 Wordpress“循环”中使用 ACF 函数,则需要传入 post id,例如

 // post id is the 2nd parameter, but it is only needed if you are not in the loop
$fieldvalue = get_field($fieldname, $postid);
echo $fieldvalue;

// also note that the_field doesn't return the value like get_field -
// it prints it out just like if you used echo with get_field
the_field($fieldname, $postid);

对于get_fields,它根本不接受字段参数,因为它返回数组中的所有 个字段。如果需要,可以将帖子 ID 作为第一个参数传递,例如

$allfields = get_fields($posttestid);
print_r($allfields);

你可以看到更多关于ACF functions here

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-13
    • 2017-06-02
    • 2016-06-08
    • 1970-01-01
    • 1970-01-01
    • 2019-04-11
    • 1970-01-01
    相关资源
    最近更新 更多