Categories
Technology

How to Change Page Title by Custom Field in Wordpress

Prerequisite

If I get right you come here to change this 😊 see in Pic below.

How to Change Page Title by Custom Field in Wordpress


If you are using custom theme make sure you have used this hook in your head tag. Because we are going to filter that value based on wp_title( ); hook.

   <title>
        <?php wp_title( '|', true, 'right' ); ?>
    </title> 

Let’s say we have custom field meta key _custom_post_name.

If you have created the ACF field then your field name will be “_” + your_field_name means if you have created page_title then your meta key will be _page_title. πŸ‘

how to modify title?

  • For any single Page or Post
<?php
/**
 * Customize the title for the Single page, if one is not set.
 *
 * @param string $title The original title.
 * @return string The title to use.
 */

add_filter( 'wp_title', 'change_page_title_callabck', 10 , 2 );

function change_page_title_callabck( $title , $separator)
{
    /**
    * To change the title on your single or post page
    */
    if( is_single() ){ 
        // Add your meta key here
        $custom_post_title = get_post_meta( get_the_ID(),'add_your_meta_key', true);
        if( $custom_post_title ){
            $title = $custom_post_title ." ".$seprator." ";
        }
        
    }
    return $title;
    
}
?>
  • For custom post type
<?php
/**
 * Customize the title for the Single page, if one is not set.
 *
 * @param string $title The original title.
 * @return string The title to use.
 */

add_filter( 'wp_title', 'change_page_title_callabck', 10 , 2 );

function change_page_title_callabck( $title , $separator)
{
    /**
    * To change the title on your single or post page
    */
    if( is_single() && 'custom_post_type' == get_post_type() ){ 
        // Add your meta key here
        $custom_post_title = get_post_meta( get_the_ID(),'add_your_meta_key', true);
        if( $custom_post_title ){
            $title = $custom_post_title ." ".$seprator." ";
        }
        
    }
    return $title;
    
}
?>

For different Pages?

  • for category you can use is_cat() OR is_tax().
  • for archive you can use is_archive().

for Reference of wp_title( ); hook.

https://developer.wordpress.org/reference/hooks/wp_title/

https://developer.wordpress.org/reference/functions/wp_title/


If it is helpfulΒ and saves your valuable Time ⏱ please show your support πŸ‘‡.

Buy Me A Coffee

Buy me A Coffee, Thank you and canva ( For Beautiful designs ). Thanks for the reading πŸ‘.