0

I am really new to wordpress, and I am trying to build a page that updates the database with given arguments. For example, if the client application calls https://codonmaster.000webhostapp.com/ranking.php?scoretime=30&nickname=hellooo&score=100 , then I want to insert a column ('hellooo',30,100) in my database.

However, I am stuck getting the query vars to my php code. The page always shows

defaultname,1566820333(current timestamp),0 

Yes, the default values. Where should I change to make this page acknowledge needed variables?

My code is below:

<?php
 require_once(dirname(__FILE__) . '/wp-config.php');
 $wp->init();
 $wp->parse_request();
 $wp->query_posts();
 $wp->register_globals();
 $wp->send_headers();


function themeslug_query_vars( $qvars ) {
    $qvars[] = 'scoretime';
    $qvars[] = 'nickname';
    $qvars[] = 'score';
   return $qvars;
}
add_filter( 'query_vars', 'themeslug_query_vars' );

$scoretime = get_query_var( 'scoretime', ''.time());
$nickname = get_query_var( 'nickname', 'defaultname' );
$score = get_query_var('score', '0');
echo "{$nickname},{$scoretime},{$score}";

1 Answer 1

1

In WordPress, query vars are not what you think they are. They are the arguments for the global WP_Query object which processes the main page request. Check the docs for more information.

What you need in that particular case is to check the $_GET parameters on the page load.

For example:

$scoretime = filter_input( INPUT_GET, 'scoretime', FILTER_SANITIZE_NUMBER_INT ) ?: (string) time();
$score = filter_input( INPUT_GET, 'score', FILTER_SANITIZE_NUMBER_INT ) ?: '0';
$nickname = filter_input( INPUT_GET, 'nickname', FILTER_SANITIZE_STRING ) ?: 'defaultname';

Please note that I have accessed them using filter_input() method, which is a good practice to do a sanitization of the inputs, especially if you plan on inserting them in the database.

Also, I have added the default values after the ?:, which is a short ternary operator, and assigns the left if its value is truthy.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.