Question

I want to publish post from php for automation reasons with dynamic data and cronjob.

I have almost succeeded, you could say that it works, but in an incorrect way.

If the title doesn't exist, create it.

If the title exists, it updates it, but with a small error.

It is published again with the same data, instead of updating it. This makes the new post sharing plugins share the post every time it is updated and I want to avoid this

<?php
// require wp-load.php to use built-in WordPress functions
require_once("/var/www/mysite.com/wp-load.php");

//Title
    $TítleProduct = ("Title Product 1");
//Desc
    $Desc = ("Product descripction 1");

// Register Post Data

$post = array();
$post['post_status']   = 'publish';
$post['post_type']     = 'post'; // can be a CPT too
$post['post_title']    = "$TítleProduct";
$post['post_content']  = ($Desc);
$post['post_author']   = 1;

function wp_exist_post_by_title($title)
{
    global $wpdb;
    $return_id = $wpdb->get_row("SELECT ID FROM wp_posts WHERE post_title = '" . $title . "' && post_status = 'publish' && post_type = 'post' ", 'ARRAY_N');
    if (empty($return_id)) {
        return false;
    } else {
        return $return_id;
    }
}

$id = wp_exist_post_by_title($post['post_title']);

if($id !== false)
{
    $post['ID'] = $id["0"];
}

// Create Post

 $post_id = wp_insert_post( $post );

/*******************************************************
** SIMPLE ERROR CHECKING
*******************************************************/

$finaltext = '';

if($post_id){

$finaltext .= 'Se ha creado/actualizado correctamente el post '.$post['ID'].'.<br>';

} else{

$finaltext .= 'Something went wrong and I didn\'t insert a new post.<br>';

}

echo $finaltext;
?>
Was it helpful?

Solution

Try to use wp_update_post() in place of wp_insert_post for update.

$id = wp_exist_post_by_title($post['post_title']);

if($id !== false)
{
    $post['ID'] = $id["0"];
    // Create Post
    $post_id = wp_update_post( $post );
} else {
    $post_id = wp_insert_post( $post );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top