get_edit_post_link()WP 2.3.0

Gets the link (URL) to edit post in the admin panel.

Can be used within the WordPress loop or outside of it. Can be used with any post types: page, post, attachment, custom_post_type and revision.

1 time — 0.000344 sec (fast) | 50000 times — 0.95 sec (very fast) | PHP 7.0.8, WP 4.6.1
Hooks from the function

Return

String|null. The edit post link for the given post. Null if the post type does not exist or does not allow an editing UI.

Usage

$edit_link = get_edit_post_link( $id, $context );
$id(int/WP_Post)
Post ID or post object, the edit link of which we need to get.
Default: is the global $post
$context(string)

Context in which the link will be used.

  • display means that ampersand (&) will be converted to &.
  • '' means to not change the ampersand.

Default: 'display'

Examples

0

#1 Print the link only if the user has sufficient capability for edit the post

if( current_user_can( 'edit_posts' ) ) {
	echo '<a href="'. get_edit_post_link(1) .'">Edit</a>';
}
-1

#2 Example of how this function works

echo get_edit_post_link( 1 );

// display: http://example.com/wp-admin/post.php?post=1&amp;action=edit
-1

#3 Display ready link

echo '<a href="' . get_edit_post_link(1) . '">Edit</a>';

Changelog

Since 2.3.0 Introduced.
Since 6.3.0 Adds custom link for wp_navigation post types. Adds custom links for wp_template_part and wp_template post types.

get_edit_post_link() code WP 6.4.3

function get_edit_post_link( $post = 0, $context = 'display' ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return;
	}

	if ( 'revision' === $post->post_type ) {
		$action = '';
	} elseif ( 'display' === $context ) {
		$action = '&amp;action=edit';
	} else {
		$action = '&action=edit';
	}

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

	if ( ! $post_type_object ) {
		return;
	}

	if ( ! current_user_can( 'edit_post', $post->ID ) ) {
		return;
	}

	$link = '';

	if ( 'wp_template' === $post->post_type || 'wp_template_part' === $post->post_type ) {
		$slug = urlencode( get_stylesheet() . '//' . $post->post_name );
		$link = admin_url( sprintf( $post_type_object->_edit_link, $post->post_type, $slug ) );
	} elseif ( 'wp_navigation' === $post->post_type ) {
		$link = admin_url( sprintf( $post_type_object->_edit_link, (string) $post->ID ) );
	} elseif ( $post_type_object->_edit_link ) {
		$link = admin_url( sprintf( $post_type_object->_edit_link . $action, $post->ID ) );
	}

	/**
	 * Filters the post edit link.
	 *
	 * @since 2.3.0
	 *
	 * @param string $link    The edit link.
	 * @param int    $post_id Post ID.
	 * @param string $context The link context. If set to 'display' then ampersands
	 *                        are encoded.
	 */
	return apply_filters( 'get_edit_post_link', $link, $post->ID, $context );
}