get_post_permalink() WordPress Function

The get_post_permalink() function retrieves the permalink for a post.

get_post_permalink( int|WP_Post $id, bool $leavename = false, bool $sample = false ) #

Retrieves the permalink for a post of a custom post type.


Parameters

$id

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

$leavename

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

Default value: false

$sample

(bool)(Optional) Is it a sample permalink.

Default value: false


Top ↑

Return

(string|WP_Error) The post permalink.


Top ↑

More Information

Basic Usage

<?php get_post_permalink( $id, $leavename, $sample ); ?>

See also get_permalink().


Top ↑

Source

File: wp-includes/link-template.php

function get_post_permalink( $id = 0, $leavename = false, $sample = false ) {
	global $wp_rewrite;

	$post = get_post( $id );

	if ( is_wp_error( $post ) ) {
		return $post;
	}

	$post_link = $wp_rewrite->get_extra_permastruct( $post->post_type );

	$slug = $post->post_name;

	$force_plain_link = wp_force_plain_post_permalink( $post );

	$post_type = get_post_type_object( $post->post_type );

	if ( $post_type->hierarchical ) {
		$slug = get_page_uri( $post );
	}

	if ( ! empty( $post_link ) && ( ! $force_plain_link || $sample ) ) {
		if ( ! $leavename ) {
			$post_link = str_replace( "%$post->post_type%", $slug, $post_link );
		}
		$post_link = home_url( user_trailingslashit( $post_link ) );
	} else {
		if ( $post_type->query_var && ( isset( $post->post_status ) && ! $force_plain_link ) ) {
			$post_link = add_query_arg( $post_type->query_var, $slug, '' );
		} else {
			$post_link = add_query_arg(
				array(
					'post_type' => $post->post_type,
					'p'         => $post->ID,
				),
				''
			);
		}
		$post_link = home_url( $post_link );
	}

	/**
	 * Filters the permalink for a post of a custom post type.
	 *
	 * @since 3.0.0
	 *
	 * @param string  $post_link The post's permalink.
	 * @param WP_Post $post      The post in question.
	 * @param bool    $leavename Whether to keep the post name.
	 * @param bool    $sample    Is it a sample permalink.
	 */
	return apply_filters( 'post_type_link', $post_link, $post, $leavename, $sample );
}


Top ↑

Changelog

Changelog
VersionDescription
3.0.0Introduced.

The content displayed on this page has been created in part by processing WordPress source code files which are made available under the GPLv2 (or a later version) license by theĀ Free Software Foundation. In addition to this, the content includes user-written examples and information. All material is subject to review and curation by the WPPaste.com community.

Show More
Show More