|
<?php |
|
/** |
|
* Plugin Name: Trac 64017: REST API Colors Meta Field |
|
* Plugin URI: https://core.trac.wordpress.org/ticket/64017 |
|
* Description: Registers a post meta field for an array of colors, exposes it to the REST API, and adds a frontend script for editors. |
|
* Version: 1.0.0 |
|
* Author: Weston Ruter |
|
* Author URI: https://weston.ruter.net/ |
|
* License: GPL-2.0+ |
|
* License URI: http://www.gnu.org/licenses/gpl-2.0.txt |
|
* Text Domain: rest-colors-meta |
|
*/ |
|
|
|
// Exit if accessed directly. |
|
if ( ! defined( 'ABSPATH' ) ) { |
|
exit; |
|
} |
|
|
|
/** |
|
* Registers the post meta field for the array of colors. |
|
* |
|
* This function is hooked into 'init' to ensure it runs after WordPress is loaded. |
|
*/ |
|
function rcm_register_colors_meta_field() { |
|
|
|
// Register the meta field for the 'post' post type. |
|
register_post_meta( |
|
'post', |
|
'color_names_array', // The meta key. |
|
[ |
|
'type' => 'array', |
|
'single' => true, // Store as a single serialized array in the database. |
|
'show_in_rest' => [ |
|
// Define the schema for the REST API. |
|
'schema' => [ |
|
'description' => __( 'An array of color names.', 'rest-colors-meta' ), |
|
'type' => 'array', |
|
'items' => [ |
|
'type' => 'string', |
|
], |
|
], |
|
], |
|
// Ensure only users who can edit the post can update the meta field. |
|
'auth_callback' => function( $allowed, $meta_key, $post_id ) { |
|
return current_user_can( 'edit_post', $post_id ); |
|
}, |
|
] |
|
); |
|
} |
|
add_action( 'init', 'rcm_register_colors_meta_field' ); |
|
|
|
|
|
/** |
|
* Prints an inline script in the footer for logged-in users who can edit the current post. |
|
* |
|
* This script provides functions to fetch and update the 'color_names_array' meta field. |
|
*/ |
|
function rcm_add_colors_meta_script() { |
|
|
|
// Only run on single post pages for logged-in users who can edit this post. |
|
if ( ! is_singular( 'post' ) || ! is_user_logged_in() || ! current_user_can( 'edit_post', get_the_ID() ) ) { |
|
return; |
|
} |
|
|
|
$post_id = get_the_ID(); |
|
$rest_url = get_rest_url( null, 'wp/v2/posts/' . $post_id ); |
|
$rest_nonce = wp_create_nonce( 'wp_rest' ); |
|
|
|
?> |
|
<script> |
|
document.addEventListener('DOMContentLoaded', () => { |
|
const postId = <?php echo wp_json_encode( (int) $post_id ); ?>; |
|
const restUrl = <?php echo wp_json_encode( $rest_url ); ?>; |
|
const restNonce = <?php echo wp_json_encode( $rest_nonce ); ?>; |
|
|
|
/** |
|
* Fetches the post's color array from the REST API and logs it to the console. |
|
*/ |
|
async function fetchPostColors() { |
|
try { |
|
console.log(`Fetching colors for post ${postId}...`); |
|
const response = await fetch(restUrl); |
|
if (!response.ok) { |
|
throw new Error(`HTTP error! Status: ${response.status}`); |
|
} |
|
const post = await response.json(); |
|
const colors = post.meta.color_names_array || []; // Default to empty array if not set. |
|
console.log('Current colors:', colors); |
|
return colors; |
|
} catch (error) { |
|
console.error('Error fetching colors:', error); |
|
} |
|
} |
|
|
|
/** |
|
* Updates the post's color array via the REST API. |
|
* @param {string[]} newColors - An array of color names to save. |
|
*/ |
|
async function updatePostColors(newColors) { |
|
if (!Array.isArray(newColors)) { |
|
console.error('The newColors parameter must be an array.'); |
|
return; |
|
} |
|
|
|
try { |
|
console.log(`Updating colors for post ${postId} to:`, newColors); |
|
const response = await fetch(restUrl, { |
|
method: 'POST', |
|
headers: { |
|
'Content-Type': 'application/json; charset=UTF-8', |
|
'X-WP-Nonce': restNonce |
|
}, |
|
body: JSON.stringify({ |
|
meta: { |
|
color_names_array: newColors |
|
} |
|
}) |
|
}); |
|
|
|
if (!response.ok) { |
|
throw new Error(`HTTP error! Status: ${response.status}`); |
|
} |
|
|
|
const data = await response.json(); |
|
console.log('Update successful! New colors are:', data.meta.color_names_array); |
|
} catch (error) { |
|
console.error('Error updating colors:', error); |
|
} |
|
} |
|
|
|
// --- Example Usage --- |
|
|
|
// Expose functions globally for easy console access. |
|
window.fetchPostColors = fetchPostColors; |
|
window.updatePostColors = updatePostColors; |
|
|
|
// Fetch and log the colors when the page loads. |
|
fetchPostColors(); |
|
|
|
console.log('Color management script loaded. You can now use `fetchPostColors()` and `updatePostColors(["red", "green", "blue"])` in the console.'); |
|
}); |
|
</script> |
|
<?php |
|
} |
|
add_action( 'wp_footer', 'rcm_add_colors_meta_script' ); |
|
|