Last active
October 9, 2018 15:15
-
-
Save mrpritchett/e9a48b959e5d78d2d8174d97361c1c4b to your computer and use it in GitHub Desktop.
Find all Widgets in All Sidebars Across A Multisite Network
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Commands to handle WordPress Widgets more in depth. | |
* | |
* Based on code from Chris Wiegman. Thanks, buddy. | |
* | |
* @author Matt Pritchett | |
*/ | |
/** | |
* Class Widgets_Command | |
*/ | |
class Widgets_Command extends \WP_CLI_Command { | |
/** | |
* Generates a report of active widgets for each site. | |
* | |
* @throws \WP_CLI\ExitException Exception on invalid exit code. | |
* | |
* @param array $args Array of arguments. | |
* @param array $assoc_args Array of associative arguments. | |
*/ | |
public function list( $args, $assoc_args ) { | |
$exit = ( defined( 'WP_DEBUG' ) && true === WP_DEBUG ) ? false : true; | |
if ( ! is_multisite() ) { | |
\WP_CLI::error( esc_html__( 'Command requires a multisite installation to continue.', 'ufhealth-multisite-wp-cli' ), $exit ); | |
return; | |
} | |
$filename = $args[0]; | |
if ( file_exists( $filename ) ) { | |
WP_CLI::warning( sprintf( 'File alredy exists. The following file will be overwritten %s', $filename ) ); | |
} | |
$active_widgets = array(); | |
$response = \WP_CLI::launch_self( 'site clist', array(), array(), false, true ); | |
$sites = explode( PHP_EOL, $response->stdout ); | |
foreach ( $sites as $site ) { | |
if ( empty( $site ) ) { | |
$site = get_site_url( get_current_blog_id() ); | |
} | |
$sidebar_response = \WP_CLI::launch_self( | |
'sidebar list', | |
array(), | |
array( | |
'url' => $site, | |
'format' => 'json', | |
), | |
false, | |
true | |
); | |
$sidebars = json_decode( $sidebar_response->stdout, true ); | |
foreach ( $sidebars as $sidebar ) { | |
$widget_response = \WP_CLI::launch_self( | |
'widget list ' . $sidebar['id'], | |
array(), | |
array( | |
'url' => $site, | |
'format' => 'json', | |
), | |
false, | |
true | |
); | |
$widgets = json_decode( $widget_response->stdout, true ); | |
foreach ( $widgets as $widget ) { | |
$active_widgets[] = array( | |
'site' => $site, | |
'sidebar' => $sidebar['name'], | |
'widget' => $widget['name'], | |
); | |
} | |
} | |
} | |
$fp = fopen( $filename, 'w+' ); | |
foreach ( $active_widgets as $fields ) { | |
fputcsv( $fp, $fields ); | |
} | |
fclose( $fp ); | |
WP_CLI::success( sprintf( 'File created: %s', $filename ) ); | |
} | |
} | |
\WP_CLI::add_command( 'widgets', '\Widgets_Command' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment