9

我正在编写一个使用简码的简单 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');
}

这很好,但问题是 wp_head 发生在短代码被解析并添加操作之前(因此没有任何内容被添加到单独的代码的头部)。为了让它发挥作用,我借用了这篇文章中的解决方案。它基本上是一个“向前看”帖子的功能,看看是否有任何短代码出现。如果是,则 IT 添加add_action('wp_head'....

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

4

1 回答 1

14

第一次尝试(不要使用这个......请参阅下面的“编辑”)

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

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' );

享受!

于 2012-03-04T20:51:15.583 回答