函数文档

edit_post_link()

💡 云策文档标注

概述

edit_post_link() 函数用于显示当前文章的编辑链接,适用于已登录且有编辑权限的用户。该函数可在循环内或循环外使用,支持文章、页面、附件和修订版本。

关键要点

  • 参数包括 $text(锚文本,默认为 'Edit This')、$before(链接前内容)、$after(链接后内容)、$post(文章 ID 或对象)和 $css_class(自定义 CSS 类)。
  • 在循环外使用时需传递 $post 参数以指定文章。
  • 使用 get_edit_post_link() 获取编辑链接 URL,此函数输出链接 HTML。
  • 通过 apply_filters('edit_post_link', ...) 钩子可过滤链接锚标签。

代码示例

// 默认用法,显示默认编辑链接
edit_post_link();

// 在段落标签中显示自定义文本的编辑链接
edit_post_link( __( 'Edit', 'textdomain' ), '', '' );

// 添加自定义 CSS 类到链接
edit_post_link( __( 'Edit', 'textdomain' ), '', '', null, 'btn btn-primary btn-edit-post-link' );

注意事项

  • 确保用户已登录且有编辑权限,否则链接不会显示。
  • 在循环外使用时,必须提供 $post 参数以避免错误。
  • 函数输出链接,若需仅获取 URL,应使用 get_edit_post_link()。

📄 原文内容

Displays the edit post link for post.

Parameters

$textstringoptional
Anchor text. If null, default is ‘Edit This’.

Default:null

$beforestringoptional
Display before edit link. Default empty.
$afterstringoptional
Display after edit link. Default empty.
$postint|WP_Postoptional
Post ID or post object. Default is the global $post.
$css_classstringoptional
Add custom class to link. Default 'post-edit-link'.

More Information

Displays a link to edit the current post, if a user is logged in and allowed to edit the post. Can be used within The Loop or outside of it. If outside the loop, you’ll need to pass the post ID. Can be used with pages, posts, attachments, and revisions.

Use get_edit_post_link to retrieve the url.

Source

function edit_post_link( $text = null, $before = '', $after = '', $post = 0, $css_class = 'post-edit-link' ) {
	$post = get_post( $post );

	if ( ! $post ) {
		return;
	}

	$url = get_edit_post_link( $post->ID );

	if ( ! $url ) {
		return;
	}

	if ( null === $text ) {
		$text = __( 'Edit This' );
	}

	$link = '<a class="' . esc_attr( $css_class ) . '" href="' . esc_url( $url ) . '">' . $text . '</a>';

	/**
	 * Filters the post edit link anchor tag.
	 *
	 * @since 2.3.0
	 *
	 * @param string $link    Anchor tag for the edit link.
	 * @param int    $post_id Post ID.
	 * @param string $text    Anchor text.
	 */
	echo $before . apply_filters( 'edit_post_link', $link, $post->ID, $text ) . $after;
}

Hooks

apply_filters( ‘edit_post_link’, string $link, int $post_id, string $text )

Filters the post edit link anchor tag.

Changelog

Version Description
4.4.0 The $css_class argument was added.
1.0.0 Introduced.

User Contributed Notes