Turn simple WordPress title script into a PHP function

I have this PHP code to construct the contents of my WordPress <title> tag:

<?php
    global $page, $paged;
    // Add a page number if necessary:
    if($paged >= 2 || $page >= 2) {
        echo sprintf(__('Page %s', 'theme-name'), max( $paged, $page ) ).' | ';
    }
    wp_title( '|', true, 'right' );
    // Add the blog name.
    bloginfo( 'name' ); 
?>

Which, if on for example Page 2 of the list of posts, returns:

Read More

Page 2 | Completed Projects | Website Name

QUESTION

How can I turn the PHP above into a function that returns a variable $pageTitle so that I can reuse this string throughout the page?

Related posts

Leave a Reply

2 comments

  1.     global $page, $paged;
        // Add a page number if necessary:
        $pageTitle = '';
        if($paged >= 2 || $page >= 2) {
            $pageTitle .= sprintf(__('Page %s', 'theme-name'), max( $paged, $page ) ).' | ';
        }
        $pageTitle .= wp_title( '|', false, 'right' );
        // Add the blog name.
        $pageTitle .= get_bloginfo( 'name' ); 
    
  2. WordPress is a mess and has different ways to either just echo to the screen or return info.

    All of this is in this codex

    For title use wp_title( '|', false );

    For bloginfo use get_bloginfo( 'name' );

    You can then use these and wrap a function around the entire thing.