使用 foreach 循环时似乎没有调用函数

Function does not seem to get called when using a foreach loop

我不太了解 PHP,但我需要写几行代码来将自定义键添加到我在 WordPress 中的 API 的响应中:

<?php
$customFields = array("maker", "model", "ou", "prod_year", "barrel_length", "stock", "stock_length", "ejector", "links",
    "chokes", "condition", "original_case", "price");

function rest_get_post_field( $post, $field_name, $request ) {
    return get_post_meta( $post[ 'id' ], $field_name, true );
}

add_action( 'rest_api_init', 'add_custom_fields' );
function add_custom_fields(){
    foreach($customFields as $field) {
        register_rest_field( 'post',$field,
        array(
            'get_callback'  => 'rest_get_post_field',
            'update_callback'   => null,
            'schema'            => null,)
        );
    }
}

?>

上面的代码不起作用。起初我打算为每个自定义字段调用 register_rest_field 方法,例如:

function add_custom_fields(){
        register_rest_field( 'post','maker',
        array(
            'get_callback'  => 'rest_get_post_field',
            'update_callback'   => null,
            'schema'            => null,)
);

我已经测试过这个并且它有效。但是,创建自定义字段名称的字符串数组然后循环遍历它们似乎是一个更好的解决方案,代码行更少。有没有办法使这项工作?谢谢。

由于您的 customFields 变量不是全局变量,函数会将其解释为 null。您需要将自定义键数组作为函数的参数传递。

function add_custom_fields($fields)
{
    foreach($fields as $field) {
        register_rest_field( 'post',$field,
        array(
            'get_callback'  => 'rest_get_post_field',
            'update_callback'   => null,
            'schema'            => null,)
        );
    }
}

然后,在您的 add_action 函数中指定您需要传递一个参数。

add_action('rest_api_init', 'add_custom_fields', 10, 1);

最后,调用您的 do_action 函数,指定 customFields 变量作为函数的参数。

do_action('rest_api_init', $customFields)

查看更多信息:Function arguments


或者(如果您必须做的事情允许的话),只需在您的函数中定义您的自定义键数组。

function add_custom_fields()
{
    $customFields = array("maker", "model", "ou", "prod_year", "barrel_length", "stock", "stock_length", "ejector", "links", "chokes", "condition", "original_case", "price");
    foreach($customFields as $field) {
        register_rest_field( 'post',$field,
        array(
            'get_callback'  => 'rest_get_post_field',
            'update_callback'   => null,
            'schema'            => null,)
        );
    }
}