WordPress自定义别名永久链接

时间:2018-07-02 22:36:40

标签: wordpress url alias permalinks slug

是否可以为Wordpress中的特定内容类型创建备用永久链接?

例如,我想要一个别名网址:

  

https://example.com/123

指向现有的永久链接,例如:

  

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

我不介意编写代码。

1 个答案:

答案 0 :(得分:1)

玩了一会儿之后,我想出了一种方法。首先,我在初始化挂钩上设置了一个动作。然后,我使用以下代码来确认URL中的ID有效,并执行重定向到永久链接。

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;
    }
  }
}