Skip to content

Instantly share code, notes, and snippets.

@thefuxia
Last active August 11, 2016 11:03
Show Gist options
  • Star 12 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save thefuxia/5477050 to your computer and use it in GitHub Desktop.
Save thefuxia/5477050 to your computer and use it in GitHub Desktop.
T5 Silent Flush - Flushes rewrite rules whenever a custom post type or taxonomy is registered and not already part of these rules. This is a soft flush, the .htaccess will not be rewritten.
<?php # -*- coding: utf-8 -*-
/**
* Plugin Name: T5 Silent Flush
* Description: Flushes rewrite rules whenever a custom post type or taxonomy is registered and not already part of these rules. This is a soft flush, the .htaccess will not be rewritten.
* Version: 2013.05.04
* Author: Thomas Scholz <info@toscho.de>
* Author URI: http://toscho.de
* License: MIT
* License URI: http://www.opensource.org/licenses/mit-license.php
*/
add_action( 'registered_post_type', 't5_silent_flush_cpt', 10, 2 );
add_action( 'registered_taxonomy', 't5_silent_flush_tax', 10, 3 );
/**
* Flush rules for custom post types.
*
* @wp-hook registered_post_type
* @param string $post_type
* @param stdClass $args
* @return void
*/
function t5_silent_flush_cpt( $post_type, $args )
{
if ( ! t5_silent_flush_args_check( $args ) )
return;
$slug = t5_silent_flush_get_slug( $args->rewrite, $post_type );
$rules = get_option( 'rewrite_rules' );
if ( ! isset ( $rules[ $slug . '/?$' ] ) )
flush_rewrite_rules( FALSE );
}
/**
* Flush rules for custom post taxonomies.
*
* @wp-hook registered_taxonomy
* @param string $taxonomy
* @param string $object_type Post, user, comment
* @param array $args Will be converted to object
* @return void
*/
function t5_silent_flush_tax( $taxonomy, $object_type, $args )
{
// No idea why we get an array here, but an object for post types.
// Objects are easier to write, so ...
$args = (object) $args;
if ( ! t5_silent_flush_args_check( $args ) )
return;
$slug = t5_silent_flush_get_slug( $args->rewrite, $taxonomy );
$rules = get_option( 'rewrite_rules' );
if ( ! isset ( $rules[ $slug . '/(.+?)/?$' ] ) )
flush_rewrite_rules( FALSE );
}
/**
* Basic check on the arguments of the registered object.
*
* @param stdClass $args
* @return boolean
*/
function t5_silent_flush_args_check( $args )
{
if ( $args->_builtin )
return FALSE;
if ( ! $args->public )
return FALSE;
if ( ! $args->rewrite )
return FALSE;
return TRUE;
}
/**
* Get the slug to search for in current rewrite rules.
*
* @param array $rewrite
* @param string $name
* @return string
*/
function t5_silent_flush_get_slug( $rewrite, $name )
{
if ( ! isset ( $rewrite[ 'slug' ] ) )
return $name;
if ( ! is_string( $rewrite[ 'slug' ] ) )
return $name;
return $rewrite[ 'slug' ];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment