Last active
December 20, 2023 13:20
-
-
Save AVGP/e2b1a138163ca2896e056a6c9a9f9bde to your computer and use it in GitHub Desktop.
A barebones WP plugin to add JSON-LD based on post data automatically. It won't really work, but it's a starting point for exploration.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* | |
Plugin Name: JSON-LDfy | |
Plugin URI: https://www.google.com | |
Description: Add JSON-LD based on some post data | |
Version: 1.0 | |
Author: Martin Splitt | |
Author URI: https://www.google.com | |
License: GPL2 | |
License URI: https://www.gnu.org/licenses/gpl-2.0.html | |
Text Domain: wtf is this? | |
Domain Path: /wat | |
*/ | |
/* | |
Stuff above is a mandatory header that WP plugins just want to have. | |
This "plugin" is probably doing a lot of things wrong, I'm not a WP plugin dev, but it is a starting point. | |
Let's start with the code that *does stuff*! | |
*/ | |
function add_jsonld_to_content( $content ) { | |
// this will use a global variable called $post which is only available in the loop and in a singular post. | |
if( !is_singular() || !in_the_loop() || !is_main_query() ) { | |
return $content; // we bail out. | |
} | |
/* | |
The $content is basically the HTML that will show up on the page. | |
We append a JSON-LD script to it. | |
*/ | |
$content .= '<script type="application/ld+json"> | |
{ | |
"@context": "https://schema.org", | |
"@type": "NewsArticle", | |
"headline": "' . $post->post_title . '", | |
"datePublished": "' . get_post_time( 'Y-m-d\\TH:i:sO' ) . '", | |
"author" : [{ | |
"@type": "Person", | |
"name": "' . get_the_author() . '", | |
"url": "https://not-sure-how-to-do-this-one.com/lol" | |
}] | |
} | |
</script>'; | |
return $content; // finally, return it all back to WP to display. | |
} | |
// the next line makes WP call our function when the post content is ready to show.. | |
add_filter( 'the_content', add_jsonld_to_content ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment