user12265276
user12265276

Reputation: 29

On a WordPress page template, what code can customize title and meta description?

On custom-page-template.php, what code can customize the section ( and <meta name=”description”) for all pages which are based on this template? I tried using the following but they nothing on a page template. (They work on functions.php though).

add_filter( 'document_title_parts', 'custom_document_title_parts' );
add_action( 'wp_head', 'my_add_meta_description');

Any idea, what code can customize and in a custom-page-template.php?

Thanks.

Upvotes: 0

Views: 191

Answers (1)

Mohammad Yousefi
Mohammad Yousefi

Reputation: 543

Use this in functions.php: (change page template's name in is_page_template)

add_filter( 'document_title_parts', function( $title_parts_array ) {
    if ( is_page_template('custom.php') ) {
        $title_parts_array['title'] = 'New title';
        echo '<script>document.querySelector(\'meta[name="description"]\').setAttribute("content", "New description");</script>';
    }
    return $title_parts_array;
} );

Or you can use this before get_header() in your custom page template

function new_page_title() {
    echo '<script>document.querySelector(\'meta[name="description"]\').setAttribute("content", "New description2");</script>';
    return 'New Title2';
}
add_action( 'pre_get_document_title', 'new_page_title' );

Upvotes: 1

Related Questions