Wordpress:如何陷入get_the_content

时间:2013-04-12 11:49:21

标签: php wordpress plugins filter hook

我正在寻找一种在Wordpress中挂钩get_the_content方法的正确方法。 Wordpress为the_contentthe_excerpt()get_the_excerpt()提供了挂钩,但不为get_the_content()提供挂钩。我有一个插件,我维护它附加并在内容帖子中添加一些HTML。 我对the_excerpt()get_the_excerpt()使用了相同的内容。我应该怎样做才能支持get_the_content()以及我看到大多数主题现在使用get_the_content()?即:如果主题使用get_the_content()而不是the_content(),我的插件将失败。

我的插件代码如下:

add_action('init', 'my_init');

function my_init() {
  add_filter('the_content', 'my_method', 12);
  add_filter('get_the_content', 'my_method', 12);
}


function my_method($content) {
  $content = "blah blah".$content."blah blah";

  return $content;
}

上面的代码(在我的插件中)从主题中侦听the_content call并将自己的内容添加到文章中。

假设这是主题文件中的方法:

<div class="entry-content">
  <?php the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?>
</div><!-- .entry-content -->

在上述情况下它可以正常工作。

但是如果主题代码是这样的(请注意从the_content()到get_the_content())的更改。

<div class="entry-content">
  <?php echo get_the_content( __( 'Continue reading <span class="meta-nav">&rarr;</span>', 'twentytwelve' ) ); ?>
</div><!-- .entry-content -->

我的插件失败,因为没有为get_the_content定义挂钩。由于我无法控制主题代码,Wordpress在documentation中解释的解决方案对我没有帮助:

<?php apply_filters('the_content',get_the_content( $more_link_text, $stripteaser, $more_file )) ?>

更新:为了清晰起见,扩展了问题定义。

2 个答案:

答案 0 :(得分:2)

您是否尝试过以下操作?

根据法典:

  

如果使用过滤内容的插件(add_filter('the_content')),   那么这将不会应用过滤器,除非你这样称呼它   (使用apply_filters):

<?php apply_filters('the_content',get_the_content( $more_link_text, $stripteaser, $more_file )) ?>

wordpress codex中记录了它。

EDITED

尝试使用输出缓冲将the_content放入变量。

这样你就不用担心get_the_content

ob_start();
the_content();
$newContent = ob_get_clean();

现在它存储在一个名为$newContent的变量中,便于您操作。

答案 1 :(得分:0)

只需尝试使用以下内容:

使用Cform的示例:

add_filter('get_the_content', 'cforms_insert',10);

适用于Reference

(或)

$content = get_the_content();
$content = apply_filters('the_content', $content);
$panels = explode("[newpage]", $content);

我认为这可以帮助您解决问题。