brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: wp eval-file runs a PHP script inside WordPress

WordPress
~/tips/tip-wordpress-eval-file-script

$ids = get_posts( array( 'post_status' => 'draft', 'fields' => 'ids', 'numberposts' => -1 ) );

Runs a PHP script file with WordPress fully loaded, passing extra arguments in $args.

A one-liner with wp eval is fine until the code needs a loop and a few lines. Then I would rather put it in a file and let wp eval-file run it with WordPress loaded.

Save a script such as count-drafts.php:

<?php
$ids = get_posts( array( 'post_status' => 'draft', 'fields' => 'ids', 'numberposts' => -1 ) );
WP_CLI::log( count( $ids ) . ' drafts' );

Run it from the WordPress folder:

wp eval-file count-drafts.php

Any extra words after the file name end up in the $args variable inside the script, so one script can serve several jobs. Use - as the file name to read the code from standard input. --skip-wordpress runs the file without loading WordPress, and --use-include includes the file instead of evaluating its contents.

Caveats: the script runs inside a method, so global variables must be declared with global before you use them. And it has full access to the site, which means a wp_delete_post() in a loop really deletes. Make a database export first, and print what you would change before you change it.

Further reading: wp eval-file (WP-CLI handbook)

More WordPress tips wp user application-password create anna backup-script --porcelain define( 'MEDIA_TRASH', true ); wp cli check-update wp theme delete --all wp media image-size All WordPress tips (85) All topics

Link