如何重构这个 Wordpress 查询?

How to refactor this Wordpress query?

我在我的 function.php 中使用 query_vars 在提交表单后在我的 URL 中获取一些数据。这一切都很好,但我觉得代码可以改进很多,但我不确定如何重构它。

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');

然后在自定义页面模板 (PHP) 中,我在页面上显示如下:

$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>

如您所见,代码不是 DRY,但是如前所述,我不确定如何在 PHP 中重构它。

使用自定义过滤器定义查询变量怎么样?

在您的 plugin/functions.php 中,您可以:

add_filter('PRFX_membership_vars', 'PRFX_default_membership_vars', 10,1);

function PRFX_default_membership_vars($vars) {
    return ['firstName', 'membership', 'subscription', 'total'];
}



add_filter('query_vars', 'PRFX_add_query_vars');

function PRFX_add_query_vars($vars) {

    $membership_vars = apply_filters('PRFX_membership_vars', []);

    foreach ($membership_vars as $membership_var) {
        $vars[] = $membership_var;
    }
    return $vars;
}

在您的自定义模板中:

$membership_vars = apply_filters('PRFX_membership_vars', []);
$membership_values = [];


foreach ($membership_vars as $membership_var) {
    $membership_values[$membership_var] = urldecode( get_query_var($membership_var, '') );
}


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

也许你可以尝试这样的事情:

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');

然后在模板中:

$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>