ACF pro - 创建前端表单和 Wordpress 类别 post

ACF pro - frontend form and Wordpress categories while creating post

我尝试构建用户可以填写表格的页面(使用我的自定义 ACF PRO 字段)并将其另存为 post。然后管理员需要检查它并在一切正常时发布。到目前为止,我有基于自定义 post 类型的表单,ACF 字段目前运行良好。但我需要在前端 post 创建者上显示带有原生 WP 类别的复选框。目前,用户无法从前端列表中选择 select 类别。保存草稿后后台即可完成

当用户填写 ACF 前端表单时,如何在前端显示带有我的 WP post 类别的复选框列表?

这是我的 ACF 表格数组:

acf_form(array(
    'post_id'       => 'new_post',
    'post_title'    => true,
    'submit_value'  => 'Add new',
    'new_post'      => array(
        'post_type'     => 'games',
        'post_status'   => 'draft'),
));

以下是您可以遵循的步骤,以便前端用户可以 select 他们想要的类别。保持 acf_form 函数不变,并将以下代码集成到 functions.php 文件中。

第 1 步:在前端呈现类别复选框供用户 select 他们

function my_acf_render_field( $field ) {
    // Do not show the code in backend acf metabox
    if( is_admin() ) {
        return;
    }
    
    $categories = $terms = get_terms( array(
        'taxonomy' => 'YOUR_TAXONOMY_NAME',
        'hide_empty' => false,
    ) );
    if( !empty( $categories ) && count( $categories ) ) {
        foreach( $categories as $key => $value ) {
            echo '<input type="checkbox" name="category[]" id="cat_'.$value->term_id.'" value="'.$value->term_id.'" />';
            echo '<label for="cat_'.$value->term_id.'">'.$value->name.'</label>';
        }
    }
}
// Replace "your_field_name" with the field name after which you want to show the category checkboxes
add_action('acf/render_field/name=your_field_name', 'my_acf_render_field');

第 2 步:在后端新建 post

保存前端用户编辑的类别 select
function my_save_post( $post_id ) {
    // bail early if not a games post
    if( get_post_type($post_id) !== 'games' ) {
        return; 
    }

    // bail early if editing in admin
    if( is_admin() ) {
        return;
    }
    
    // update the post created by ACF
    wp_update_post(array(
        'ID'            => $post_id,
        'tax_input'     => array(
                    'YOUR_TAXONOMY_NAME' => $_POST['category']
        )
    ));
}
add_action('acf/save_post', 'my_save_post');

就是这样。现在,用户也可以 select 来自前端的类别。