Search code examples
phpwordpressrefactoringquery-variables

How to refactor this Wordpress query?


I am using query_vars in my function.php to get some data in my URL after a form is submitted. This is all working fine, however I feel like the code can be improved a lot, but I'm not sure how to refactor this.

function add_query_vars(
 $membership_vars
) {
 $membership_vars[] = "firstName";
 $membership_vars[] = "membership";
 $membership_vars[] = "subscription";
 $membership_vars[] = "total";
 return $membership_vars;
}

add_filter('query_vars', 'add_query_vars');

And then in a custom page template (PHP) I am displaying this on the page like this:

$firstName = urldecode($wp_query->query_vars['firstName']);
$membership = urldecode($wp_query->query_vars['membership']);
$subscription = urldecode($wp_query->query_vars['subscription']);
$total = urldecode($wp_query->query_vars['total']);

<section>
 <p>Congratulations <?php echo $firstName ?>!</p>
 <p>You have chosen: <?php echo $membership ?> 
 <p>You have subscribed to: <?php echo $subscription ?> 
 <p>Your total paid is: <?php echo $total ?> 
</section>

As you can see the code isn't DRY, however as mentioned I'm not sure how to refactor this in PHP.


Solution

  • Maybe you can try something like this:

    function add_query_vars( $membership_vars ) {
     $params = array( 'firstName', 'membership', 'subscription', 'total' );
     
     foreach ( $params as $param ) {
       $membership_vars[] = $param;
     }
    
     return $membership_vars;
    }
    
    add_filter('query_vars', 'add_query_vars');
    

    and then in the template:

    $params = array( 'firstName', 'membership', 'subscription', 'total' );
    $values = array();
    
    foreach ( $params as $param ) {
      $values[$param] = urldecode( get_query_var($param, '') );
    }
    
    <section>
     <p>Congratulations <?php echo esc_html( $values['firstName'] ); ?>!</p>
     <p>You have chosen: <?php echo esc_html( $values['membership'] );?> 
     <p>You have subscribed to: <?php echo esc_html( $values['subscription'] ); ?> 
     <p>Your total paid is: <?php echo esc_html( $values['total'] ); ?> 
    </section>