Last active
September 5, 2019 23:29
-
-
Save PaulMorel/0b4abcd7709db562980358bd027b4c4c to your computer and use it in GitHub Desktop.
Create an endpoint for a generated JSON site map of every post, page, post-type, etc.
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 | |
/** | |
* Create an endpoint for a generated JSON site map of every post, page, post-type, etc. | |
* | |
* @return void | |
*/ | |
function json_sitemap() { | |
global $wp; | |
$url = 'sitemap.json'; | |
// Return early if URL is incorrect. Causes 404 in usual cases | |
if ( $wp->request !== $url ) { | |
return; | |
} | |
// Setup sitemap variable | |
$sitemap = []; | |
// Get all posts | |
$posts = get_posts([ | |
'post_type' => 'any', | |
'posts_per_page' => -1, | |
'post_status' => 'publish' | |
]); | |
// Get all post urls | |
foreach( $posts as $post ) { | |
$sitemap[] = get_permalink( $post ); | |
} | |
//Get all post types | |
$post_types = get_post_types([ | |
'public' => true | |
]); | |
// Get all post type archive urls | |
foreach ( $post_types as $post_type) { | |
$sitemap[] = get_post_type_archive_link( $post_type ); | |
} | |
// Get all authors | |
$authors = get_users(); | |
// Get all author urls | |
foreach ($authors as $author) { | |
$sitemap[] = get_author_posts_url( $author->ID ); | |
} | |
// Get all public taxonomies | |
$taxonomies = get_taxonomies([ | |
'public' => true | |
]); | |
foreach ( $taxonomies as $taxonomy ) { | |
// Get all terms for each taxonomy | |
$terms = get_terms([ | |
'taxonomy' => $taxonomy, | |
'hide_empty' => false, | |
]); | |
// Get all term urls | |
foreach( $terms as $term ){ | |
$sitemap[] = get_term_link( $term ); | |
} | |
} | |
// Get the search page | |
$sitemap[] = home_url('?s='); | |
// Get the search page with no results | |
$sitemap[] = home_url('?s=most%20likely%20an%20empty%20search%20result%20page'); | |
// Get a 404 page | |
$sitemap[] = home_url('404-page-most-likely-not-found/'); | |
// Remove any falsy values | |
$sitemap = array_filter($sitemap); | |
// Reset array keys | |
$sitemap = array_values($sitemap); | |
//Send a JSON response back and exit | |
wp_send_json($sitemap, 200); | |
} | |
add_action( 'template_redirect', 'json_sitemap' ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment