Wordpress - Include WP_Query in my own PHP file?
Load WordPress in custom PHP Script:
You need to load essential WordPress core functionality in your custom PHP script for WP_Query
to work properly.
For example, let's say you have a custom PHP file named my-cron.php
and WordPress is installed in the web root, like this:
public_html/
index.php
my-cron.php <--
wp-load.php
wp-settings.php
...
wp-admin/
wp-content/
wp-includes/
In this setup, if you want to use WP_Query
in my-cron.php
file, you need to load the wp-load.php
file. So in my-cron.php
file you need to have the following CODE:
if ( ! defined('ABSPATH') ) {
/** Set up WordPress environment */
require_once( dirname( __FILE__ ) . '/wp-load.php' );
}
Access WP_Query:
At this point, you'll have the access to WP_Query
, so you can use it like this:
// simply selecting posts with category name "wordpress"
$the_query = new WP_Query( array( 'category_name' => 'wordpress' ) );
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
}
else {
echo "No post found for category named wordpress";
}
Delete Posts:
However, WP_Query doesn't have delete function. For that you'll either need to use the wp_delete_post()
function or WPDB
class. Using wp_delete_post()
is recommended as it'll take care of many dependencies, however, if you need more control, then you may use WPDB
class or $wpdb
global variable, but be careful if you choose that path.
For example, the following CODE will delete the post with ID 1
:
$deleted = wp_delete_post( 1 );
if( $deleted === false ) {
echo "Couldn't delete Post with ID=1";
}
else {
echo "Deleted Post with ID=1";
}
Of course you can combine WP_Query
with wp_delete_post
to find and delete posts that meet specific criteria.
Setup Cron:
Once you are done writing the custom PHP script, you need to setup cron job to run as a HTTP request, like the following:
5 * * * * wget -q -O - http://your-domain.com/my-cron.php
Security:
Since accessing WP_Query
or wp_delete_post
function doesn't require any authentication (or permission) by default, you need to make sure my-cron.php
is not publicly accessible. For example, you can add the following at the beginning of my-cron.php
file to give access to localhost
only:
$allowed_ip = '127.0.0.1';
if( $allowed_ip !== $_SERVER['REMOTE_ADDR'] ) {
exit( 0 );
}