views:

39

answers:

2

I am brand new at writing Wordpress plugins, so to start I am trying to create a simple one that just modifies a string. I wrote the script a while ago, and know that it functions. But to use it for Wordpress I want to apply it to the post titles. When I replaced the string with the function "get_the_title()" it returns a white screen. I stripped it down to:

function display_title() {
echo get_the_title();
}

add_action('the_title', 'display_title');

This still returns a white screen. So I figure it must be the "get_the_title()" function. Can anybody explain to me why this doesn't work, and maybe a different way to retrieve the title string?

+1  A: 

Well, for one thing, 'the_title' isn't an action, it's a filter. So that function is never firing. So it's not the fault of that function, it is probably something else. I would suggest reading up on the plugin api and learning the difference between actions and filters. Filters are specifically designed to do what you want in a simple way:

http://codex.wordpress.org/Plugin_API/

John P Bloch
Thank you, I see the difference now. However, if I just enter a string instead of the "get_the_title()" function then it seems to work without issue. It loads the page and replaces the titles with that string.
Ben
+3  A: 

As John says the_title is a filter rather than an action hook, although your function will be called regardless of whether you register it using add_filter or add_action.

Your problem is that with filters your function is expected to return a value (normally a modified version of the argument passed). So, to modify the title using this filter you should do something like this:

function display_title($title) {
    $title .= '!'; // Do something with the title string here
    return $title;
}

add_filter('the_title', 'display_title');
Richard M
Thank you, this worked splendidly. I didn't know that I could use a variable called $title and it would retrieve each string. Is there a list of these somewhere in the codex?
Ben
The function doesn't retrieve the title string, it gets passed it as an argument. Basically when you call `the_title()` in your Wordpress loop, the title is retrieved from the database, passed through all the functions hooked into the `the_title` filter and then printed.Unfortunately most filters are not documented in the codex, so the best way to find out what arguments your function will be passed is to search the Wordpress source code for `apply_filters('filter_name'`, the arguments which follow this will be passed to your function.
Richard M
If you look at `wp-includes/default-filters.php`, most of the filters for `the_title` should be there.
John P Bloch