通过Function设置变量名称和值


Set variable name and value through Function

Hallo我正在尝试创建一个带有两个参数的函数
参数ONE应该设置变量名,参数TWO设置自定义字段的名称,该字段是变量的值。

我需要一个函数,因为变量应该从不同页面的自定义字段中获取值,具体取决于
-如果{它的父级具有ID 77,则获取它自己的字段}
-否则{如果它的父字段没有ID 77,则获取其父字段}

这是我尝试过的,但还不起作用:

function variable_is_field($variable, $field) {
    global $post;
    if($post->post_parent == 77)        // if page parent ID=77
                $variable = get_field($field); 
    else 
                $variable = get_field($field, $post->post_parent;); 
}
variable_is_field("$my-variable1", "my-custom-field1");
echo $my-variable1;

知道代码出了什么问题吗?

我可以提出两个解决方案

如果你只需要它在这个范围和一次类似的评论建议,那么代码将是:

function variable_is_field($field) {
    global $post;
    $variable = null;
    if($post && $post->post_parent == 77)        // if page parent ID=77
                $variable = get_field($field); 
    else 
                $variable = get_field($field, $post->post_parent;); 
    return $variable ;
}
$my-variable1 = variable_is_field("my-custom-field1");
echo $my-variable1;

否则,如果你在全球范围内需要它,你可以尝试一些类似dis 的方法

global $my-variable1;
function variable_is_field($field) {
        global $post;
        global $my-variable1;
        if($post && $post->post_parent == 77)        // if page parent ID=77
                    $my-variable1= get_field($field); 
        else 
                    $my-variable1 = get_field($field, $post->post_parent;); 
    }
variable_is_field("my-custom-field1");
echo $my-variable1;

希望这能有所帮助。