使用WordPress短代码添加<meta>标签

eme*_*his 8 php wordpress shortcode

我正在编写一个使用短代码的简单WordPress插件.我希望包含短<meta>代码的页面具有特定标记.这可能吗?如果是这样,有没有一种优雅的方式来做到这一点?

我知道我可以<meta>使用wp_head钩子添加标签,但我希望元标记内容与插件生成的字符串匹配.我可以将所有代码移动到标题中,但后来我不确定如何从短代码中引用它.换句话说,当我<head>使用过滤器声明一个变量时,它不能用我用短代码调用的类方法.

有任何想法吗?

更新:

提出了一个很好的解决方案,其中短代码的处理函数将操作添加到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');
}
Run Code Online (Sandbox Code Playgroud)

这是膨胀,但问题是wp_head在解码短代码之前发生并添加动作(所以没有任何东西被添加到头部,代码高于ALONE).为了使它工作,我在这篇文章中借用了解决方案.它基本上是一个"向前看"到帖子的功能,看看是否有任何短代码.如果是,那么IT增加了add_action('wp_head'....

编辑:我删除了关于如何传递变量的后续问题.这是一个新的问题在这里.

Max*_*ime 12

第一次尝试(不要使用此...请参阅下面的'编辑'):

首先,您需要使用以下内容设置短代码:

add_shortcode( 'metashortcode', 'metashortcode_addshortcode' );
Run Code Online (Sandbox Code Playgroud)

然后,你将创建一个函数,你必须在其中添加一个wp_head类似的东西:

function metashortcode_addshortcode() {
    add_action( 'wp_head', 'metashortcode_setmeta' );
}
Run Code Online (Sandbox Code Playgroud)

然后,您将在以下内容中定义您要执行的操作wp_head:

function metashortcode_setmeta() {
    echo '<meta name="key" content="value">';
}
Run Code Online (Sandbox Code Playgroud)

添加短代码[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' );
Run Code Online (Sandbox Code Playgroud)

请享用!