get_edit_post_link( int|WP_Post $post, string $context = ‘display’ ): string|null

Retrieves the edit post link for post.

Description

Can be used within the WordPress loop or outside of it. Can be used with pages, posts, attachments, revisions, global styles, templates, and template parts.

Parameters

$postint|WP_Postoptional
Post ID or post object. Default is the global $post.
$contextstringoptional
How to output the '&' character. Default '&'.

Default:'display'

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.

Source

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 = '&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 );
}

Hooks

apply_filters( ‘get_edit_post_link’, string $link, int $post_id, string $context )

Filters the post edit link.

Changelog

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

User Contributed Notes

  1. Skip to note 2 content
    // Hide the Edit Post Link from Non Administrators Start.
    
    function wpdocs_remove_get_edit_post_link( $link ) {
        if ( current_user_can( 'administrator' ) ) {
            return $link;
        }
    
        return null;
    }
    
    add_filter( 'get_edit_post_link', 'wpdocs_remove_get_edit_post_link' );
    
    // Hide the Edit Post Link from Non Administrators End.

You must log in before being able to contribute a note or feedback.