首页 > 解决方案 > 无法通过 get_post_meta() 从自定义插件中检索 ACF 字段

问题描述

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

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

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

我已经尝试过get_field()the_field()并且get_sub_field()来自 ACF 网站的功能,但没有一个有效。

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

标签: wordpressadvanced-custom-fields

解决方案


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

正如我们在评论中所讨论的,如果您没有在 Wordpress“循环”中使用 ACF 函数,则需要传入帖子 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 功能的更多信息


推荐阅读