John Davidson

php - wordpress API: how to update custom meta box

0 comments
Message:


I've created a custom meta box, but i can't update that through api rest. This is my code. The var $_POST in a function save_custom_meta_box is always empty when I send a request.


Create meta box


add_action( 'add_meta_boxes', 'adding_custom_meta_boxes', 10, 2 );
if (!function_exists('adding_custom_meta_boxes')) {
function adding_custom_meta_boxes( $post_type, $post ) {
add_meta_box(
"demo-meta-box",
"Custom Meta Box",
"custom_meta_box_markup",
"post",
"side",
"high",
null
);
}
}

Storing Meta Data


add_action("save_post", "save_custom_meta_box", 10, 3);
function save_custom_meta_box($post_id, $post, $update)
{
if(!current_user_can("edit_post", $post_id)){
return $post_id;
}

if($post->post_type != "post"){
return $post_id;
}

$meta_box_checkbox_value = "";

if(isset($_POST["meta-box-checkbox"]))
{
$meta_box_checkbox_value = $_POST["meta-box-checkbox"];
}

update_post_meta($post_id, "meta-box-checkbox", $meta_box_checkbox_value);
}

SOLUTION:
Use action rest_after_insert_post.


add_action('rest_after_insert_post', 'wp_kama_rest_after_insert_post_type_action', 10, 3);
function wp_kama_rest_after_insert_post_type_action( $post, $request, $creating ) {

if ($creating) {
return;
}

$body = json_decode($request->get_body());
if($body->metaBoxCheckbox)
{
update_post_meta($post->ID, "meta-box-checkbox", $body->metaBoxCheckbox);
}

return;
}


My Answer:
'custom_meta_box', // ID of the meta box
'Custom Meta Box', // Title of the meta box
'display_custom_meta_box', // Callback function to display the meta box
$post_type, // Post type where the meta box should be displayed
'normal', // Context of the meta box (e.g., 'normal', 'side', 'advanced')
'high' // Priority of the meta box (e.g., 'high', 'core', 'default', 'low')
);
}
}

function display_custom_meta_box( $post ) {
$custom_meta_value = get_post_meta( $post->ID, 'custom_meta_key', true );
?>


}

function save_custom_meta_box( $post_id ) {
if ( isset( $_POST['custom_meta_field'] ) ) {
update_post_meta( $post_id, 'custom_meta_key', sanitize_text_field( $_POST['custom_meta_field'] ) );
}
}

add_action( 'save_post', 'save_custom_meta_box' );

In your REST API request, make sure you are sending the custom_meta_field parameter in the request body. For example, if you are using the fetch API in JavaScript:

fetch('https://example.com/wp-json/wp/v2/posts/123', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': wpApiSettings.nonce
},
body: JSON.stringify({
custom_meta_field: 'Updated value'
})
});

This should update the custom meta box value when you send a request to the WordPress REST API.

Rate this post

3 of 5 based on 9563 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us