Wordpress:使用 wp_insert_post() 填充自定义 post 类型字段

Wordpress: Using wp_insert_post() to fill custom post type fields

我创建了自定义 post 类型 wrestling 并使用高级自定义字段创建了相应的自定义字段。现在,我希望用户在前端填写此自定义表单,以便在提交时,数据会在仪表板中的自定义 post 类型中自动更新。为此,我创建了一个自定义页面并为其分配了一个包含所需表单的自定义模板。用户应该填写四个 HTML 表单域,分别命名为 namevenuemain_eventfee

我使用高级自定义字段创建的自定义表单字段分别命名为 promotion_namevenuemain_event_price。现在,为了将用户在前端输入的数据填充到仪表板的自定义 post 类型字段中,我尝试使用 wp_insert_post() 函数,如下所示:

$post_information = array(
        'promotion_name' => $_POST['name'],
        'venue' => $_POST['venue'],
        'main_event_' => $_POST['main_event'],
        'price' => $_POST['fee'],
        'post_type' => 'wrestling',
    );

    wp_insert_post( $post_information );

然而,在用户提交表单后,新条目(no_title)确实出现在我的自定义 post 类型中,但自定义表单字段仍然是空的(见下图:)

我确定这是因为我没有正确使用 wp_insert_post() 来更新自定义 post 类型。我真的很感激这里的一些帮助。谢谢。

PS:这就是我在 functions.php:

中定义自定义 post 类型的方式
<?php 
function wrestling_show_type()
{
    register_post_type('wrestling',
                    array('labels' => array('name' => 'Wrestling Shows', 'singular_name' => 'Wrestling Show'),
                        'public' => true,
                        'has_archive' => true,
                        'rewrite' => array('slug' => 'wrestling')));

    flush_rewrite_rules();
}
add_action('init', 'wrestling_show_type');
?>

如果您使用过 ACF,您应该使用他们的 API 与字段进行交互。有一个名为 update_field() 的方法可以完全满足您的需求。此方法需要 3 个参数:

update_field($field_key, $value, $post_id)

$field_key 是 ACF 为您创建的每个字段提供的 ID。这张图片取自他们自己的文档,向您展示了如何获取它:

编辑: $field_key 也将接受字段名称。

$value$post_id 非常简单,它们代表您要设置字段的值,以及您正在更新的 post。

在你的情况下,你应该做一些事情来检索这个 $post_id。幸运的是,这就是 wp_insert_post() returns。所以,你可以这样做:

$post_information = array(
    //'promotion_name' => $_POST['name'],
    'post_type' => 'wrestling'
);

$postID = wp_insert_post( $post_information ); //here's the catch

有了ID,那就简单了,对每个要更新的字段调用update_field()即可。

update_field('whatever_field_key_for_venue_field', $_POST['venue'], $postID);
update_field('whatever_field_key_for_main_event_field', $_POST['main_event'], $postID);
update_field('whatever_field_key_for_fee_field', $_POST['fee'], $postID);

所以基本上你所做的是先创建 post,然后用值更新它。

我已经在 functions.php 文件中完成了此类工作,而且效果很好。据我所见,我认为您是在某种模板文件中使用此例程。我认为它会正常工作,你只需确保 ACF 插件已激活。

编辑:

我忘记了 promotion_name 字段。我评论了 $post_information 中的行,因为它不会起作用。您应该使用 update_field() 代替,就像其他 3.

update_field('whatever_field_key_for_promotion_name_field', $_POST['name'], $postID);