函数文档

get_permalink()

💡 云策文档标注

概述

get_permalink() 函数用于获取当前文章或指定文章 ID 的完整固定链接。它支持多种文章类型,包括页面、附件和自定义文章类型,并可根据站点固定链接设置生成 URL。

关键要点

  • 参数:$post(可选,文章 ID 或 WP_Post 对象,默认为全局 $post);$leavename(可选,布尔值,是否保留文章或页面名称,默认为 false)
  • 返回值:成功时返回固定链接 URL 字符串,文章不存在时返回 false
  • 使用时机:最早可在 setup_theme Action 中使用,更早使用(如 plugins_loaded)会导致致命错误
  • 注意事项:在文章页面(如索引、归档)的循环外使用时,若无 ID 参数,将返回循环中最后一篇文章的链接,而非当前页面链接
  • 内部处理:根据文章类型调用相应函数(如 get_page_link()、get_attachment_link()),并处理固定链接结构中的占位符(如 %year%、%category%)

代码示例

// 获取当前文章固定链接(在循环内使用)
echo get_permalink();

// 获取指定文章 ID 的固定链接
echo get_permalink( 123 );

// 获取文章固定链接并保留文章名称
echo get_permalink( $post, true );

// 通过 slug 获取固定链接(用户贡献示例)
function get_link_by_slug( $slug, $type = 'post' ) {
  $post = get_page_by_path( $slug, OBJECT, $type );
  return get_permalink( $post->ID );
}

注意事项

  • 在输出链接时,建议使用 esc_url() 进行转义以确保安全
  • get_page_by_title() 已弃用,建议使用替代方法
  • 函数涉及多个过滤器钩子,如 post_link、pre_post_link,可用于自定义链接生成

📄 原文内容

Retrieves the full permalink for the current post or post ID.

Parameters

$postint|WP_Postoptional
Post ID or post object. Default is the global $post.
$leavenamebooloptional
Whether to keep post name or page name.

Default:false

Return

string|false The permalink URL. False if the post does not exist.

More Information

In a Plugin or Theme, it can be used as early as the <a href="https://developer.wordpress.org/reference/hooks/setup_theme/">setup_theme</a> Action. Any earlier usage, including <a href="https://developer.wordpress.org/reference/hooks/plugins_loaded/">plugins_loaded</a>, generates a Fatal Error.

Note that when used outside The Loop on a posts page (index, archive, etc.) without the ID parameter, it will return the URL of the last post in The Loop, not the permalink for the current page.

Source

function get_permalink( $post = 0, $leavename = false ) {
	$rewritecode = array(
		'%year%',
		'%monthnum%',
		'%day%',
		'%hour%',
		'%minute%',
		'%second%',
		$leavename ? '' : '%postname%',
		'%post_id%',
		'%category%',
		'%author%',
		$leavename ? '' : '%pagename%',
	);

	if ( is_object( $post ) && isset( $post->filter ) && 'sample' === $post->filter ) {
		$sample = true;
	} else {
		$post   = get_post( $post );
		$sample = false;
	}

	if ( empty( $post->ID ) ) {
		return false;
	}

	if ( 'page' === $post->post_type ) {
		return get_page_link( $post, $leavename, $sample );
	} elseif ( 'attachment' === $post->post_type ) {
		return get_attachment_link( $post, $leavename );
	} elseif ( in_array( $post->post_type, get_post_types( array( '_builtin' => false ) ), true ) ) {
		return get_post_permalink( $post, $leavename, $sample );
	}

	$permalink = get_option( 'permalink_structure' );

	/**
	 * Filters the permalink structure for a post before token replacement occurs.
	 *
	 * Only applies to posts with post_type of 'post'.
	 *
	 * @since 3.0.0
	 *
	 * @param string  $permalink The site's permalink structure.
	 * @param WP_Post $post      The post in question.
	 * @param bool    $leavename Whether to keep the post name.
	 */
	$permalink = apply_filters( 'pre_post_link', $permalink, $post, $leavename );

	if (
		$permalink &&
		! wp_force_plain_post_permalink( $post )
	) {

		$category = '';
		if ( str_contains( $permalink, '%category%' ) ) {
			$cats = get_the_category( $post->ID );
			if ( $cats ) {
				$cats = wp_list_sort(
					$cats,
					array(
						'term_id' => 'ASC',
					)
				);

				/**
				 * Filters the category that gets used in the %category% permalink token.
				 *
				 * @since 3.5.0
				 *
				 * @param WP_Term  $cat  The category to use in the permalink.
				 * @param array    $cats Array of all categories (WP_Term objects) associated with the post.
				 * @param WP_Post  $post The post in question.
				 */
				$category_object = apply_filters( 'post_link_category', $cats[0], $cats, $post );

				$category_object = get_term( $category_object, 'category' );
				$category        = $category_object->slug;
				if ( $category_object->parent ) {
					$category = get_category_parents( $category_object->parent, false, '/', true ) . $category;
				}
			}
			/*
			 * Show default category in permalinks,
			 * without having to assign it explicitly.
			 */
			if ( empty( $category ) ) {
				$default_category = get_term( get_option( 'default_category' ), 'category' );
				if ( $default_category && ! is_wp_error( $default_category ) ) {
					$category = $default_category->slug;
				}
			}
		}

		$author = '';
		if ( str_contains( $permalink, '%author%' ) ) {
			$authordata = get_userdata( $post->post_author );
			$author     = $authordata->user_nicename;
		}

		/*
		 * This is not an API call because the permalink is based on the stored post_date value,
		 * which should be parsed as local time regardless of the default PHP timezone.
		 */
		$date = explode( ' ', str_replace( array( '-', ':' ), ' ', $post->post_date ) );

		$rewritereplace = array(
			$date[0],
			$date[1],
			$date[2],
			$date[3],
			$date[4],
			$date[5],
			$post->post_name,
			$post->ID,
			$category,
			$author,
			$post->post_name,
		);

		$permalink = home_url( str_replace( $rewritecode, $rewritereplace, $permalink ) );
		$permalink = user_trailingslashit( $permalink, 'single' );

	} else { // If they're not using the fancy permalink option.
		$permalink = home_url( '?p=' . $post->ID );
	}

	/**
	 * Filters the permalink for a post.
	 *
	 * Only applies to posts with post_type of 'post'.
	 *
	 * @since 1.5.0
	 *
	 * @param string  $permalink The post's permalink.
	 * @param WP_Post $post      The post in question.
	 * @param bool    $leavename Whether to keep the post name.
	 */
	return apply_filters( 'post_link', $permalink, $post, $leavename );
}

Hooks

apply_filters( ‘post_link’, string $permalink, WP_Post $post, bool $leavename )

Filters the permalink for a post.

apply_filters( ‘post_link_category’, WP_Term $cat, array $cats, WP_Post $post )

Filters the category that gets used in the %category% permalink token.

apply_filters( ‘pre_post_link’, string $permalink, WP_Post $post, bool $leavename )

Filters the permalink structure for a post before token replacement occurs.

Changelog

Version Description
1.0.0 Introduced.

User Contributed Notes

  1. Skip to note 13 content

    Get post or page (or whatever) permalink by slug:

    function get_link_by_slug($slug, $type = 'post'){
      $post = get_page_by_path($slug, OBJECT, $type);
      return get_permalink($post->ID);
    }

    If you are using polylang (like I usually do), you can get the permalink starting from whichever language slug (I generally start from my language, usually the websites’s default):

    function get_link_by_slug($slug, $lang_slug = null, $type = 'post'){
      $post = get_page_by_path($slug, OBJECT, $type);
      $id = ($lang_slug) ? pll_get_post($post->ID, $lang_slug) : $post->ID;
      return get_permalink($id);
    }

  2. Skip to note 15 content

    Pass in a post object instead of an ID
    This shows how you can you can get the permalink with the page title instead of the ID.

    <a href="<?php echo esc_url( get_permalink( get_page_by_title( 'Monthly Events' ) ) ); ?>"></a>

  3. Skip to note 16 content

    Link to Specific Post
    Returns the permalinks of two specific posts (post IDs 1 and 10) as hypertext links within an informational list.

    <ul>
    	<li>
    		<ul>
    			<li><a href="<?php echo esc_url( get_permalink(1) ); ?>"></a></li>
    			<li><a href="<?php echo esc_url( get_permalink(10) ); ?>"></a></li>
    		</ul>
    	</li>
    </ul>

  4. Skip to note 22 content

    Get page permalink by its template slug:

    function wpdocs_wp_get_page_url_by_template_slug( $template_slug ) {
        $url = null;
        $template = 'page-' . $template_slug . '.php';
    
        $pages = get_posts( array(
            'post_type' => 'page',
            'meta_query' => array(
                array(
                    'key' => '_wp_page_template',
                    'value' => $template,
                    'compare' => '=',
                )
            )
        ) );
    
        if ( isset( $pages[0] ) ) {
            $url = get_permalink( $pages[0]->ID );
        }
        return $url;
    }

    You can call the function anywhere in your theme like this:

    //outputs url like "http(s)://(www.)(subdomain.)domain.com/shopping-cart-page-name__depends-on-permalink-settings/"
    echo wpdocs_wp_get_page_url_by_template_slug( 'shopping_cart' );

    Note: the function only retreives the first page that uses the given template. I wrote it to get the url for my shopping cart, and the like, obviously these are used only once. I have modified my templates dropdown so that it won’t show certain templates if they have been used in any other post. If you want to get all the posts that use the given template, modify the function like this:

    function wpdocs_wp_get_page_url_by_template_slug( $template_slug ) {
        $urls = array();
        $template = 'page-' . $template_slug . '.php';
    
        $pages = get_posts( array(
            'post_type' => 'page',
            'meta_query' => array(
                array(
                    'key' => '_wp_page_template',
                    'value' => $template,
                    'compare' => '=',
                )
            )
        ) );
    
        foreach ( $pages as $page ) {
            $urls[] = get_permalink( $page->ID );
        }
    
        return !empty( $urls ) ? $urls : false;
    }

  5. Skip to note 24 content

    For security measure be sure to use:

    esc_url( $url:string, $protocols:array|null, $_context:string );

    Example:

    echo esc_url( get_permalink(), 'textdomain' );

    See https://developer.wordpress.org/plugins/security/securing-output/