Advertisement
mbis

Add query URL parameters to the custom permalink

Apr 30th, 2022
1,361
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.67 KB | None | 0 0
  1. <?php
  2. /**
  3.  * 1. Add custom metabox
  4.  */
  5. function pm_add_metabox() {
  6.   add_meta_box(
  7.     'bis_additional-data',
  8.     __( 'Query URL Parameters', 'bis' ),
  9.     'bis_mb_html',
  10.     array('page'),
  11.     'side',
  12.     'high'
  13.   );
  14. }
  15. add_action( 'add_meta_boxes', 'pm_add_metabox' );
  16.  
  17. function bis_mb_html($post) {
  18.     wp_nonce_field( '_pm_metabox_nonce', 'pm_metabox_nonce' );
  19.  
  20.     $pm_url_parameters = esc_textarea(get_post_meta(get_the_ID(), 'pm_url_parameters', true));
  21.     ?>
  22.  
  23.     <p>
  24.         <input class="widefat" name="pm_url_parameters" type="text" value="<?php echo esc_attr( $pm_url_parameters ); ?>">
  25.     </p>
  26.     <?php
  27. }
  28.  
  29. /**
  30.  * 2. Save custom metabox data
  31.  */
  32. function pm_metabox_save($post_id) {
  33.     if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; }
  34.     if ( ! isset( $_POST['pm_metabox_nonce'] ) || ! wp_verify_nonce( $_POST['pm_metabox_nonce'], '_pm_metabox_nonce' ) ) { return; }
  35.     if ( ! current_user_can( 'edit_post', $post_id ) ) { return; }
  36.  
  37.     if ( isset( $_POST['pm_url_parameters'] ) || isset( $_POST['pm_url_parameters'] ) ) {
  38.         update_post_meta( $post_id, 'pm_url_parameters', $_POST['pm_url_parameters'] );
  39.     }
  40.  
  41. }
  42. add_action( 'save_post', 'pm_metabox_save' );
  43.  
  44. /**
  45.  * 3. Add query URL parameters to the custom permalink
  46.  */
  47. function pm_append_url_parameter($permalink, $post) {
  48.   if(!empty($post->post_type) && (in_array($post->post_type, array('page')))) {
  49.         $pm_url_parameters = esc_textarea(get_post_meta(get_the_ID(), 'pm_url_parameters', true));
  50.  
  51.         if(!empty($pm_url_parameters)) {
  52.             $permalink .= $pm_url_parameters;
  53.         }
  54.     }
  55.  
  56.     return $permalink;
  57. }
  58. add_filter('permalink_manager_filter_final_post_permalink', 'pm_append_url_parameter', 999, 2);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement