on here: on here: on here:

How to use update_post_meta when inserting an new post

93 views Asked by At

How do I use update_post_meta() to put the value from this:

<input type="text" name="gname" id="gname">

on here:

<input type="text" name="budget" value="" style="width:100%;" fdprocessedid="ectck">

I'm a beginner in PHP and my task is to put the input value from gname to a custom field, using update_post_meta(), which has name="budget".

Here is my working code, but it cannot put the value on budget:

<?php
////////// INSERT WP POST
if (isset($_POST['fname']) && isset($_POST['gname']) && isset($_POST['hname'])) {

    $my_post = array(
        'post_type' =>  'job',
        'post_title' => $_POST['fname'],
        'post_content' => $_POST['hname'],
        'post_status' => 'publish',
    );

    // Get the value of the source input field
    $gname_value = $_POST['gname'];
    
    // Get the post ID
    $post_id = get_the_ID();
    
    // Update the target input field with the value
    update_post_meta($post_id, 'budget', $gname_value);

    wp_insert_post($my_post);
}
?>

I'm using WordPress.

1

There are 1 answers

1
LoicTheAztec On

When using wp_insert_post() you can use 'meta_input' argument to add metadata on the fly, instead of using afterward update_post_meta().

Note that the function wp_insert_post() will return the post ID.

So your code will be:

<?php
///// INSERT WP POST /////
if ( isset($_POST['fname']) && isset($_POST['gname']) && isset($_POST['hname']) ) {
 
    $post_id = wp_insert_post( array(
        'post_type'    =>  'job',
        'post_title'   => sanitize_text_field($_POST['fname']),
        'post_content' => sanitize_text_field($_POST['hname']),
        'post_status'  => 'publish',
        'meta_input'   => array(
            'budget'   => sanitize_text_field($_POST['gname']),
        ),
    ) );
}
// Get budget value
$budget = get_post_meta($post_id, 'budget', true);

// Populate budget value in your input field
?>
<input type="text" name="budget" value="<?php echo $budget; ?>" style="width:100%;" fdprocessedid="ectck">
<?php

Or using update_post_meta() it will be like:

<?php
///// INSERT WP POST /////
if ( isset($_POST['fname']) && isset($_POST['gname']) && isset($_POST['hname']) ) {
 
    $post_id = wp_insert_post( array(
        'post_type'    =>  'job',
        'post_title'   => sanitize_text_field($_POST['fname']),
        'post_content' => sanitize_text_field($_POST['hname']),
        'post_status'  => 'publish',
    ) );

    if ( ! is_wp_error( $post_id ) ) {
        update_post_meta($post_id, 'budget', sanitize_text_field($_POST['gname']));
    }
}
// Get budget value
$budget = get_post_meta($post_id, 'budget', true);

// Populate budget value in your input field
?>
<input type="text" name="budget" value="<?php echo $budget; ?>" style="width:100%;" fdprocessedid="ectck">
<?php