Skip to content

Instantly share code, notes, and snippets.

@jesgs
Last active August 24, 2023 09:22
Show Gist options
  • Save jesgs/e619bfbfe10ad998d8a61ac41cc958a7 to your computer and use it in GitHub Desktop.
Save jesgs/e619bfbfe10ad998d8a61ac41cc958a7 to your computer and use it in GitHub Desktop.
Fixes issue with menu_order not saving properly with Gutenberg
<?php
/**
* Add page attributes to post
*/
function mytheme_add_post_attributes()
{
add_post_type_support('post', 'page-attributes');
}
add_action('init', 'mytheme_add_post_attributes', 500);
/**
* Add the menu_order property to the post object being saved
*
* @param \WP_Post|\stdClass $post
* @param WP_REST_Request $request
*
* @return \WP_Post
*/
function mytheme_pre_insert_post($post, \WP_REST_Request $request)
{
$body = $request->get_body();
if ($body) {
$body = json_decode($body);
if (isset($body->menu_order)) {
$post->menu_order = $body->menu_order;
}
}
return $post;
}
add_filter('rest_pre_insert_post', 'mytheme_pre_insert_post', 12, 2);
/**
* Load the menu_order property for frontend display in the admin
*
* @param \WP_REST_Response $response
* @param \WP_Post $post
* @param \WP_REST_Request $request
*
* @return \WP_REST_Response
*/
function mytheme_prepare_post(\WP_REST_Response $response, $post, $request)
{
$response->data['menu_order'] = $post->menu_order;
return $response;
}
add_filter('rest_prepare_post', 'mytheme_prepare_post', 12, 3);
@eriky
Copy link

eriky commented Mar 2, 2021

Thanks as well!

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