Advertisement
Guest User

Wordpress Plugin - Remove slug from custom post type (mod)

a guest
Aug 30th, 2013
730
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.79 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: Remove slug from custom post type
  4. Plugin URI: http://www.ultimatewebtips.com/remove-slug-from-custom-post-type/
  5. Description: Removes the slug from permalink on all custom post types
  6. Version: 1.0.3
  7. Author: Joakim Ling
  8. Author URI: http://www.ultimatewebtips.com/
  9. */
  10.  
  11. class UWT_RemoveSlugCustomPostType{
  12.    
  13.     static $_s = null;
  14.     private $htaccess_tag = 'REMOVE SLUG CUSTOM POST TYPE RULES';
  15.    
  16.     public function __construct() {
  17.         $this->rewrite_rules();
  18.        
  19.         add_action('admin_menu', array(&$this, 'menu'));
  20.         add_action('wp_insert_post', array(&$this, 'post_save'));
  21.  
  22.         add_filter('post_type_link', array(&$this, 'remove_slug'), 10, 3);
  23.         add_filter('redirect_canonical', array(&$this, 'cancel_redirect_canonical'));
  24.         //add_filter('posts_request', array(&$this, 'request'));
  25.        
  26.     }
  27.    
  28.     function cancel_redirect_canonical($redirect_url) {
  29.         $suffix = get_option('uwt_permalink_customtype_suffix');
  30.         if (empty($suffix))
  31.             return $redirect_url;
  32.         global $wp_post_types;
  33.         foreach ($wp_post_types as $type=>$custom_post) {
  34.             $hit = get_query_var($custom_post->query_var);
  35.             if (!empty($hit))
  36.                 return false;
  37.         }
  38.     }
  39.    
  40.     public function menu() {
  41.         add_options_page( 'Permalink custom post type', 'Custom post type', 'manage_options', __FILE__, array(&$this, 'menu_page'));
  42.     }
  43.    
  44.     public function menu_page() {
  45.    
  46.         if (!current_user_can('manage_options')) {
  47.             wp_die( __('You do not have sufficient permissions to access this page.') );
  48.         }
  49.        
  50.         // Returns checked (for checkbox) if the provided string is found in the provided array)
  51.         function checked_val($target_val, $target_array) {
  52.        
  53.             if ($target_array != null) {
  54.        
  55.                 if (in_array( $target_val, $target_array ) ) {
  56.                     return 'checked="checked" ';
  57.                 }
  58.                
  59.             }
  60.        
  61.         }
  62.        
  63.         // Query for getting custom post types
  64.         $get_post_types_args = array('public'=>true, '_builtin'=>false);
  65.         $post_types = get_post_types($get_post_types_args, 'objects');
  66.        
  67.         // Field names
  68.         $hidden_field_name = 'uwt_submit_hidden';
  69.         $selected_cpts_key = 'selected_cpts';
  70.         $opt_name = 'uwt_permalink_customtype_suffix';
  71.        
  72.        
  73.         // If the form has been submitted
  74.         if(isset($_POST[$hidden_field_name]) && $_POST[$hidden_field_name] == 'Y') {
  75.  
  76.             // Loop through each custom post type
  77.             foreach( $post_types as $post_type ) {
  78.            
  79.                 // If this custom post type is selected
  80.                 if ($_POST['chk_' . $post_type->name] == 'checked') {
  81.  
  82.                     // Record it in the array
  83.                     $selected_cpts[] = $post_type->name;
  84.                    
  85.                 }
  86.  
  87.             }
  88.  
  89.             update_option($selected_cpts_key, $selected_cpts);
  90.        
  91.             // Save the suffix
  92.             $opt_val = preg_replace('/[^0-9a-z]+/i', '', $_POST[$opt_name]);
  93.             update_option($opt_name, $opt_val);
  94.            
  95.         ?>
  96.        
  97.             <div class="updated"><p><strong><?php _e('Settings saved' ); ?></strong></p></div>
  98.            
  99.         <?php
  100.        
  101.             $this->rewrite_rules(true);
  102.             $this->add_rules_htaccess();
  103.         }
  104.        
  105.         else {
  106.        
  107.             // Otherwise just load existing options
  108.             $selected_cpts = get_option($selected_cpts_key);
  109.             $opt_val = get_option($opt_name);
  110.            
  111.         }
  112.        
  113.         ?>
  114.  
  115. <div class="wrap">
  116.  
  117. <?php screen_icon(); ?>
  118.  
  119. <h2>Permalink custom post type</h2>
  120.  
  121. <h3>Custom Post Types to remove the permalink slug from</h3>
  122.  
  123. <form name="form1" method="post" action="">
  124.  
  125. <?php
  126.    
  127.     // get the registered data about each post type with get_post_type_object
  128.     foreach( $post_types as $post_type ) {
  129.             echo '<p><label for="chk_' . $post_type->name . '"><input id="chk_' . $post_type->name . '" name="chk_' . $post_type->name . '" type="checkbox" value="checked" ' . checked_val( $post_type->name, $selected_cpts ) . '/> ' . $post_type->name . '</label></p>';
  130.     }
  131.  
  132.  
  133. ?>
  134.  
  135. <h3>Custom Post Type Permalink Suffix</h3>
  136.  
  137.  
  138.     <input type="hidden" name="<?php echo $hidden_field_name; ?>" value="Y">
  139.     <p>Permalink custom type suffix:
  140.         <input type="text" name="<?php echo $opt_name; ?>" value="<?php echo $opt_val; ?>" size="20">
  141.         <br />
  142.         <em>Use this option if you want your custom post type posts to have a suffix, e.g. ".html", leave empty if you want normal structure (http://siteurl/post_title/)</em>
  143.     </p>
  144.    
  145.     <hr />
  146.     <p class="submit">
  147.         <input type="submit" name="Submit" class="button-primary" value="<?php esc_attr_e('Save Changes') ?>" />
  148.     </p>
  149. </form>
  150. </div>
  151. <?php
  152.     }
  153.    
  154.     public function request($input) {
  155.         global $wp_post_types;
  156.         $array_slug[] = "wp_posts.post_type = 'post'";
  157.         foreach ($wp_post_types as $type=>$custom_post) {
  158.             if ($custom_post->_builtin == false)
  159.                 $array_slug[] = "wp_posts.post_type = '" . trim($type, '/') . "'";
  160.         }
  161.         $types = '(' . implode(' || ', $array_slug) . ')';
  162.         $input = str_replace("wp_posts.post_type = 'post'", $types, $input);
  163.         return $input;
  164.     }
  165.    
  166.     static public function init() {
  167.         if (self::$_s == null) {
  168.             self::$_s = new self();
  169.         }
  170.         return self::$_s;
  171.     }
  172.    
  173.     static public function flush_rewrite_rules() {
  174.         $uwt_o = self::init();
  175.         $uwt_o->rewrite_rules(true);   
  176.         $uwt_o->add_rules_htaccess();
  177.     }
  178.  
  179.     public function post_save($post_id) {
  180.         global $wp_post_types;
  181.         $post_type = get_post_type($post_id);
  182.         foreach ($wp_post_types as $type=>$custom_post) {
  183.             if ($custom_post->_builtin == false && $type == $post_type) {
  184.                 $this->rewrite_rules(true);
  185.                 $this->add_rules_htaccess();               
  186.             }
  187.         }
  188.     }
  189.    
  190.     public function remove_slug($permalink, $post, $leavename) {
  191.         global $wp_post_types;
  192.         $suffix = get_option('uwt_permalink_customtype_suffix');
  193.         foreach ($wp_post_types as $type=>$custom_post) {
  194.             if ($custom_post->_builtin == false && $type == $post->post_type) {
  195.                 $custom_post->rewrite['slug'] = trim($custom_post->rewrite['slug'], '/');
  196.                 $permalink = str_replace(get_bloginfo('url') . '/' . $custom_post->rewrite['slug'] . '/', get_bloginfo('url') . "/", $permalink);
  197.                 if (!empty($suffix))
  198.                     $permalink = substr($permalink, 0, -1) . ".{$suffix}";
  199.             }
  200.         }
  201.         return $permalink;
  202.     }
  203.    
  204.     public function rewrite_rules($flash = false) {  
  205.         global $wp_post_types, $wpdb;
  206.         $suffix = get_option('uwt_permalink_customtype_suffix');
  207.         foreach ($wp_post_types as $type=>$custom_post) {
  208.             if ($custom_post->_builtin == false) {
  209.                 $querystr = "SELECT {$wpdb->posts}.post_name, {$wpdb->posts}.post_parent
  210.                 FROM {$wpdb->posts}
  211.                 WHERE {$wpdb->posts}.post_status = 'publish'
  212.                 AND {$wpdb->posts}.post_type = '{$type}'
  213.                 AND {$wpdb->posts}.post_date < NOW()";
  214.                 $posts = $wpdb->get_results($querystr, OBJECT);
  215.                 foreach ($posts as $post) {
  216.                     if($post->post_parent > 0) {
  217.                         $regexStr = $this->build_regex($post);
  218.                             $regex = (!empty($suffix)) ? $regexStr . "/{$post->post_name}\\.{$suffix}\$" : $regexStr . "/{$post->post_name}\$";
  219.                             add_rewrite_rule($regex, "index.php?{$custom_post->query_var}={$post->post_name}", 'top');
  220.                     }
  221.                     else {
  222.                         $regex = (!empty($suffix)) ? "{$post->post_name}\\.{$suffix}\$" : "{$post->post_name}\$";
  223.                             add_rewrite_rule($regex, "index.php?{$custom_post->query_var}={$post->post_name}", 'top');
  224.                         }
  225.                     }
  226.                 }
  227.             }
  228.            
  229.             if ($flash == true)
  230.             flush_rewrite_rules(false);
  231.         } // a recursive function to build the path of the cpt's hierarchy used in the regex pattern
  232.        
  233.         private function build_regex($post) {
  234.             $parent = get_post($post->post_parent);
  235.         if($parent->post_parent > 0)
  236.         $str .= $this->build_regex($parent) . '/' . $parent->post_name;
  237.         else   $str .= $parent->post_name;
  238.         return $str;
  239.     }
  240.  
  241.     private function add_rules_htaccess() {
  242.         global $wp_post_types;
  243.         $suffix = get_option('uwt_permalink_customtype_suffix');
  244.         $write = array();
  245.         $htaccess_filename = ABSPATH . '/.htaccess';
  246.         if (is_readable($htaccess_filename)) {
  247.             $htaccess = fopen($htaccess_filename, 'r');
  248.             $content = fread($htaccess, filesize($htaccess_filename));
  249.             foreach ($wp_post_types as $type=>$custom_post) {
  250.                 $rewrite_rule = (!empty($suffix))
  251.                             ? "RewriteRule ^{$custom_post->query_var}/(.+)/\$ /\$1\.{$suffix} [R=301,l]"
  252.                             : "RewriteRule ^{$custom_post->query_var}/(.+)/\$ /\$1 [R=301,L]";
  253.                 if (strpos($content, $rewrite_rule) == false && $custom_post->_builtin == false)
  254.                     $write[] = $rewrite_rule;
  255.             }
  256.             fclose($htaccess);
  257.         }
  258.         else {
  259.             add_action('admin_notices', array(&$this, 'compatibility_notice'));
  260.             return;
  261.         }
  262.        
  263.         if (!empty($write) && is_writable($htaccess_filename)) {
  264.             $new_rules = '# BEGIN ' . $this->htaccess_tag . PHP_EOL;
  265.             $new_rules .= str_replace('$', '\\$', implode(PHP_EOL, $write)) . PHP_EOL;
  266.             $new_rules .= '# END ' . $this->htaccess_tag;
  267.             if (strpos($content, "# BEGIN {$this->htaccess_tag}") === false) {
  268.                 file_put_contents($htaccess_filename, $new_rules . PHP_EOL . PHP_EOL . $content);
  269.             }
  270.             else {
  271.                 $pattern = "/# BEGIN {$this->htaccess_tag}.*?# END {$this->htaccess_tag}/ims";
  272.                 $content = preg_replace($pattern, $new_rules, $content);
  273.                 file_put_contents($htaccess_filename, $content);
  274.             }
  275.         }
  276.         else
  277.             add_action('admin_notices', array(&$this, 'compatibility_notice'));
  278.     }
  279.    
  280.     public function compatibility_notice() {
  281.         global $wp_post_types;
  282.         $rules = '';
  283.         foreach ($wp_post_types as $type=>$custom_post) {
  284.             if ($custom_post->_builtin == false) {
  285.                 $slug = str_replace('/', '', $custom_post->rewrite['slug']);
  286.                 $rules .= 'RewriteRule ^' . $slug . '/(.+)$ /$1 [R=301,L]<br />';
  287.             }
  288.         }
  289.        
  290.         echo '<div class="error fade" style="background-color:red;"><p><strong>Remove Slug Custom post type error!</strong><br />.htaccess is not writable, please add following lines to complete your installation: <br />'.$rules.'</p></div>';
  291.     }
  292. }
  293.  
  294. add_action('init', array('UWT_RemoveSlugCustomPostType', 'init'), 99);
  295. register_activation_hook( __FILE__, array('UWT_RemoveSlugCustomPostType', 'flush_rewrite_rules') );
  296. register_deactivation_hook( __FILE__, array('UWT_RemoveSlugCustomPostType', 'flush_rewrite_rules') );
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement