How to put variable in array, wp_insert_post?

How to put the variable $get_value in the array, wp_insert_post?

 if ($get_value) {
                    $get_value = "'post_content' => $postpost->post_content,
                       'post_excerpt' => $postpost->post_excerpt,
                        'post_name' => $postpost->post_name,
                        'post_title' => $postpost->post_title,";
                } else {
                    $get_value = '';
$args = array(
                        'comment_status' => $postpost->comment_status,
                        'ping_status' => $postpost->ping_status,
                        'post_parent' => $postpost->post_parent,
                        'post_passworks' => $postpost->post_password,
                        'post_status' => 'publish',
                        'post_type' => 'post',
                        'to_ping' => $postpost->to_ping,
                        'menu_order' => $postpost->menu_order,
                    $new_post_id = wp_insert_post($args);

Well first make sure that $get_value is an array, not a string. Right now you are setting $get_value as a string that for some reason you are making look like array values.

For instance you have $get_value = "'post_content' => $postpost->post_content" when you should be setting it up like $get_value['post_content'] => $postpost->post_content;

You can also use $get_value = array('post_content' => $postpost->post_content, ...); and do all your values at once in the same array.

Once you have $get_value as an array, then it is just a matter of merging it with $args before you pass it off to wp_insert_post(). You can do this with using $new_post_id = wp_insert_post(array_merge($args, $get_value));

What this will do is take every string key of $get_value and add it to $args before inserting. If the two arrays have the same string keys, the values you have in $get_value will overwrite those of $args. The end result is that you have a merged array of your final values.

Experiment a little with this and you should see it work out fairly easily. I hope this helps! :slight_smile:

1 Like