In this step-by-step guide, we will show you how to enhance the search engine optimization (SEO) of your WordPress website by adding and activating custom SEO fields (Title, Description, Keywords) on your posts and pages. By using meta boxes and integrating them into your custom template, you can improve your website’s visibility and ranking on search engines.
Step 1: Access the functions.php File
Locate the functions.php file in your WordPress theme directory.
Path: /wp-content/themes/sunshine/functions.php (replace “sunshine” with the name of your theme directory)
Open the functions.php file and create space to add the meta_box code. You can add your custom functions after the “Dynamic Sidebar” section, which is usually indicated by the comment: “// If Dynamic Sidebar Exists”.
/** =============================================
* Add custom fields for SEO
* Add SEO meta boxes on Pages and Posts
*===============================================*/
function add_seo_meta_boxes() {
$post_types = array('page', 'post');
foreach ($post_types as $post_type) {
add_meta_box(
'seo_meta_box',
'SEO Settings',
'render_seo_meta_box',
$post_type,
'normal',
'high'
);
}
}
add_action('add_meta_boxes', 'add_seo_meta_boxes');
After launching the seo_meta_boxes(), now it is time to render them
// Render SEO meta boxes
function render_seo_meta_box($post) {
// Retrieve current values for fields
$seo_title = get_post_meta($post->ID, '_seo_title', true);
$seo_description = get_post_meta($post->ID, '_seo_description', true);
$seo_keywords = get_post_meta($post->ID, '_seo_keywords', true);
// Include nonce field for security
wp_nonce_field('seo_meta_box_nonce', 'seo_meta_box_nonce');
// Output HTML for the fields
?>