Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- // See https://wordpress.stackexchange.com/a/301351/137402 for details.
- add_action( 'init', 'my_register_questions_post_types' );
- function my_register_questions_post_types() {
- register_post_type( 'science-question', array(
- 'label' => 'Science Questions',
- 'public' => true,
- 'supports' => [ 'title', 'editor', 'custom-fields' ],
- 'rewrite' => array(
- // The rewrite slug. You can change 'science' to whatever you like.
- 'slug' => 'science/question/%task_id%',
- ),
- // Other args here.
- ) );
- register_post_type( 'math-question', array(
- 'label' => 'Math Questions',
- 'public' => true,
- 'supports' => [ 'title', 'editor', 'custom-fields' ],
- 'rewrite' => array(
- // The rewrite slug. You can change 'math' to whatever you like.
- 'slug' => 'math/question/%task_id%',
- ),
- // Other args here.
- ) );
- }
- add_action( 'init', 'my_register_questions_taxonomies' );
- function my_register_questions_taxonomies() {
- // Set the slug to 'task'.
- register_taxonomy( 'task', array( 'science-question', 'math-question' ), array(
- 'label' => 'Tasks',
- 'public' => true,
- 'hierarchical' => true,
- // Other args here.
- ) );
- }
- add_action( 'init', 'my_register_questions_rewrite_tags' );
- function my_register_questions_rewrite_tags() {
- add_rewrite_tag( '%task_id%', '(\d+)' );
- }
- // Replaces %task_id% in the permalink (i.e. $post_link).
- add_filter( 'post_type_link', 'my_filter_questions_post_type_link', 10, 2 );
- function my_filter_questions_post_type_link( $post_link, $post ) {
- if ( false !== strpos( $post_link, '%task_id%' ) ) {
- $cats = get_the_terms( $post, 'task' );
- $cat_id = 0;
- // If the post was assigned to at least one "task" category.
- if ( $cats && ! is_wp_error( $cats ) ) {
- $cat_id = $cats[0]->term_id;
- }
- // Else, /{SLUG}/question/0/{POST SLUG} should work well. =) But of
- // course, all "question" CPT posts should be assigned to *at least*
- // one "task".
- $post_link = str_replace( '%task_id%', $cat_id, $post_link );
- }
- return $post_link;
- }
Add Comment
Please, Sign In to add comment