dmxn2k dmxn2k - 3 years ago 180
PHP Question

When Programmatically Creating a Post in WordPress, must the Executable php File with wp_insert_post be Located in the wp-includes Folder?

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 :/';
?>


The browser returned

"This page isn’t working

website.com is currently unable to handle this request.
HTTP ERROR 500"

I have tried several variations of the above code with different errors. I suspect these errors occur because the code is run from another folder, because codex , because even though Wordpress Documentation does not explicitly say it, the post.php example is located in wp-includes.
(https://developer.wordpress.org/reference/functions/wp_insert_post/)

tl,dr;
Can wp_insert_post be run from outside of the wp-includes folder?

Thank you for saving time by providing this answer.

Answer Source

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');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download