skip to Main Content

I’ve got a page called /team-page/?id=x that’s built in WordPress

The URL parameter of "id" determines the content that will dynamically show on that page. However, my meta title for that page is statically set. Is there a way I can dynamically set the meta title based on the page content? Each variation of /team-page will have a unique H1 – ideally, I’d love to just grab this H1 and set it as the meta title.

2

Answers


  1. You can achieve it with document_title_parts filter. It takes $titles as parameter, which consist of two parts – title and site (except for front page – instead of site it’s tagline)

    So try this

    add_filter( 'document_title_parts', 'custom_title' );
    function custom_title( $title ) {
    
        // Just to see what is $title
        // echo '<pre>';
        // print_r( $title );
        // echo '</pre>';
        // die();
    
        $uri = parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ); // get current uri without query params
    
        // Change meta only on team-page. 
        if ( '/team-page/' === $uri ) {
            // you can do here anything you want
            $title['title'] = get_the_title() . ' and whatever string you want ' . $_GET['id'];
        }
        return $title;
    }
    

    Also don’t forget to check and sanitize your $_GET['id'] if needed.

    Login or Signup to reply.
  2. You’re looking for get_query_var()

    Retrieves the value of a query variable in the WP_Query class.

    One small thing to understand is that get_query_var() only retrieves public query variables that are recognized by WP_Query.

    So we need to register our variable first. This is considered best practice. Simply using $_GET['id'] is considered to be unsafe within the WordPress ecosystem.

    add_filter( 'query_vars', 'wpso66660959_query_vars' );
    function wpso66660959_query_vars( $qvars ) {
        $qvars[] = 'ref';
        return $qvars;
    };
    

    Also you should use something other than id as it is already used by WordPress to handle the WP_Query. I’ve used ref (reference) but you can choose whatever as long as it doesn’t impact WordPress core.

    then we can simply built our custom title.

    <?= '<title>' . get_the_title() . ' | Order N° ' . get_query_var( 'ref', 'undifined' ) . '</title>'; ?>
    

    Note that, if your theme is using WordPress to set your pages title, you might need to set some sort of conditional statement around add_theme_support( 'title-tag' );, in your function.php.

    Something like…

    //...
    if ( ! is_page( 'team-page' ) )
        add_theme_support( 'title-tag' );
    

    The title-tag is usually included in your theme options.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search