0

I'm using a function to filter the_title, adding a string onto the end, but would also like to return the original title, unfiltered on the same page. Is there a way to get the title without it being filtered?

  • 1
    Did you try remove_filter() ? – birgire Feb 22 '17 at 13:27
2

There's a few ways to do this, but I would argue that the preferred way is, in general, fetching the post_title attribute from the post object. This does not depend on removing all filters for a certain function and adding them back later — the latter requires you to directly access the global $wp_filter.

get_post retrieves the post object for a post ID, and the post object, on construction, populates all post fields with the fields from the database, without applying any filtering.

Thus, your code would simply be

$title = get_post( $post_id )->post_title;

If the post with ID $post_id is not guaranteed to exist, be sure to check whether the returned value from get_post is a post object.

NB another approach is to use get_post_field( 'post_title', $post_id ), which by default only has the filter 'post_title' applied to it (and not the the_title filter). However, as @PatJ kindly pointed out, using the optional $context parameter, you can get the raw value using the context "raw":

get_post_field( 'post_title', $post_id, 'raw' );
  • It would be better to use get_post_field( 'post_title' ); for that, because it includes checks. PS Just noticed you updated ;-) – birgire Feb 22 '17 at 13:42
  • Hehe, updated my answer at exactly the same time. get_post_field applies the post_title filter, so you're not getting the raw data. get_post doesn't really run the risk of not returning an object with the post title property, but I understand your concern; I'd rather do the isset check myself then. – engelen Feb 22 '17 at 13:44
  • 2
    get_post_field() has an optional context parameter, which will accept 'raw' as a context. So to get the unfiltered post_title, you can use get_post_field( 'post_title', $post_id, 'raw' ). – Pat J Feb 22 '17 at 13:47
  • Good point @PatJ, I've updated my answer! – engelen Feb 27 '17 at 19:11
0

You can create your own function, put this in functions.php:

function get_title_no_filters($post = 0){

    $post = get_post( $post );

    echo isset( $post->post_title ) ? $post->post_title : '';
}

use it like this, just like the get_the_title WordPress offers:

get_title_no_filters();//inside a loop no need to send ID or post object

if you are not using it in a loop you can send an ID or a Post Object. This is the raw title no filters.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.