Get wp_title() from page ID into a variable

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).

Related posts

2 comments

  1. 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.

  2. 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;
    ?>
    

Comments are closed.