plugin development – best practice for query string values – get_query_var always empty for my value supplied in query string

Question

I’m constructing a form in my WP plugin. I need to specify which records to modify by supplying a value in the URL like so:

https://example.com/wp-admin/admin.php?page=my_plugin-event-video-assoc&event_post_id=123

I’ve properly set up my code so that I have my desired code running to handle that url request, but get_query_var always returns NULL:

$event_post_id = get_query_var('event_post_id', NULL);
var_dump($event_post_id); // this is always NULL

Having read the docs on custom query vars, I have tried add_filter in my plugin’s primary PHP file:

function myco_query_vars( $qvars ) {
    $qvars[] = 'event_post_id';
    return $qvars;
}
add_filter( 'query_vars', 'myco_query_vars' );

But, even though this is the first thing my plugin does, this doesn’t help and get_query_vars still returns NULL. I have also tried moving that add_filter code to various other spots but it doesn’t make any difference where I put it. Do I need to run that code in some kind of WP hook?

I can extract event_post_id from superglobal $_GET['event_post_id'] but I’d like my code to observer WP best practices. To be honest, I don’t understand the reason for this peculiar aspect of WordPress. I fail to see how it provides any security at all because it doesn’t validate anything.

Can anyone tell me what is considered best practice for working with custom query string values in WordPress? If this is to user get_query_var, please help me fix my code so that function returns my variable.

0
S. Imp 2 weeks 2021-11-18T13:05:20-05:00 0 Answers 0 views 0

Leave an answer

Browse
Browse