How to Add Article Schema without a Plugin

When it comes to schema markup, the most complicated one is the one that you have to add to all your posts and pages.

Adding schema markup to all posts and past is something that nobody is willing to do manually, especially when you have hundreds and hundreds of posts.

If you add this to your functions.php file, it will add the basic article schema to all your posts.

function add_article_schema_to_posts() {
  if ( is_single() && 'post' == get_post_type() ) {
    $schema = '{
      "@context": "https://schema.org",
      "@type": "Article",
      "mainEntityOfPage": {
        "@type": "WebPage",
        "@id": "' . get_permalink() . '"
      },
      "headline": "' . get_the_title() . '",
      "image": {
        "@type": "ImageObject",
        "url": "' . get_the_post_thumbnail_url() . '"
      },
      "datePublished": "' . get_the_date( 'c' ) . '",
      "dateModified": "' . get_the_modified_date( 'c' ) . '",
      "author": {
        "@type": "Person",
        "name": "' . get_the_author() . '"
      },
      "publisher": {
        "@type": "Organization",
        "name": "' . get_bloginfo( 'name' ) . '",
        "logo": {
          "@type": "ImageObject",
          "url": "' . get_site_icon_url() . '"
        }
      },
      "description": "' . wp_strip_all_tags( get_the_excerpt() ) . '"
    }';

    echo '<script type="application/ld+json">' . $schema . '</script>';
  }
}
add_action( 'wp_head', 'add_article_schema_to_posts' );

Table of Contents


Disclaimer

This is not the perfect solution, you can make adjustments to the code to mimic what most SEO Plugins are doing.

There are more code snippets where this came from.

Manuel Campos, English Professor

Manuel Campos

I am José Manuel. I am writing about things I know and things that I am learning about WordPress. I hope you find the content of this blog useful.

WP SURFER

home

about

privacy

contact

© 2024 WP SURFER • Made with Love in Costa Rica