2

I'm pretty sure that it's not possible but can I get the result of wp_title() into a variable if I know post's ID?

So, for instance I'm on a "blog" page and I want to have the title of "about" page in a variable (not in the <title> tag like in this questions: Setting title using wp_title filter).

2 Answers 2

2

As you said, wp_title works only for current post, so can be a little tricky save it in a variable for a post that is not the current.

However, wp_title works not only for singular post / page / cpt but also for every type of archive. So it's easy create a custom function that copy the part of the core function that regard the single post / page.

   function get_the_wp_title( $postid = '', $sep = '&raquo;', $seplocation = '' ) {
     if ( ! $postid ) return '';
     $post = get_post($postid);
     if ( ! is_object($post) || ! isset($post->post_title) ) return '';
     $t_sep = '%WP_TITILE_SEP%';
     $title = apply_filters('single_post_title', $post->post_title, $post);
     $prefix = '';
     if ( ! empty($title) ) $prefix = " $sep ";
     if ( 'right' == $seplocation ) { // sep on right, so reverse the order
        $title_array = explode( $t_sep, $title );
        $title_array = array_reverse( $title_array );
        $title = implode( " $sep ", $title_array ) . $prefix;
      } else {
        $title_array = explode( $t_sep, $title );
        $title = $prefix . implode( " $sep ", $title_array );
      }
      return apply_filters('wp_title', $title, $sep, $seplocation);
    }

Code is in large part copied fron the core wp_title function.

Note that all filters defined for wp_title also works for this function.

1
  • Thank you! That's a solution but too bad that there is no built-in function like this. Perhaps it's not that useful.
    – Paul
    Aug 31, 2013 at 22:03
0

wp_title() function has a second parameter 'display' . Set it to false to get the title in a variable :

<?php $variable = wp_title('&raquo;',FALSE); ?>

If you want to get the title by page ID :

<?php
$pageID = 86;
$page = get_post($pageID);
echo $page->post_title;
?>
1
  • 2
    Yes, but wp_title() also adds something like: Page Title - Site Name. Or it comes with a filter in functions.php in the default theme which modifies its behavior. I'd like to get this title and not page's title which can be also obtained with get_the_title( $id );.
    – Paul
    Aug 31, 2013 at 9:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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