Work with WordPress from an External File to be Run from the Command Line
Using the WP CLI
In the HTML root, create a PHP file. It should be at the same directory level as the wp-load.php
file.
Run wp eval-file file-name.php
to run the script. If using Ddev, run it as ddev wp eval-file file-name.php
.
Using the PHP command
In the HTML root, create a PHP file. It should be at the same directory level as the wp-load.php
file.
At the top of that file, add:
<?php
define( 'WP_USE_THEMES', false );
require_once( './wp-load.php' );
That is enough to set up the connection to the WordPress database and access the WordPress functions.
From there, a query can be written for example to get all posts of a certain taxonomy that have an ACF field populated:
$posts = new WP_Query( array(
'posts_per_page' => - 1, // retrieve all items without regard for pagination rules
'tax_query' => array(
array(
'taxonomy' => 'my-taxonomy', // taxonomy name
'meta_key' => 'my-acf-field-name', // an ACF field
"operator" => "EXISTS",
)
)
) );
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$posts->the_post();
// do something with the post
}
} else {
echo "No posts found\n";
}
The file can then be executed by running: $ php my-file-name.php
. If working in Ddev, first SSH into the environment: $ ddev ssh
and then run the file.
To make the file a bit safer, add the following to only allow execution from the command line:
if (php_sapi_name() != 'cli') {
echo "This application must be run on the command line.\n";
exit();
}
Feedback?
Email us at enquiries@kinsa.cc.