Support » Developing with WordPress » Expose old slugs using REST API

  • Hi,

    I’m building a React-powered site using the REST API and GatsbyJS.
    I need to be able to redirect URL with old slug to new.
    Is there a way to expose the old slugs using the WP REST API?

Viewing 5 replies - 1 through 5 (of 5 total)
  • Moderator bcworkz

    (@bcworkz)

    Where would the old slugs come from? I suspect you would need a custom endpoint, assuming the old slugs still exist somewhere in the DB.

    @bcworkz WordPress automatically saves the old post slugs in the database.

    • This reply was modified 2 years, 1 month ago by  Cristian.
    Moderator bcworkz

    (@bcworkz)

    Do you mean the auto-save and backup versions? You can get at them with $wpdb methods and custom SQL. I’m not sure what WHERE criteria to use offhand. Use phpMyAdmin to examine the versions. Determine what’s in common with the current version and what’s reliably different. The two ANDed together should return the record you need containing the old slug.

    Some sites limit the backup versions so old slugs soon disappear. As long as this works for you and you’re not writing a general plugin, then it doesn’t matter 🙂

    I’m referring to exposing “_wp_old_slug” in the REST API.
    I tried using register_meta like below but it didn’t work for custom post types:

    add_action( 'rest_api_init', 'expose_old_slugs_in_api' );
    
    function expose_old_slugs_in_api() {
      // Get list of all post types except 'attachment'
      $post_types = get_post_types( array( 'show_in_rest' => true, 'show_in_nav_menus' => true ) ) ;
        
      $args = array(
        'type'          => 'string',
        'single'        => false,
        'show_in_rest'  => true
      );
      
      foreach ($post_types as $type) {    
        register_meta( $type, '_wp_old_slug', $args );
      }
    }
    Moderator bcworkz

    (@bcworkz)

    Sorry for the slow reply. I’m sorry also because I’m not that familiar with the REST API. I’m unsure why there’s a problem with CPTs. I suppose you could create a custom endpoint as a workaround.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Expose old slugs using REST API’ is closed to new replies.