ACF克隆字段-设置默认值

时间:2020-06-21 14:37:04

标签: wordpress clone advanced-custom-fields

我已经在“ NJ”字段组中建立了一个名为“ NJ”的ACF克隆字段,该字段克隆了“ Global”字段中所有70多个ACF字段。这些字段组显示在相同的自定义帖子类型上。

我希望这些克隆的字段具有默认/后备值设置,该值等于原始字段中的值。因此,如果克隆的字段保留为空白,则默认为原始字段中的值。反过来,这将消除我的模板代码中大量条件语句的需要。

示例:

  • “全球”字段组>数字字段:“游戏总数”>值:'100'

  • “ NJ”字段组>“数字”字段(由“克隆”字段创建):“总计” 游戏”(如果未输入任何值,请使用 同一篇文章)

我在这里找到了两个答案,可以在保存帖子时复制值,但这并不是我想要的。我可能无法知道,但任何建议都将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:0)

因此,假设您在 NJ acf group字段中有一个克隆子字段,它将克隆您选择的 Global 子字段的全部70+,并且如果您像这样转储了所有字段。 ..

echo '<pre>'; print_r(get_fields()); echo '</pre>'; exit;

哪个返回这样的内容...

Array
(
    [global] => Array
        (
            [total_games] => 24
            ...
        )

    [nj] => Array
        (
            [total_games] => 
            ...
        )

    ... 
)

如果返回的数组结构与我的匹配,则可以将以下代码添加到函数中,以简单地遍历所有 NJ 克隆子字段,检查当前值是否为空,然后检查 > Global 有一个匹配密钥,如果有匹配密钥,则获取 Global 值,并将其分配给相应的 NJ 克隆字段。

循环完成后,在保存/更新帖子(自定义帖子类型)时,将 NJ 字段更新为一个大数组。从而在您的帖子中返回预期结果。

在我的代码中,我正在检查post的帖子类型。将post更改为您的自定义帖子类型,即可使用。

请参见下面的代码中的注释...

// acf action that runs when you save post
add_action( 'acf/save_post', 'nj_empty_clone_value_check', 20 );

/**
 * @param $post_id int
 * @return void
 */
function nj_empty_clone_value_check($post_id) {

    // global post
    global $post;

    // check we are on the correct post type (currently set to post)
    if($post->post_type <> 'post') return;

    // get all the fields values from our current post
    $fields = get_fields($post_id);

    // changes check
    $changes = false;

    // for each of the cloned subfields in NJ group
    foreach ($fields['nj'] as $key => $value) {

        // if current NJ group cloned subfield value is blank
        if(!$value) {

            // check the original Global group subfield value is not blank
            if(!empty($fields['global'][$key])) {

                // update the NJ group subfield value with the Global group subfield value
                $fields['nj'][$key] = $fields['global'][$key];

                // update changes check to true
                $changes = true;

            }

        }

    }

    // if any changes have been made to NJ group
    if($changes) {

        // update NJ group field with updated NJ array data
        update_field('nj', $fields['nj'], $post_id);

    }

}
相关问题