在wordpress帖子中定位标题

时间:2010-08-10 15:47:26

标签: wordpress wordpress-plugin

我正在制作一个修改帖子标题的wordpress插件。我只想在查看单个帖子时这样做。具体来说,我想在标题旁边添加一个链接,但出于问题的目的,我将添加一些仲裁文本。

我开始时使用'the_title'过滤器挂钩,并调用此函数。

function add_button_to_title($title)
{
  global $post;
  if(is_single())
  {
    return $title.'googly googly';
  }
  return $title;
}

问题是,侧栏上的链接显然也使用'the_title',因为我看到我的文字也显示在侧栏中,这导致我:

if(is_single() && in_the_loop())

但是,然后,在我的主题(我想一般的主题)中有一个链接到上一篇文章和下一篇文章,它也使用了“标题”过滤器。所以最后我有:

if(is_single() && in_the_loop() && ($post->post_title == $title))

最后一个条件基本上确保它是正在打印的帖子的标题,而不是下一个或上一个帖子的标题。这是有效的,但我不确定它在不同的主题下会有多好用......看起来非常黑了。来自wordpress大师的任何建议吗?我担心标题会因其他原因而被修改,条件会失败。

感谢任何帮助!

4 个答案:

答案 0 :(得分:2)

应,

除了正如ShaderOp所说,需要进行主题修改之外,还没有一个很好的解决方案。您的解决方案大部分都可以使用。唯一的例外是主题开发人员在页面中更改了查询。我想这可能是一个很好的解决方案,它将覆盖你遇到的95%以上的案例。

答案 1 :(得分:2)

我通过添加一项检查来解决类似的问题,以查看过滤的标题是否与帖子的标题相匹配。这样可以避免页面上的其他帖子标题(侧边栏,菜单中)也被过滤掉。

function add_button_to_title( $title ) {
  global $post;
  if( is_single() && $title == $post->post_title ) {
    return $title . 'googly googly';
  } else {
    return $title;
  }
}

答案 2 :(得分:0)

保留add_button_to_title功能的原始版本会不会更容易,但不是将其挂钩到过滤器,而是直接从相应位置的single.php页面调用它?

例如,在主题single.php中的某个位置,而不是:

<h3 class="storytitle">
    <a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a>
</h3>

使用此:

<h3 class="storytitle">
    <a href="<?php the_permalink() ?>" rel="bookmark">
        <?php echo add_button_to_title(the_title('', '', false); ?>
    </a>
</h3>

答案 3 :(得分:0)

今天我遇到了类似的问题。 the_title在整个页面中被调用几次(例如,在html-head,菜单,侧边栏中)。我遵循了使用条件和帖子/页面ID的类似方法。

此外,我添加了一个布尔标志,使用'the_content'过滤器设置为true。因此标题会更改,直到显示内容为止。这样,我确保侧边栏/窗口小部件不受影响(例如,主题主题有一个默认的窗口小部件,其中包含指向页面的链接 - 这里其他条件不会有用,因为get_the_id()将返回等效项)。仅当主题使用右侧的侧边栏时,此功能才有效。在找到页面/帖子的'the_title'之前,我没有找到一种方法直接挂钩以启用布尔标志。

function myplugin_adjust_title($title, $id) {
    global $myplugin_title_changed;

    if ($myplugin_title_changed) {
        return $title;
    }

    if (in_the_loop() && is_page('myplugin') && $id == get_the_ID()) {
        $title = '';
    }
    return $title;
}
add_filter('the_title', 'myplugin_adjust_title', 10, 2);

function myplugin_adjust_title_helper_content($content) {
    global $myplugin_title_changed;
    $myplugin_title_changed = true;
    return $content;
}
add_filter('the_content', 'myplugin_adjust_title_helper_content');
相关问题