函数文档

wp_post_preview_js()

💡 云策文档标注

概述

wp_post_preview_js() 函数用于在预览标签页或窗口中输出一个小的 JavaScript 片段,以在用户导航到其他页面时移除 window.name。这可以防止用户离开后重用同一标签页进行预览。

关键要点

  • 函数仅在 is_preview() 返回 true 且 $post 非空时执行
  • 生成的 window.name 必须与 post_submit_meta_box() 中使用的名称匹配,格式为 'wp-preview-' 加上文章 ID
  • 该函数通过输出内联 JavaScript 来清理预览窗口状态

代码示例

function wp_post_preview_js() {
	global $post;

	if ( ! is_preview() || empty( $post ) ) {
		return;
	}

	// Has to match the window name used in post_submit_meta_box().
	$name = 'wp-preview-' . (int) $post->ID;

	ob_start();
	?>
	<script>
	( function() {
		var name = '<?php echo $name; ?>';
		if ( window.name === name ) {
			window.name = '';
		}
	} )();
	</script>
	<?php
	ob_end_flush();
}

注意事项

  • 此函数自 WordPress 4.3.0 版本引入
  • 相关函数包括 wp_remove_surrounding_empty_script_tags()、wp_print_inline_script_tag() 和 is_preview()

📄 原文内容

Outputs a small JS snippet on preview tabs/windows to remove window.name when a user is navigating to another page.

Description

This prevents reusing the same tab for a preview when the user has navigated away.

Source

function wp_post_preview_js() {
global $post;

if ( ! is_preview() || empty( $post ) ) {
return;
}

// Has to match the window name used in post_submit_meta_box().
$name = 'wp-preview-' . (int) $post->ID;

ob_start();
?>
<script>
( function() {
var query = document.location.search;

if ( query && query.indexOf( 'preview=true' ) !== -1 ) {
window.name = '<?php echo $name; ?>';
}

if ( window.addEventListener ) {
window.addEventListener( 'pagehide', function() { window.name = ''; } );
}
}());
//# sourceURL=<?php echo rawurlencode( __FUNCTION__ ); ?>
</script>
</pre><p class="wporg-dot-link-list"><a href="https://developer.wordpress.org/reference/files/wp-includes/functions.php/">View all references</a> <a href="https://core.trac.wordpress.org/browser/tags/6.9.4/src/wp-includes/functions.php#L7781">View on Trac</a> <a href="https://github.com/WordPress/wordpress-develop/blob/6.9.4/src/wp-includes/functions.php#L7781-L7809">View on GitHub</a></p></section>

<section class="wp-block-wporg-code-reference-related" data-nosnippet="true"><h2 id="related" class="is-toc-heading wp-block-heading has-heading-5-font-size" tabindex="-1" ><a href="#related">Related</a></h2> <section style="margin-top:var(--wp--preset--spacing--20)" class="wp-block-wporg-code-table" id="uses"><figure class="wp-block-table "><table><thead><tr><th scope="col">Uses</th><th scope="col">Description</th></tr></thead><tbody><tr class=""><td><a href="https://developer.wordpress.org/reference/functions/wp_remove_surrounding_empty_script_tags/">wp_remove_surrounding_empty_script_tags()</a><code>wp-includes/script-loader.php

Removes leading and trailing _empty_ script tags.

wp_print_inline_script_tag()wp-includes/script-loader.php

Prints an inline script tag.

is_preview()wp-includes/query.php

Determines whether the query is for a post or page preview.

Changelog

Version Description
4.3.0 Introduced.