Wordpress (ACF) 函数没有 return 值

Wordpress (ACF) function does not return a value

我能够通过变量解析数据没问题,但是我的 echo 的 HTML 输出没有被正确包装。

<?
    if( get_field('pre_video_set_label_name') ) {
        echo "<h3>" . the_field('pre_video_set_label_name') . "</h3>";
    } else {
        echo "<h3>Post-Event Video</h3>";
    }
?>

如果我对 pre_video_set_label_name 的输入是 "Test",那么 HTML 输出将变为:

Test<h3></h3>

我的预期输出是:

<h3>Test</h3>

但我没有得到这些结果。

似乎没有什么可以包装的,而且我最近经常遇到这个问题。是不是我的思路有问题?

您应该将 get_field()echo 一起使用,因为 the_field() 已经回应了元字段:

echo "<h3>" . get_field('pre_video_set_label_name') . "</h3>";

get_field() returns 元值,而不是回显它。

当您使用 wordpress / (ACF) 函数时,请始终检查它们是否 显示 return 值。

函数,显示值:

function displayX(){
    echo "data";
}

如果你想调用这个函数,你不会需要一个echo来显示数据,直接调用它,例如

displayX();  //output: data

注:函数,不会return数据。但即使它没有明确的 return 语句,也不会 return 数据,it still will return something (NULL).

函数,其中returns的值:

function returnX(){
    return "data";
}

如果你想调用这个函数,你需要一个echo来显示数据,调用它即可,例如

echo returnX();  //output: data

注意:这个函数会return数据,不会自己显示。

不同的行为

当您使用显示或 return 值的函数时,您会注意到一些差异。

  1. 作业

    1.1 函数,显示值:

    $variable = displayX();
    

    注:$variable,会被赋值为NULL,上面的行输出data.

    1.2函数,其中returns的值:

    $variable = returnX();
    

    注意:$variable会被赋值为data而上面那行不会输出任何东西。

  2. 串联

    2.1 函数,显示值:

    echo "string start " . displayX() . " string end";
    

    注意: 您将在这里连接 NULL,因为此函数将 return 这个值。函数 首先显示 data,然后您会看到连接的字符串。

    2.2函数,其中returns的值:

    $variable = returnX();
    

    注意: 您将在这里连接 data,因为此函数将 return 这个值。在您看到连接的字符串之前,函数 不会 首先显示任何内容。

  3. 打印

    3.1 函数,显示值:

    displayX();
    

    注:这段代码输出data.

    3.2函数,其中returns的值:

    returnX();
    

    注意:此代码不会显示任何内容。


因此,在您当前的示例中,您使用 the_field(), which displays the data. But if you want to concatenate it, you will need the data returned, means use get_filed(),这只会 return 数据。

还有一种简单的方法可以检查return函数是什么。只需执行:var_dump(functionCall()); 你就会看到函数 returns.