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

时间:2015-08-12 09:15:15

标签: php html wordpress forms content-management-system

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

我使用高级自定义字段创建的自定义表单字段分别命名为promotion_namevenuemain_event_price。现在,为了将前端用户输入的数据填充到仪表板上的自定义帖子类型字段,我尝试使用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),但自定义表单字段仍为空(请参阅下图:)

enter image description here

enter image description here

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

PS:这是我在functions.php中定义自定义帖子类型的方式:

<?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');
?>

1 个答案:

答案 0 :(得分:11)

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

update_field($field_key, $value, $post_id)

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

How to get the field key

修改 $field_key也接受字段名称。

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

在您的情况下,您应该采取措施来检索此$post_id。幸运的是,wp_insert_post()返回的是什么。所以,你可以这样做:

$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);

所以基本上你要做的就是首先创建帖子,然后用值更新它。

我已经在functions.php文件中完成了这类工作,并且工作正常。根据我所看到的情况,我认为您在某种模板文件中使用此例程。我认为它会正常工作,你只需要确保ACF插件被激活。

修改

我忘记了promotion_name字段。我评论了$post_information内的一行,因为它无法正常工作。您应该使用update_field(),而不是其他3。

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