Skip to content

Instantly share code, notes, and snippets.

@fjarrett
Last active October 4, 2015 14:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save fjarrett/2653299 to your computer and use it in GitHub Desktop.
Save fjarrett/2653299 to your computer and use it in GitHub Desktop.
Add prefixes to WordPress post types when a theme is activated
<?php
/* Checks to see if new post type names (with prefixes) are being used. If not, then the old
* post type names are converted as long as there aren't conflicting post type names that are
* being registered by other plugins.
*
* @hook {action} after_setup_theme
*/
function fjarrett_prefix_post_types(){
global $wpdb;
$prefix = 'fjarrett_'; // Define the prefix you would like to use
$post_types = array( 'acme', 'foo', 'bar' ); // Create an array of existing post type names you want to add the prefix to
foreach ( $post_types as $post_type ) {
// Check first to see if another plugin is registering a conflicting post type name
if ( post_type_exists( $post_type ) ) {
continue;
}
// Check to see if database entries exist for the prefixed post type
$new_entries_exist = ( $wpdb->query( $wpdb->prepare( "SELECT * FROM " . $wpdb->posts . " WHERE post_type = %s", $prefix . $post_type ) ) ) ? true : false;
// Move along if new entries exist
if ( $new_entries_exist ) {
continue;
}
// If we make it this far, check to see if database entries exist for the old post type
$old_entries_exist = ( $wpdb->query( $wpdb->prepare( "SELECT * FROM " . $wpdb->posts . " WHERE post_type = %s", $post_type ) ) ) ? true : false;
// Add the prefix to old entries
if ( $old_entries_exist ) {
$wpdb->query(
$wpdb->prepare(
'UPDATE ' . $wpdb->posts . ' SET post_type = %s WHERE post_type = %s',
$prefix . $post_type,
$post_type
)
);
$wpdb->query(
$wpdb->prepare(
'UPDATE ' . $wpdb->posts . ' SET guid = replace( guid, "post_type = %s", "post_type = %s" )',
$post_type,
$prefix . $post_type
)
);
}
}
}
add_action( 'after_setup_theme', 'fjarrett_prefix_post_types' );
@fjarrett
Copy link
Author

Sadly, there is not a hook yet that fires only when themes are activated.

The after_setup_theme action is a little misleading in that it fires when WordPress sets up the current theme, not when an admin activates and/or configures the current theme. So, it's basically firing with every load of WP when the theme is active.

Someone first made a patch for this 3 years ago and it looks like it's finally being revisited now: http://core.trac.wordpress.org/ticket/7795

The changelog for register_activation_hook() looks depressing as well: http://codex.wordpress.org/Function_Reference/register_activation_hook#Changelog

@pippinsplugins
Copy link

Yeah, sad indeed. after_theme_setup is probably the best one to use for now.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment