Skip to content

Instantly share code, notes, and snippets.

@AWOL-TECH
Created October 3, 2023 18:09
Show Gist options
  • Save AWOL-TECH/8ed08974856d513bf7783e2237f80319 to your computer and use it in GitHub Desktop.
Save AWOL-TECH/8ed08974856d513bf7783e2237f80319 to your computer and use it in GitHub Desktop.
Code snippet to convert the h2 tag of a blog post (single) to h1 for better SEO. For some reason many themes are outputting H2 tags which will be flagged by SEO tools and such. This code will search for an h2 tag in your single post with the specified class and switch it over to an h1.
/**
* functions.php or main plugin file
**/
function awol_enqueue_modify_title_script() {
if (is_single()) {
wp_enqueue_script('modify-title', get_stylesheet_directory_uri() . '/js/awol-modify-title.js', array('jquery'), '1.0', true);
}
}
add_action('wp_enqueue_scripts', 'awol_enqueue_modify_title_script');
/**
* awol-modify-title.js
* create a /js/ folder in your child theme and save the code below as awol-modify-title.js
**/
document.addEventListener("DOMContentLoaded", function() {
// Check if we are on a single post page
if (isSinglePost()) {
// Check if the element with class "entry_title" exists - change this to your class in the h2 tag
var entryTitle = document.querySelector('.entry_title');
if (entryTitle) {
// Create a new H1 element
var newH1 = document.createElement('h1');
// Copy the contents of the existing H2 to the new H1
newH1.innerHTML = entryTitle.innerHTML;
// Add a class to the new H1
newH1.classList.add('entry_title'); // Replace 'entry_title' with your desired class name
// Add a data attribute e.g. property="something" to the new H1 - change to whatever you need
newH1.setAttribute('itemprop', 'name');
// Replace the existing H2 with the new H1 element.
entryTitle.parentNode.replaceChild(newH1, entryTitle);
}
}
});
function isSinglePost() {
// Check if the body element has a class of "single-post"
return document.body.classList.contains('single-post');
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment