黃聰:wordpress自定義post_type,並且自定義固定鏈接


<?
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();
?>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM