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;
?>
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
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 );
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0