Skip to content

Instantly share code, notes, and snippets.

@georgestephanis
Created November 12, 2013 16:34
Show Gist options
  • Save georgestephanis/7434099 to your computer and use it in GitHub Desktop.
Save georgestephanis/7434099 to your computer and use it in GitHub Desktop.
Useful as part of a nest of toggles as to whether a CPT should be defined. For example, whether the theme supports it, or whether something filters it active, or ~this~.
<?php
function get_all_cpts_in_db() {
global $wpdb;
if ( false === ( $cpts = get_transient( 'all_cpts_in_db' ) ) {
$cpts = $wpdb->get_col( "SELECT DISTINCT( `post_type` ) FROM {$wpdb->posts}" );
set_transient( 'all_cpts_in_db', $cpts );
}
return (array) $cpts;
}
function does_db_have_cpt( $cpt_slug ) {
$cpts = get_all_cpts_in_db();
return in_array( $cpt_slug, $cpts );
}
add_action( 'save_post', 'maybe_purge_cpts_in_db_transient' );
function maybe_purge_cpts_in_db_transient( $post_id ) {
$post_type = get_post_type( $post_id );
if ( ! does_db_have_cpt( $post_type ) ) {
delete_transient( 'all_cpts_in_db' );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment