Ward
Ward

Reputation: 3318

Wordpress Custom Alias Permalinks

Is there a way to create an alternate permalink for a specific content type in Wordpress?

For example, I want an alias url:

https://example.com/123

to point to an existing permalink such as:

https://example.com/something/this-is-a-post

I don't mind writing code if I have to.

Upvotes: 0

Views: 680

Answers (1)

Ward
Ward

Reputation: 3318

After a little playing around, I came up with a method. First I set up an action on the init hook. Then I use the following code to confirm the id from the URL is valid and perform a redirection to the permalink.

function my_init() {
  global $wpdb;

  // Using an alias id to redirect to permalink

  // split URL path into parts and look at the first part (index 0)
  $path_parts = explode("/", substr(wp_parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH), 1));

  // make sure we're dealing with an number
  if (is_numeric($path_parts[0]))
  {
    // query the database using the numeric value to see if it corresponds to a post ID of the mp type and its status is publish
    $results = $wpdb->get_results("SELECT post_type, post_status FROM wp_posts WHERE ID = $path_parts[0]");
    if ($results[0]->post_type == 'mp' && ($results[0]->post_status == 'publish' || is_admin()))
    {
      // redirect to permalink url
      wp_redirect(get_post_permalink($path_parts[0]));
      exit;
    }
  }
}

Upvotes: 1

Related Questions