How to insert post from external php file?

I have this php file on the root directory, and i seen this example for inserting post from external php file but for some reason it doesn't work for me, wp_insert_post() always returns 0

So whats the problem ? and how i can fix it?

I'm trying to build a Cron Job file to insert new posts from XML file In the end

Thank you!

CronJob.php:

?php 

require_once  './wp-load.php';

$new_post = array(
    'post_title' = 'My New Post',
    'post_content' = 'Lorem ipsum dolor sit amet...',
    'post_status' = 'publish',
    'post_date' = date('Y-m-d H:i:s'),
    'post_author' = '3',
    'post_type' = 'post'
);
$post_id = wp_insert_post($new_post);

var_dump($post_id); die; // Return  int(0)

Topic wp-insert-post wp-cron Wordpress

Category Web


You should make sure if wp-load.php is loading correctly when you want to set up the WordPress Environment in a PHP file that exists outside of your WordPress installation.

There is no Function which can get it outside of WordPress Environment. You would have to set it manually, depending upon your directory structure.

you should first define your WordPress path something like this

define( 'WPPATH', dirname(dirname(__FILE__)) . '/wordpress/wp-load.php' );

require_once (WPPATH);

Here you would have to echo out dirname(dirname(__FILE__)) and match your WordPress root directory URL accordingly, as it changes server to server.


The best way to do this is, write the above code in your themes function.php. In this way you will have access to all the WP inbuilt functions, hooks, actions etc.

Then use Cronjob Scheduler plugin - https://wordpress.org/plugins/cronjob-scheduler/ to run your function periodically.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.