返回介绍

get_permalink()

发布于 2017-09-10 23:46:33 字数 14627 浏览 1072 评论 0 收藏 0

get_permalink( int|WP_Post $post,  bool $leavename = false )

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


description


参数

$post

(int|WP_Post) (Optional) Post ID or post object. Default is the global $post.

$leavename

(bool) (Optional) Whether to keep post name or page name.

Default value: false


返回值

(string|false) The permalink URL or false if post does not exist.


源代码

File: wp-includes/link-template.php

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 ( $post->post_type == 'page' )
		return get_page_link($post, $leavename, $sample);
	elseif ( $post->post_type == 'attachment' )
		return get_attachment_link( $post, $leavename );
	elseif ( in_array($post->post_type, get_post_types( array('_builtin' => false) ) ) )
		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 && !in_array( $post->post_status, array( 'draft', 'pending', 'auto-draft', 'future' ) ) ) {
		$unixtime = strtotime($post->post_date);

		$category = '';
		if ( strpos($permalink, '%category%') !== false ) {
			$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 ( $parent = $category_object->parent )
					$category = get_category_parents($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 ( strpos($permalink, '%author%') !== false ) {
			$authordata = get_userdata($post->post_author);
			$author = $authordata->user_nicename;
		}

		$date = explode(" ",date('Y m d H i s', $unixtime));
		$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 );
}

更新日志

Versiondescription
1.0.0Introduced.

More Information

In a Plugin or Theme, it can be used as early as the setup_theme Action. Any earlier usage, including plugins_loaded, 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.


相关函数

Uses

  • wp-includes/functions.php: wp_list_sort()
  • wp-includes/category-template.php: get_the_category()
  • wp-includes/category-template.php: get_category_parents()
  • wp-includes/pluggable.php: get_userdata()
  • wp-includes/taxonomy.php: get_term()
  • wp-includes/link-template.php: home_url()
  • wp-includes/link-template.php: get_page_link()
  • wp-includes/link-template.php: get_attachment_link()
  • wp-includes/link-template.php: get_post_permalink()
  • wp-includes/link-template.php: pre_post_link
  • wp-includes/link-template.php: post_link_category
  • wp-includes/link-template.php: post_link
  • wp-includes/link-template.php: user_trailingslashit()
  • wp-includes/plugin.php: apply_filters()
  • wp-includes/option.php: get_option()
  • wp-includes/post.php: get_post()
  • wp-includes/post.php: get_post_types()
  • wp-includes/load.php: is_wp_error()
  • Show 13 more uses Hide more uses

Used By

  • wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php: WP_REST_Posts_Controller::prepare_item_for_response()
  • wp-includes/rest-api/endpoints/class-wp-rest-posts-controller.php: WP_REST_Posts_Controller::get_item()
  • wp-includes/class-wp-customize-nav-menus.php: WP_Customize_Nav_Menus::ajax_insert_auto_draft_post()
  • wp-includes/link-template.php: wp_get_canonical_url()
  • wp-includes/embed.php: wp_embed_excerpt_more()
  • wp-includes/embed.php: wp_oembed_add_discovery_links()
  • wp-includes/embed.php: get_post_embed_url()
  • wp-includes/embed.php: get_post_embed_html()
  • wp-includes/link-template.php: get_preview_post_link()
  • wp-includes/customize/class-wp-customize-nav-menu-item-setting.php: WP_Customize_Nav_Menu_Item_Setting::value_as_wp_post_nav_menu_item()
  • wp-includes/class-wp-customize-nav-menus.php: WP_Customize_Nav_Menus::search_available_items_query()
  • wp-includes/class-wp-customize-nav-menus.php: WP_Customize_Nav_Menus::load_available_items_query()
  • wp-admin/includes/class-wp-posts-list-table.php: WP_Posts_List_Table::handle_row_actions()
  • wp-admin/includes/upgrade.php: wp_install_maybe_enable_pretty_permalinks()
  • wp-admin/includes/dashboard.php: wp_dashboard_recent_posts()
  • wp-admin/includes/media.php: get_media_item()
  • wp-admin/includes/post.php: get_sample_permalink_html()
  • wp-admin/includes/post.php: get_sample_permalink()
  • wp-admin/includes/class-wp-media-list-table.php: WP_Media_List_Table::_get_row_actions()
  • wp-admin/includes/class-wp-comments-list-table.php: WP_Comments_List_Table::column_response()
  • wp-includes/category-template.php: wp_list_categories()
  • wp-includes/pluggable.php: wp_notify_postauthor()
  • wp-includes/pluggable.php: wp_notify_moderator()
  • wp-includes/general-template.php: wp_get_archives()
  • wp-includes/deprecated.php: get_boundary_post_rel_link()
  • wp-includes/deprecated.php: get_parent_post_rel_link()
  • wp-includes/deprecated.php: previous_post()
  • wp-includes/deprecated.php: next_post()
  • wp-includes/query.php: wp_old_slug_redirect()
  • wp-includes/link-template.php: get_comments_pagenum_link()
  • wp-includes/link-template.php: paginate_comments_links()
  • wp-includes/link-template.php: get_adjacent_post_link()
  • wp-includes/link-template.php: get_adjacent_post_rel_link()
  • wp-includes/link-template.php: get_post_type_archive_link()
  • wp-includes/link-template.php: get_post_comments_feed_link()
  • wp-includes/link-template.php: get_the_permalink()
  • wp-includes/deprecated.php: post_permalink()
  • wp-includes/link-template.php: get_attachment_link()
  • wp-includes/link-template.php: the_permalink()
  • wp-includes/admin-bar.php: wp_admin_bar_edit_menu()
  • wp-includes/feed.php: the_permalink_rss()
  • wp-includes/class-walker-page.php: Walker_Page::start_el()
  • wp-includes/post-template.php: _wp_link_page()
  • wp-includes/post-template.php: get_the_content()
  • wp-includes/post.php: _transition_post_status()
  • wp-includes/post.php: wp_insert_post()
  • wp-includes/canonical.php: redirect_canonical()
  • wp-includes/canonical.php: redirect_guess_404_permalink()
  • wp-includes/ms-functions.php: get_blog_permalink()
  • wp-includes/nav-menu.php: wp_setup_nav_menu_item()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::mw_getPost()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::mw_getRecentPosts()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::_prepare_page()
  • wp-includes/class-wp-xmlrpc-server.php: wp_xmlrpc_server::_prepare_post()
  • wp-includes/comment-template.php: get_post_reply_link()
  • wp-includes/comment-template.php: comment_form()
  • wp-includes/comment-template.php: get_trackback_url()
  • wp-includes/comment-template.php: comments_popup_link()
  • wp-includes/comment-template.php: get_comment_reply_link()
  • wp-includes/comment-template.php: get_comment_link()
  • wp-includes/comment-template.php: get_comments_link()
  • wp-includes/comment.php: trackback()
  • wp-includes/comment.php: pingback()
  • wp-includes/class-wp-editor.php: _WP_Editors::wp_link_query()
  • Show 59 more used by Hide more used by

User Contributed Notes

  1. Skip to note content You must log in to vote on the helpfulness of this noteVote results for this note: 2You must log in to vote on the helpfulness of this note Contributed by Codex

    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' ) ) ); ?>"><?php esc_html_e( 'Monthly Events', 'textdomain' ); ?></a>
    
  2. 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);
    }
    <?php echo str_replace("http://www.mysite.com/","http://www.yoursite.com/",get_permalink()); ?>

    Return the permalink of the post, then search for http://www.mysite.com/ and change it to http://www.yoursite.com/

    Default Usage
    The permalink for current post (used within The Loop). As the tag does not display the permalink, the example uses the PHP echo command.

    Permalink for this post:

    
    echo get_permalink();
    

    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><?php esc_html_e( 'MyBlog info:', 'textdomain' ); ?>
    		<ul>
    			<li><a href="<?php echo esc_url( get_permalink(1) ); ?>"><?php esc_html_e( 'About MyBlog', 'textdomain' ); ?></a></li>
    			<li><a href="<?php echo esc_url( get_permalink(10) ); ?>"><?php esc_html_e( 'About the owner', 'textdomain' ); ?></a></li>
    		</ul>
    	</li>
    </ul>
    

    Get current post/page url outside loop. $post is a global variable.

    
    <?php echo get_permalink( $post->ID ); ?>
    

    Woocommerce shop page permalink

    <?php echo get_permalink( wc_get_page_id('shop') ); ?>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文