Created
August 20, 2019 08:01
-
-
Save wpmudev-sls/c97591fc1359d9ea7bf05d6b9f39472a to your computer and use it in GitHub Desktop.
[SmartCrawl] - Custom Permalink. Allow to define a custom slug name for sitemap
This file contains 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: [SmartCrawl] - Custom Permalink | |
* Plugin URI: https://premium.wpmudev.org/ | |
* Description: Allow to define a custom slug name for sitemap | |
* Author: Alessandro Kaounas @ WPMUDEV | |
* Author URI: https://premium.wpmudev.org/ | |
* License: GPLv2 or later | |
*/ | |
if ( ! defined( 'ABSPATH' ) ) { | |
exit; | |
} | |
// Define custom sitemap slug | |
define('WPMUDEV_SITEMAP_SLUG', 'demo.xml'); | |
add_action('plugins_loaded', 'wpmudev_smartcrawl_init'); | |
function wpmudev_smartcrawl_init() { | |
if (class_exists('Smartcrawl_Controller_Sitemap')) { | |
// Remove current action | |
remove_action('init', array( Smartcrawl_Controller_Sitemap::get(), 'serve_sitemap' ), 999); | |
// Override plugin function | |
add_action('init', 'wpmudev_smartcrawl_serve_sitemap'); | |
} | |
} | |
function wpmudev_smartcrawl_custom_permalink() { | |
return home_url( false ) . '/' . WPMUDEV_SITEMAP_SLUG; | |
} | |
function wpmudev_smartcrawl_serve_sitemap() { | |
if ( ! function_exists( 'smartcrawl_get_sitemap_path' ) ) { | |
return; | |
} | |
if ( ! Smartcrawl_Settings::get_setting( 'sitemap' ) ) { | |
return; | |
} | |
$instance = Smartcrawl_Controller_Sitemap::get(); | |
$url_path = $instance->get_url_part( $_SERVER['REQUEST_URI'], PHP_URL_PATH ); | |
$path = smartcrawl_get_sitemap_path(); | |
$is_gzip = preg_match( '~\.gz$~i', $url_path ); | |
$path = $is_gzip ? "{$path}.gz" : $path; | |
// Report it | |
if ( preg_match( '~' . preg_quote( '/' . WPMUDEV_SITEMAP_SLUG ) . '(\.gz)?$~i', $url_path ) ) { | |
// Check if any updates are required | |
if ( ! file_exists( $path ) || wpmudev_smartcrawl_is_sitemap_dirty() ) { | |
wpmudev_smartcrawl_update_sitemap(); | |
} | |
// Serve the file if it exists | |
if ( file_exists( $path ) ) { | |
if ( $is_gzip ) { | |
header( 'Content-Encoding: gzip' ); | |
} | |
header( 'Content-Type: text/xml' ); | |
die( smartcrawl_file_get_contents( $path ) ); // phpcs:ignore -- Can't escape XML | |
} else { | |
wp_die( esc_html__( 'The sitemap file was not found.', 'wds' ) ); | |
} | |
} | |
} | |
function wpmudev_smartcrawl_is_sitemap_dirty() { | |
return ! Smartcrawl_Xml_Sitemap::get()->is_sitemap_pristine(); | |
} | |
function wpmudev_smartcrawl_update_sitemap() { | |
Smartcrawl_Xml_Sitemap::get()->generate_sitemap(); | |
Smartcrawl_Xml_Sitemap::get()->set_sitemap_pristine( true ); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment