第一次尝试(不要使用这个......请参阅下面的“编辑”):
首先,您需要使用以下内容设置您的简码:
add_shortcode( 'metashortcode', 'metashortcode_addshortcode' );
然后,您将创建一个函数,您必须在其中添加一个wp_head
类似这样的钩子:
function metashortcode_addshortcode() {
add_action( 'wp_head', 'metashortcode_setmeta' );
}
然后,您将在 中定义要执行的操作wp_head
:
function metashortcode_setmeta() {
echo '<meta name="key" content="value">';
}
添加短代码[metashortcode]
应根据需要添加您的元数据。提供代码只是为了帮助您了解如何实现它。它没有经过全面测试。
编辑:前面的代码只是一个概念,由于执行顺序而无法工作。这是一个将获得预期结果的工作示例:
// Function to hook to "the_posts" (just edit the two variables)
function metashortcode_mycode( $posts ) {
$shortcode = 'metashortcode';
$callback_function = 'metashortcode_setmeta';
return metashortcode_shortcode_to_wphead( $posts, $shortcode, $callback_function );
}
// To execute when shortcode is found
function metashortcode_setmeta() {
echo '<meta name="key" content="value">';
}
// look for shortcode in the content and apply expected behaviour (don't edit!)
function metashortcode_shortcode_to_wphead( $posts, $shortcode, $callback_function ) {
if ( empty( $posts ) )
return $posts;
$found = false;
foreach ( $posts as $post ) {
if ( stripos( $post->post_content, '[' . $shortcode ) !== false ) {
add_shortcode( $shortcode, '__return_empty_string' );
$found = true;
break;
}
}
if ( $found )
add_action( 'wp_head', $callback_function );
return $posts;
}
// Instead of creating a shortcode, hook to the_posts
add_action( 'the_posts', 'metashortcode_mycode' );
享受!