Advertisement
mbis

REST API

Nov 16th, 2021 (edited)
856
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.45 KB | None | 0 0
  1. function pm_custom_uri_rest() {
  2.     register_rest_field(
  3.         'product',
  4.         'custom_uri',
  5.         array(
  6.             'get_callback' => 'rest_get_custom_uri',
  7.             'update_callback' => 'rest_update_custom_uri',
  8.             'schema' => array(
  9.                 'description' => 'The value of "Current URI" field.',
  10.                 'type' => 'string',
  11.                 'context' => array('view', 'edit')
  12.             )
  13.         )
  14.     );
  15. }
  16. add_action('rest_api_init', 'pm_custom_uri_rest');
  17.  
  18. function rest_get_custom_uri($post, $field_name, $request) {
  19.     return (!empty($post['id'])) ? Permalink_Manager_URI_Functions_Post::get_post_uri($post['id']) : '';
  20. }
  21.  
  22. function rest_update_custom_uri($value, $post, $field_name) {
  23.     // Perform Validation of input
  24.     if (!$value || !is_string($value)) {
  25.         return;
  26.     }
  27.  
  28.     // Get product ID
  29.     if(!empty($post->ID)) {
  30.         $post_id = $post->ID;
  31.     } elseif(method_exists($post, 'get_id')) {
  32.         $post_id = $post->get_id();
  33.     }
  34.  
  35.     if(!empty($post_id)) {
  36.         Permalink_Manager_URI_Functions::save_single_uri($post_id, $value, false, true);
  37.     }
  38. }
  39.  
  40. function pm_rest_custom_uri_after_rest_insert($post, $request, $is_new_post) {
  41.     if($is_new_post && class_exists('Permalink_Manager_URI_Functions_Post')) {
  42.         // 1. Generate the URI
  43.         $new_uri = Permalink_Manager_URI_Functions_Post::get_default_post_uri($post);
  44.  
  45.         // 2. Save the URI in DB
  46.         Permalink_Manager_URI_Functions::save_single_uri($post->ID, $new_uri, false, true);
  47.     }
  48. }
  49. add_action('rest_after_insert_product', 'pm_rest_custom_uri_after_rest_insert', 9, 3);
  50.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement