0

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)
0

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.

  • I prefer do not to use with plugin I just need to use wp_insert_post function of Wordpress. Thanks anyway – Moti Winkler Jan 20 '17 at 13:55
0

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.