WordPress in command line scripts

Though WordPress has wp-cron functionality to do scheduled tasks, I still like Unix crontab to do them. Fortunately, we can write script programs in PHP to run from a command line even if the scripts call WordPress functions. To do WordPress operation in a script, we have to include ‘wp-load.php’ before the operation. Below is a sample script to create a new post. You can run it from a command line. Before loading ‘wp-load.php’, you have to set PHP ‘$_SERVER’ variable. Especially in a multisite environment, WordPress will determine which site to involve by $_SERVER values. #!/usr/bin/php <?php // define(‘WP_DEBUG’, true); /* uncomment for debug */ $_SERVER = array( "HTTP_HOST" … Continue reading WordPress in command line scripts

Calling wp_insert_post to create a post with assigned ID in WordPress

Regarding ‘wp_insert_post’ function, you may want to insert posts with assigned IDs for some reason. Yes, you can do it by using $post->import_id. There is also $post->ID parameter to determine ID. I’ll describe difference between $post->import_id and $post->ID of wp_insert_post. If you want to insert a new post with arbitrary ID, use $post->import_id. If you want to update a existing post, use $post->ID. Without existing post with the ID, the function will do nothing. When you use $post->import_id, please make sure that there is no existing post with ID same as import_id. If the post exists, wp_insert_post will make a new post with automatically generated ID which is not what … Continue reading Calling wp_insert_post to create a post with assigned ID in WordPress

Modifying HTTP response header in your WordPress site

Though Google recommends responsive web design most, they also support sites which produce different HTML on the same URL depending on user-agent information. My site is the latter. Google’s recommendation to sites like mine is to use ‘Vary’ HTTP header. But with standard installation, WordPress doesn’t set ‘Vary’ HTTP field in HTTP response header. So I need to insert it in the header by modifying functions.php. To insert HTTP header fields, write a filter function for ‘wp_headers’ in your functions.php. function add_vary_header($headers) { $headers[‘Vary’] = ‘User-Agent’; return $headers; } add_filter(‘wp_headers’, ‘add_vary_header’); You can also remove unwanted header fields by unsetting them. (related information) function remove_x_pingback($headers) { unset($headers[‘X-Pingback’]); return $headers; } … Continue reading Modifying HTTP response header in your WordPress site