views:

22

answers:

2

Hi, I am working on a wordpress plugin that modifies the title of a post. I only want to do this when I am viewing a single post. To be specific, I want to add a link beside the title, but for purposes of the question, I will be adding some arbitary text.

I started out by using the 'the_title' filter hook, and calling this function.

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

The problem is, the links on the side bar apparently also use 'the_title', as I saw my text showing up in the side bars as well, which led me to:

if(is_single() && in_the_loop())

But then, in my theme(and i suppose themes in general) there is a link to the previous post and next post, which also uses 'the title' filter. So finally I have:

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

The last conditional basically makes sure that it is the title of the post that is being printed, not the title of the next or previous post. This works but I am not sure how well it will work given different themes...It seems like terribly hacked together. Any advice from wordpress gurus out there? I am worried that the title would be modified for other reasons and the conditional will fail.

Any help is appreciated!

A: 

Wouldn't it be easier to keep the original version of your add_button_to_title function, but instead of hooking it to a filter, call it directly from your single.php page in the appropriate place?

For example, somewhere in your theme's single.php, instead of this:

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

Use this:

<h3 class="storytitle">
    <a href="<?php the_permalink() ?>" rel="bookmark">
        <?php echo add_button_to_title(the_title('', '', false); ?>
    </a>
</h3>
ShaderOp
This isn't really a good solution because it's going to be a plugin, not a theme modification. That means there's no access to the theme files from the plugin, so Ying needs a solution that will work almost everywhere without file modification.
John P Bloch
@ShaderOp: yeap, this is what i initially did to bootstrap. As John pointed out, I want it to be able to reach a wide audience who should just be able to 'plug it in'. Thanks for the contribution though!
Ying
+1  A: 

Ying,

There isn't really a good solution except, as ShaderOp said, requiring theme modification. Your solution will work for the most part. The only exception is if the theme developer has changed the query in a page. I'd say this is probably a good enough solution that it'll cover more than 95% of the cases you'd run into.

John P Bloch