通过Function设置变量名称和值

时间:2015-04-02 17:01:55

标签: php wordpress function

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

我需要一个函数,因为变量应该从不同页面的自定义字段中获取其值,具体取决于
- 如果{它的父母的身份证号为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;

知道代码有什么问题吗?

1 个答案:

答案 0 :(得分:0)

我可以提出2个解决方案

如果您只在此范围内需要它,并且有一次像评论建议一样,那么代码将是:

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

那样的somenthing
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;

希望这可以提供帮助。

相关问题