sql – query_vars doesn’t return query string (trying to get data from $wpdb)

Question

I have a ref query string which matches rows in my wp_invites table.

In my wp_invites table, I have the following columns:

Let’s assume here is one of the rows:

  • Lead name: Freddy
  • Reference: 4FxtfVFszCHd

When the user accesses their invite, their URL will be something like: test.test/?ref=4FxtfVFszCHd

I’m using query_vars to handle the URL parameters. Then accessing the row in the DB where the query string matches reference in the table column.

Here is my current approach:

<?php

/*
* Step 1:
* Get reference query param from URL
*/

function add_query_vars_filter( $vars ){
  $vars[] = "ref";
  return $vars;
}

add_filter( 'query_vars', 'add_query_vars_filter' );



/*
* Step 2:
* Get data from row in wp_invites table where reference equals what's in the query string
*/

$reference = sanitize_text_field( get_query_var('ref') );

global $wpdb;

$table_name = $wpdb->prefix . 'invites';

$results = $wpdb->get_results(
  $wpdb->prepare( "SELECT * FROM $table_name WHERE reference=%s", $reference), ARRAY_A
);


var_dump($results);
  
if( $results ){
  foreach ($results as $result){
    echo '<p>'. $result['lead_name'] . '</p>';
  }
}

?>

Here are my results:

  • The above just prints Welcome to WordPress. This is your first post. Edit or delete it, then start writing!
  • My lead_name echo doesn’t print
  • A var_dump($vars) and ref returned empty
  • A var_dump($results) returns array(0){}

I think my issues are stemming because return $vars; isn’t returning a value for ref?

Edit:

My approach follows what’s listed in the official docs.

Doing the following to access the var returns NULL.

global $wp_query;
var_dump($wp_query->vars);

Unsure how to proceed. My URL definitely has a ref query string

0
Freddy 2 months 2022-12-03T14:52:41-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse