Skip to content

Instantly share code, notes, and snippets.

@geoffreycrofte
Last active June 21, 2022 10:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save geoffreycrofte/1e0e86226460b0d26873d36c42e166ac to your computer and use it in GitHub Desktop.
Save geoffreycrofte/1e0e86226460b0d26873d36c42e166ac to your computer and use it in GitHub Desktop.
Get theme color palette from the active WordPress Theme (WP REST API)
;( function( $, window, document, undefined ) {
// Prepare the async function
async function fetchColorsJSON() {
const response = await fetch(crofte.rest_theme_url, {
"headers": {
"Accept": "application/json, */*;q=0.1", // optional
"X-WP-Nonce": crofte.rest_nonce,
"Sec-Fetch-Mode": "cors", // optional
"Sec-Fetch-Site": "same-origin" // optional
},
"method": "GET", // optional
"mode": "cors" // optional
});
const ActiveTheme = await response.json();
// Control what you need to control here, ActiveTheme might not be an array.
return ActiveTheme[0].theme_supports['editor-color-palette'];
}
// Use the async function
fetchColorsJSON().then(colors => {
if ( Array.isArray( colors ) ) {
// We should have a table of Object reprenseting the colors.
console.log( colors );
} else {
// If you don't, prepare a fallback.
}
});
} )( jQuery, window, document );
<?php
/**
* Enqueue script files to use WP REST API
*
* @since 1.0
* @author Geoffrey Crofte
*/
function crofte_enqueues() {
global $pagenow;
if ( $pagenow === 'A PAGE WHERE YOU USE THIS SCRIPT' ) {
wp_enqueue_script( 'crofte-main', plugin_dir_url( __FILE__ ) . 'assets/js/crofte-admin.js', array( 'jquery' ), '1.0.0', true );
$crofte_datas = array(
'rest_nonce' => wp_create_nonce( 'wp_rest' ),
'rest_theme_url' => esc_url_raw( rest_url() ) . 'wp/v2/themes?status=active',
);
wp_localize_script( 'crofte-main', 'crofte', $crofte_datas );
}
}
add_action( 'admin_enqueue_scripts', 'crofte_enqueues' );
@geoffreycrofte
Copy link
Author

Answering my own question on Twitter.
If you have a solution full PHP, I take it with joy.

https://twitter.com/geoffreycrofte/status/1538246202721984512

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment