Skip to content

Instantly share code, notes, and snippets.

@rocketgeek
Last active December 30, 2021 13:45
Show Gist options
  • Save rocketgeek/31e50dab69969a0135342ac36a0f3283 to your computer and use it in GitHub Desktop.
Save rocketgeek/31e50dab69969a0135342ac36a0f3283 to your computer and use it in GitHub Desktop.
Run php scripts from the command line with full access to WordPress functions.
<?php
/**
* A utility script to load WordPress to run
* php scripts directly from the command line.
*/
if ( php_sapi_name() !== 'cli' ) {
die( "This script is meant to be run from the command line" );
}
set_time_limit(0);
ini_set( 'max_execution_time', 0 ); // Sets execution time to no limit
ini_set( "memory_limit", "-1" ); // Sets memory limit to no limit
function find_wordpress_base_path() {
$dir = dirname( __FILE__ );
do {
if( file_exists( $dir . "/wp-config.php" ) ) {
return $dir;
}
} while( $dir = realpath( "$dir/.." ) );
return null;
}
define( 'BASE_PATH', find_wordpress_base_path() . "/" );
define( 'WP_USE_THEMES', false );
require( BASE_PATH . 'wp-load.php' );
// Common WP globals.
global $wp, $wp_query, $wp_the_query, $wp_rewrite, $wp_did_header, $wpdb;
// End preliminary WordPress load.
// Custom script can continue below this line.
/**
* Array search utility function.
*/
function sub_array_search( $array, $field, $value ) {
foreach( $array as $key => $sub_array ) {
if ( $sub_array[ $field ] === $value )
return $key;
}
return false;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment