Last active
June 21, 2022 10:30
-
-
Save geoffreycrofte/1e0e86226460b0d26873d36c42e166ac to your computer and use it in GitHub Desktop.
Get theme color palette from the active WordPress Theme (WP REST API)
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
;( 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 ); |
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 | |
/** | |
* 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' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Answering my own question on Twitter.
If you have a solution full PHP, I take it with joy.
https://twitter.com/geoffreycrofte/status/1538246202721984512