Hello, gentlemen! I’ve coded up a solution for this that seems to work with some initial testing (though I’ve not tested with the most recent versions). It’s pretty awesome to be able to pull info from child sites in this way. Got me excited! I provided this to the MainWP team a short while ago for possible inclusion in the Code Snippet extension, but seeing as you struck the conversation back up, I figured I’d make it available here, as well.
/**
* Filter report tokens to include tokens for code snippets that return information from child sites
* Code snippet tokens should be formatted as [code.snippet:{{snippet-id}}] where {{snippet-id}} is replaced by the actual code snippet ID.
*/
add_filter( 'mainwp_pro_reports_custom_tokens', [ $this, 'insert_code_snippet_tokens' ], 10, 3 );
add_filter( 'mainwp_client_reports_custom_tokens', [ $this, 'insert_code_snippet_tokens' ], 10, 3 );
public function insert_code_snippet_tokens( $report_tokens, $report, $site ) {
// Might this be needed to ensure snippets are queried properly and run on multi user installs?
// Or would this introduce a security issue?
// add_filter( 'mainwp_is_multi_user', '__return_false', 20 );
// Check that Code Snippets extension is active (would not be needed if code lives in Code Snippet extension)
if ( class_exists( 'MainWP_CS_DB' ) ) {
// Get all snippets
$snippets = (new MainWP_CS_DB())->get_codesnippet_by();
// Loop through the snippets
foreach ( $snippets as $key => $snippet ) {
// Only add custom tokens for snippets which Return Information
if ( $snippet->type == 'R' ) {
// Prepare and run code on site for which report is being generated
// Code has been duplicated from MainWP_CS->run_snippet() but does not use $_POST variables for site and code
$code = preg_replace( '|^[\s]*<\?(php)?|', '', $snippet->code );
$code = preg_replace( '|\?>[\s]*$|', '', $code );
$code = trim( $code );
if ( empty( $site['id'] ) ) {
die( json_encode( 'FAIL' ) );
} else if ( empty( $code ) ) {
die( json_encode( 'CODEEMPTY' ) );
}
global $mainWPCSExtensionActivator;
$response = apply_filters( 'mainwp_fetchurlauthed', $mainWPCSExtensionActivator->get_child_file(), $mainWPCSExtensionActivator->get_child_key(), $site['id'], 'code_snippet', [ 'action' => 'run_snippet', 'code' => $code ] );
// Set token content conditional on response
$insert = $response['status'] == 'SUCCESS' ? $response['result'] : '';
// Define the custom token
$report_tokens["[code.snippet:{$snippet->id}]"] = $insert;
}
}
}
return $report_tokens;
}