WordPress plugin : Add page title and description programmatically.

Spread the love

If you want to programmatically set the page title and meta description for a specific page in WordPress, you can use the wp_title filter for the title and the pre_get_document_title and wp_head actions for the meta description. Here’s an example:

Code

// Set the page title
function custom_page_title($title) {
    // Check if it's the specific page you want to modify the title for
    if (is_page('your-page-slug')) {
        // Change the title as needed
        $new_title = 'Your New Page Title';
        $title = $new_title . ' | ' . get_bloginfo('name'); // Append the site name if desired
    }

    return $title;
}

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

// Set the meta description
function custom_page_meta_description() {
    // Check if it's the specific page you want to set the meta description for
    if (is_page('your-page-slug')) {
        // Change the meta description as needed
        $meta_description = 'Your meta description goes here.';
        echo '<meta name="description" content="' . esc_attr($meta_description) . '" />' . PHP_EOL;
    }
}

add_action('wp_head', 'custom_page_meta_description');

Replace 'your-page-slug' with the actual slug or ID of the page for which you want to set the title and meta description. Update 'Your New Page Title' and 'Your meta description goes here.' with the desired title and description.

Please note that these examples assume you are not using a theme that supports the title-tag feature, in which case you might need to handle the title in a different way. If your theme supports title-tag, the title is typically handled dynamically by WordPress.

Scroll to Top