سؤال

What is the proper way to define the post date when submitting a post from the front end using wp_insert_post (Trac)?

My snippet now is publishing with the mysql time...

if (isset ($_POST['date'])) {
    $postdate = $_POST['Y-m-d'];
}
else {
    $postdate = $_POST['2011-12-21'];
}

// ADD THE FORM INPUT TO $new_post ARRAY
$new_post = array(
'post_title'    =>   $title,
'post_content'  =>   $description,
'post_date'     =>   $postdate,
'post_status'   =>   'publish',
'post_parent' => $parent_id,
'post_author' => get_current_user_id(),
);

//SAVE THE POST
$pid = wp_insert_post($new_post);
هل كانت مفيدة؟

المحلول

If you don't add a post_date then WordPress fills it automatically with the current date and time.

To set another date and time [ Y-m-d H:i:s ] is the right structure. An example below with your code.

$postdate = '2010-02-23 18:57:33';

$new_post = array(
   'post_title'    =>   $title,
   'post_content'  =>   $description,
   'post_date'     =>   $postdate,
   'post_status'   =>   'publish',
   'post_parent'   =>   $parent_id,
   'post_author'   =>   get_current_user_id(),
);

//SAVE THE POST
$pid = wp_insert_post($new_post);

نصائح أخرى

to convert your date into Wordpress (MySQL DATETIME) format, try this:

$date_string = "Sept 11, 2001"; // or any string like "20110911" or "2011-09-11"
// returns: string(13) "Sept 11, 2001"

$date_stamp = strtotime($date_string);
// returns: int(1000166400)

$postdate = date("Y-m-d H:i:s", $date_stamp);
// returns: string(19) "2001-09-11 00:00:00"

$new_post = array(
    // your other arguments
   'post_date'     =>   $postdate
);

$pid = wp_insert_post($new_post);

or course if you want to really be sexy do this:

'post_date'     => date("Y-m-d H:i:s", strtotime("Sept 11, 2001"))

You can't format the $_POST['date'] like this... You'll have to run the value from $_POST['date'] through something like $postdate = date( $_POST['date'] )... There's also the possibility to call get_option for the blog settings. See Option Reference in Codex.

For the community here is my final working code:

header

$year = $_REQUEST['year'];
$month = $_REQUEST['month'];
$day = $_REQUEST['day'];
$postdate =  $year . "-" . $month . "-" . $day . " 08:00:00";

$new_post = array(
    'post_title'    =>  $title,
    'post_content'  =>  $description,
    'post_status'   =>  'publish',
    'post_author'   =>  get_current_user_id(),
    'post_date'     =>  $postdate
);

came across thru google. i know its old but there is no definite answer. wordpress code uses current_time( 'mysql' ) to save date/time in wp_update_post function! this will generate the desired date format.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى wordpress.stackexchange
scroll top