Get wp_title() from page ID into a variable

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 = '»', $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.

Leave a Comment

error code: 523