update_option not working in stand-alone PHP script

I have a standalone PHP script in my WordPress theme’s directory that I run once every hour through a cron job (or manually if needed). All other WordPress functions are working except the update_option() function.

A simplified version of my script looks like this:

require_once('/path/to/site/wp-load.php');

$value = my_function();
update_option('my_option', $value);

and in one of my theme’s files, I am running the following code:

echo get_option('my_option');

Nothing is printed, and a var_dump shows that the returned value is false.

My wp-admin/options.php page doesn’t list my_option either.

I’m at a loss, because below those lines, I am using the following WordPress functions to interact with my WordPress database successfully:

  • get_posts
  • delete_post_meta
  • add_post_meta

Debugging my script, my_function returns a string (about 10 characters) and no errors are thrown with my PHP error settings at E_ALL.

Do I need to include other WordPress core files? I thought that wp-load.php was all you needed.


WordPress version: 3.7

4 Answers
4

I’m not sure why it does’t work for you, but the following works in the file wp-content/test.php:

<?php
// doesn't make difference to have this or not, for the rest to work
define( 'WP_USE_THEMES', false ); 

require( $_SERVER['DOCUMENT_ROOT'] .'/wp-load.php' );

function my_function()
{
    return 'hello world';
}

$value = my_function();
update_option( 'my_option', $value );
var_dump( get_option( 'my_option' ) );

Leave a Comment