我正在编写一个使用shortcode的简单WordPress插件。我希望包含快捷代码的页面具有特定的<meta>
标记。这可能吗?如果是这样,有没有一种优雅的方法可以做到这一点?
我知道我可以用wp_head
钩子添加<meta>
标签,但我希望元标签内容与插件生成的字符串相匹配。我可以将所有代码移到标题中,但我不知道以后如何从短代码中引用它。换句话说,当我用过滤器在<head>
中声明一个变量时,它对我用shortcode调用的类方法不可用。
有什么想法吗?
更新:
提出了一个很好的解决方案,其中shortcode的处理程序函数将操作添加到wp_head钩子:
add_shortcode('fakeshortcode', 'fakeshortcode_handler');
function fakeshortcode_handler() {
function add_meta_tags() {
//echo stuff here that will go in the head
}
add_action('wp_head', 'add_meta_tags');
}
这是很好的,但问题是wp_head发生在解析短代码并添加操作之前(因此,单独使用上面的代码不会向头中添加任何内容)。为了让它发挥作用,我借用了这篇文章中的解决方案。这基本上是一个"向前看"帖子并查看是否有任何短代码即将到来的功能。如果是,则it添加add_action('wp_head'...
。
编辑:我删除了关于如何传递变量的后续问题。这是一个新问题。
第一次尝试(不要使用这个…请参阅下面的"编辑"):
首先,你需要用这样的东西设置你的短代码:
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' );
享受吧!
这篇文章是很久以前写的,但我认为使用has_shortcode
函数是另一个很好的解决方案:
function add_meta_tags() {
global $post;
if ( has_shortcode( $post->post_content, 'YOUR-SHORTCODE' ) ) {
//echo stuff here that will go in the head
}
}
add_action('wp_head', 'add_meta_tags');