| | 2053 | /** |
| | 2054 | * Return a shortlink for a post, page, attachment, or blog. |
| | 2055 | * |
| | 2056 | * Shortlinks are not supported by default. A plugin is required to get shortlink support. |
| | 2057 | * This function exists to provide a shortlink tag that all themes and plugins can target. A plugin must hook in to |
| | 2058 | * provide the actual shortlinks. |
| | 2059 | * |
| | 2060 | * @param int $id A post or blog id. Default is 0, which means the current post or blog. |
| | 2061 | * @param string $contex Whether the id is a 'blog' id, 'post' id, or 'media' id. If 'post', the post_type of the post is consulted. If 'query', the current query is consulted to determin the id and context. Default is 'post'. |
| | 2062 | * @param bool $allow_slugs Whether to allow post slugs in the shortlink. It is up to the plugin how and whether to honor this. |
| | 2063 | * @return string A shortlink or an empty string if no shortlink exists for the requested resource or if shortlinks are not enabled. |
| | 2064 | * @since 3.0.0. |
| | 2065 | */ |
| | 2066 | function wp_get_shortlink($id = 0, $context = 'post', $allow_slugs = true) { |
| | 2067 | // Allow plugins to short-circuit this function. |
| | 2068 | $shortlink = apply_filters('pre_get_shortlink', false, $id, $context, $allow_slugs); |
| | 2069 | if ( false !== $shortlink ) |
| | 2070 | return $shortlink; |
| | 2071 | |
| | 2072 | global $wp_query; |
| | 2073 | $post_id = 0; |
| | 2074 | if ( 'query' == $context && is_single() ) |
| | 2075 | $post_id = $wp_query->get_queried_object_id(); |
| | 2076 | elseif ( 'post' == $context ) |
| | 2077 | $post_id = $id; |
| | 2078 | |
| | 2079 | $shortlink = ''; |
| | 2080 | |
| | 2081 | // Return p= link for posts. |
| | 2082 | if ( !empty($post_id) ) { |
| | 2083 | $post = get_post($post_id); |
| | 2084 | if ( isset($post->post_type) && 'post' == $post->post_type ) |
| | 2085 | $shortlink = home_url('?p=' . $post->ID); |
| | 2086 | } |
| | 2087 | |
| | 2088 | return apply_filters('get_shortlink', $shortlink, $id, $context, $allow_slugs); |
| | 2089 | } |
| | 2090 | |
| | 2091 | function wp_shortlink_wp_head() { |
| | 2092 | $shortlink = wp_get_shortlink(0, 'query'); |
| | 2093 | |
| | 2094 | if ( empty($shortlink) ) |
| | 2095 | return; |
| | 2096 | |
| | 2097 | echo '<link rel="shortlink" href="' . $shortlink . '" />'; |
| | 2098 | } |
| | 2099 | |
| | 2100 | function wp_shortlink_header() { |
| | 2101 | if ( headers_sent() ) |
| | 2102 | return; |
| | 2103 | |
| | 2104 | $shortlink = wp_get_shortlink(0, 'query'); |
| | 2105 | |
| | 2106 | if ( empty($shortlink) ) |
| | 2107 | return; |
| | 2108 | |
| | 2109 | header('Link: <' . $shortlink . '>; rel=shortlink'); |
| | 2110 | } |
| | 2111 | |