如何将变量放入数组wp_sert_post?

时间:2021-02-13 作者:Mano World

如何将变量$get\\u值放入数组wp\\u insert\\u 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,
                        $get_value,
                        \'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);

1 个回复
SO网友:Ankur

您必须在简单数组中转换$get\\u value变量,然后在关联数组中转换,然后将两个数组合并为一个数组,然后可以通过wp\\u insert\\u post()函数创建或更新帖子。您可以通过以下代码实现这一点。

if ($get_value) {
    // change the string structure for converting into the array.
    $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,
);

// converting the string to array.
$string_to_array = explode(\',\', $get_value);

// converting the simple array to associative array.
function simple_array_to_associative_array($simple_array) {
    $new_array = [];
    $i = 0;
    $last_element = end($simple_array);
    foreach ($simple_array as $index => $value) {
        if($i % 2 == 0 && $last_element == $value) {
            $new_array[$value] = \'\';
        } elseif($i % 2 == 0) {
            $new_array[$value] = $simple_array[$index + 1];
        }
        $i++;
    }
    return $new_array;
}

$converted_array = simple_array_to_associative_array($string_to_array);

// merge the both array.
$final_args = $args + $converted_array;

$new_post_id = wp_insert_post($final_args);