5ally

Untitled

Aug 21st, 2018
250
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.01 KB | None | 0 0
  1. <?php
  2. // See https://wordpress.stackexchange.com/a/301351/137402 for details.
  3.  
  4. add_action( 'init', 'my_register_questions_post_types' );
  5. function my_register_questions_post_types() {
  6.     register_post_type( 'science-question', array(
  7.         'label' => 'Science Questions',
  8.         'public' => true,
  9.         'supports' => [ 'title', 'editor', 'custom-fields' ],
  10.         'rewrite' => array(
  11.             // The rewrite slug. You can change 'science' to whatever you like.
  12.             'slug' => 'science/question/%task_id%',
  13.         ),
  14.         // Other args here.
  15.     ) );
  16.  
  17.     register_post_type( 'math-question', array(
  18.         'label' => 'Math Questions',
  19.         'public' => true,
  20.         'supports' => [ 'title', 'editor', 'custom-fields' ],
  21.         'rewrite' => array(
  22.             // The rewrite slug. You can change 'math' to whatever you like.
  23.             'slug' => 'math/question/%task_id%',
  24.         ),
  25.         // Other args here.
  26.     ) );
  27. }
  28.  
  29. add_action( 'init', 'my_register_questions_taxonomies' );
  30. function my_register_questions_taxonomies() {
  31.     // Set the slug to 'task'.
  32.     register_taxonomy( 'task', array( 'science-question', 'math-question' ), array(
  33.         'label' => 'Tasks',
  34.         'public' => true,
  35.         'hierarchical' => true,
  36.         // Other args here.
  37.     ) );
  38. }
  39.  
  40. add_action( 'init', 'my_register_questions_rewrite_tags' );
  41. function my_register_questions_rewrite_tags() {
  42.     add_rewrite_tag( '%task_id%', '(\d+)' );
  43. }
  44.  
  45. // Replaces %task_id% in the permalink (i.e. $post_link).
  46. add_filter( 'post_type_link', 'my_filter_questions_post_type_link', 10, 2 );
  47. function my_filter_questions_post_type_link( $post_link, $post ) {
  48.     if ( false !== strpos( $post_link, '%task_id%' ) ) {
  49.         $cats = get_the_terms( $post, 'task' );
  50.         $cat_id = 0;
  51.  
  52.         // If the post was assigned to at least one "task" category.
  53.         if ( $cats && ! is_wp_error( $cats ) ) {
  54.             $cat_id = $cats[0]->term_id;
  55.         }
  56.         // Else, /{SLUG}/question/0/{POST SLUG} should work well. =) But of
  57.         // course, all "question" CPT posts should be assigned to *at least*
  58.         // one "task".
  59.  
  60.         $post_link = str_replace( '%task_id%', $cat_id, $post_link );
  61.     }
  62.  
  63.     return $post_link;
  64. }
Add Comment
Please, Sign In to add comment