I ask this question with the following context:
I want to programmatically create a post in Wordpress using wp_insert_post().
I originally saved the executable php file in the wp-includes folder, but I could not run the php file from my browser, which I wanted to do for convenience.
I saved the executable php file at /public_html/folder/executable_file.php and ran this code from the Chrome browser:
<?php
$postContent = 'test post';
$title = 'test title';
// Create post object
$my_post = array(
'post_title' => $title,
'post_content' => $postContent,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => 'uncategorized'
);
// Insert the post into the database
wp_insert_post( $my_post );
echo 'At least the file executed :/';
?>
If I understand you correctly, you are trying to run this script outside of the scope of Wordpress. You can't. wp_insert_post
is a core function of Wordpress and relies on many core aspects of Wordpress (like $wpdb
), therefore you must be in the scope of Wordpress to run a script using WP functions. This is why you are getting a fatal error.
Furthermore, you don't need to (and you SHOULDN'T) put a file in the /wp-includes/
directory. The proper way to do this would be to set up a custom theme and put your code in the functions.php file, and then hook into one of the many action hooks Wordpress provides. Something like this:
// in your functions.php file, located at /wp-content/themes/your-theme/
function so46492768_insert_post() {
$postContent = 'test post';
$title = 'test title'
// Create post object
$my_post = array(
'post_title' => $title,
'post_content' => $postContent,
'post_status' => 'publish',
'post_author' => 1,
'post_category' => 'uncategorized'
);
// Insert the post into the database
wp_insert_post( $my_post );
echo 'At least the file executed :/';
}
add_action('init','so46492768_insert_post');