Created
December 26, 2011 01:50
-
-
Save trepmal/1520378 to your computer and use it in GitHub Desktop.
WordPress: [concept] Cross-CPT Parent/Child
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Plugin Name: [concept] Cross-CPT Parent/Child | |
//Description: Just a demo!. | |
add_action( 'init', 'kl_post_types'); | |
function kl_post_types() { | |
register_post_type( 'parent', array( | |
'label' => 'Parent', | |
'public' => true, | |
'hierarchical' => true, | |
'supports' => array( 'title', 'editor' ), | |
'taxonomies' => array( 'category' ), | |
'rewrite' => true, | |
) ); | |
register_post_type( 'child', array( | |
'label' => 'Child', | |
'public' => true, | |
'hierarchical' => true, | |
'supports' => array( 'title', 'editor' ), | |
'taxonomies' => array( 'category' ), | |
'rewrite' => array( 'slug' => '' ), | |
) ); | |
add_action( 'add_meta_boxes', 'cross_cpt_parent_box_init' ); | |
} | |
function cross_cpt_parent_box_init() { | |
add_meta_box( 'cpt_parent', 'CPT Parent', 'cross_cpt_parent_box', 'child' ); | |
} | |
function cross_cpt_parent_box() { | |
global $post; | |
$parent = isset($post->post_parent) ? $post->post_parent : 0; | |
$args = array( | |
'child_of' => 0, | |
'sort_order' => 'ASC', | |
'show_option_none' => '(none)', | |
'sort_column' => 'post_title', | |
'hierarchical' => 1, | |
'post_type' => 'parent', | |
'selected' => $parent, | |
'name' => 'parent_id', | |
); | |
wp_dropdown_pages( $args ); | |
} | |
add_filter( 'rewrite_rules_array','kl_rewrite_rules', 9 ); | |
function kl_rewrite_rules( $rules ) { | |
$newrules = array(); | |
$newrules['child/([a-z0-9-]*)/([a-z0-9-]*)$'] = 'index.php?post_type=child&name=$matches[2]'; | |
return $newrules + $rules; | |
} | |
add_filter( 'query_vars','kl_query_vars', 1 ); | |
function kl_query_vars( $vars ) { | |
return $vars; | |
} | |
add_action( 'wp_loaded','kl_flush_rules' ); | |
function kl_flush_rules(){ | |
$rules = get_option( 'rewrite_rules' ); | |
if ( ! isset( $rules['child/([a-z0-9-]*)/([a-z0-9-]*)$'] ) ) { | |
global $wp_rewrite; | |
$wp_rewrite->flush_rules(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment