Oleksandr Myronchuk
Oleksandr Myronchuk

Reputation: 382

How to change the date of the post in WordPress

I want to change the date of the post, when I publish the post. I wrote in my plugin

add_action( 'publish_post', 'myPlugin_published' );

function myPlugin_published()
{
    $postdate = '2010-02-23 18:57:33';/*For example*/

    $new_post = array(
       'post_date' => $postdate
    );

    wp_insert_post($new_post);
}

The problem is that the date is not changed.

How to change the date of the post in WordPress ?

Upvotes: 3

Views: 14140

Answers (3)

Oleksandr Myronchuk
Oleksandr Myronchuk

Reputation: 382

Thank you all for the help

function my_function( $post_id )
        {
            $postdate = '2010-02-23 18:57:33';

            $my_args = array(
               'ID' => $post_id,
               'post_date' => $postdate
            );

            if ( ! wp_is_post_revision( $post_id ) ){

                    // unhook this function so it doesn't loop infinitely
                    remove_action('save_post', 'my_function');

                    // update the post, which calls save_post again
                    wp_update_post( $my_args );

                    // re-hook this function
                    add_action('save_post', 'my_function');
            }
        }
        add_action('save_post', 'my_function');

Upvotes: 6

Andy Tschiersch
Andy Tschiersch

Reputation: 3815

At this time the post is already saved. Use wp_update_post() instead:

add_action( 'publish_post', 'myPlugin_published', 10, 2 );

function myPlugin_published( $ID, $post )
{
    $postdate = '2010-02-23 18:57:33';/*For example*/

    $update_post = array(
        'ID' => $ID,
        'post_date' => $postdate
    );

    wp_update_post( $update_post );
}

Upvotes: 2

Hassan ALi
Hassan ALi

Reputation: 1331

On the post editor screen, under the Publish meta box you will see the option to publish the post immediately. Right next to it, there is an edit link. Clicking on the edit link will display the post’s time and date settings.

enter image description here

Using the date and time settings, you can choose any date and time in the past as well as in the future. Choosing a future date and time will allow you to schedule the post to be published on that time. enter image description here

On the other hand, choosing a date and time in the past will update the date and change the post’s position in your site’s archive pages. For example if you change the month of a post from June to January, then it will appear on the January’s monthly archive page even if you just published that post. The post will also appear accordingly on the all posts list page in the admin area.

enter image description here

This is particularly useful when you want to publish an article, but don’t want it to appear on the front page of your site. You can just back date it to a date earlier than the last post on your site’s front-page.

Upvotes: -3

Related Questions