黄聡:wordpressカスタムpost_type、およびカスタム固定リンク

5572 ワード

<?
class zsjh
{
    function init()
    {
        add_action( 'init', array($this,'create_zsjh') );
        add_filter('post_type_link', array($this, 'get_permalink') ,1 ,3 );
    }
    
    function create_zsjh()
    {
        $labels = array(
            'name' => ' ',   
            'singular_name' => ' ',   
            'add_new' => ' ',   
            'add_new_item' => ' ',   
            'edit_item' => ' ',   
            'new_item' => ' ',   
            'view_item' => ' ',   
            'search_items' => ' ',   
            'not_found' =>  ' ~',   
            'not_found_in_trash' => ' ~',    
            'parent_item_colon' => '',  
            'menu_name' => ' ',
            'menu_position' => 5
        );   
        $args = array(   
            'labels' => $labels,
            'public' => true,
            'publicly_queryable' => true,
            'show_ui' => true,
            'show_in_menu' => true,
            'query_var' => true,
            'capability_type' => 'post',
            'has_archive' => true,
            'hierarchical' => false,
            'supports' => array('title','editor','thumbnail','comments','custom-fields'),
        );
        
        // hc_post_type_zsjh 
        register_post_type( 'hc_post_type_zsjh', $args);
        // 
        add_action('generate_rewrite_rules',array($this, 'jihua_rewrite_rules') );
    }
    
    function jihua_rewrite_rules( $wp_rewrite )
    {
        global $wp_rewrite;
        $wp_rewrite->add_permastruct('hc_post_type_zsjh', '/jihua/%jihua_id%.html', false);
        $new_rules = array('jihua/([0-9]+)?.html$' => 'index.php?post_type=hc_post_type_zsjh&p=$matches[1]' );
        $wp_rewrite->rules = $new_rules + $wp_rewrite->rules; 
    }

    function get_permalink( $permalink, $post, $leavename )
    {
        // %jihua_id% ID
        $permalink = str_replace("%jihua_id%", $post->ID, $permalink);
        return $permalink;
    }
}

$zsjh = new zsjh();
$zsjh->init();
?>