无法通过 get_post_meta() 从自定义插件检索 ACF 字段

Cannot retrieve ACF fields from a custom plugin through get_post_meta()

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

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

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

我尝试了 ACF 网站上的 get_field()the_field()get_sub_field() 功能,但 none 可以正常工作。

编辑: 这是使用 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).

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

正如我们在评论中讨论的那样,如果您没有在 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,它根本不需要字段参数,因为它returns 所有个字段在一个数组中。如果需要,您可以将 post id 作为第一个参数传递,例如

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

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