使用 Post 类型填充 ACF 复选框

Populate ACF Checkboxes with Post Types

我正在尝试使用 WP 站点的各种 post 类型填充复选框 ACF 字段。这是一个插件,因此 post 类型将根据安装位置而有所不同。

默认情况下,插件使用页面和 posts,因为它是 post 类型,但需要让用户选择使用复选框来 select 网站上的其他 CPT。我如何使用网站上所有 CPT 的列表填充复选框字段。这是我当前的 PHP 代码部分,用于在插件

中加载字段
array (
    'key' => 'field_56e6d87b6c7be',
    'label' => 'Add to Custom Post Types',
    'name' => 'fb_pixel_cpt_select',
    'type' => 'checkbox',
    'instructions' => 'Select which Custom Post Types you would like to use.',
    'required' => 0,
    'conditional_logic' => 0,
    'wrapper' => array (
        'width' => '',
        'class' => '',
        'id' => '',
    ),
    'choices' => array (
    ),
    'default_value' => array (
    ),
    'layout' => 'vertical',
    'toggle' => 0,
),

您可以在此处使用 ACF 加载字段功能来自动填充您的字段。在此处查看更多信息:http://www.advancedcustomfields.com/resources/acfload_field/

然后,使用 Wordpress get_post_types 调用 (https://codex.wordpress.org/Function_Reference/get_post_types),您可以检索这些值并像这样填充您的字段。

add_filter('acf/load_field/name=fb_pixel_cpt_select', 'acf_load_post_types');

function acf_load_post_types($field)
{
    foreach ( get_post_types( '', 'names' ) as $post_type ) {
       $field['choices'][$post_type] = $post_type;
    }

    // return the field
    return $field;
}

确保您的字段已经创建,然后再尝试填充它。

这将为您的 ACF 块或具有所有 post 类型的任何内容创建一个 select 字段,但没有导航菜单的那些(例如附件 post 类型)。

add_filter('acf/load_field/name=select_post_type', 'yourprefix_acf_load_post_types');
/*
 *  Load Select Field `select_post_type` populated with the value and labels of the singular 
 *  name of all public post types
 */
function yourprefix_acf_load_post_types( $field ) {

    $choices = get_post_types( array( 'show_in_nav_menus' => true ), 'objects' );

    foreach ( $choices as $post_type ) :
        $field['choices'][$post_type->name] = $post_type->labels->singular_name;
    endforeach;
    return $field;
}