• pedjas

    (@pedjas)


    I set custom query)var handler according to https://developer.www.ads-software.com/reference/hooks/query_vars/

    It works fine. When I add query unto site URL it is available in query_vars.

    However, I need to have validation of allowed values for custom query var, and if proper value is not specified i want to return HTTP 404 to user visitor.

    I cannot find how to intercept setting query_var, to check and disallow invalid values.

    Is that possible?

    • This topic was modified 1 year ago by Yui. Reason: mv developmental section
Viewing 1 replies (of 1 total)
  • Deviant Media LLC

    (@abretado1985)

    Hook Into pre_get_posts Action: The pre_get_posts action hook allows you to alter the query before it is executed. This is where you can add your validation logic.

    function validate_custom_query_var( $query ) {
      if ( !is_admin() && $query->is_main_query() ) {
        // Assuming 'my_custom_var' is your custom query var
        $value = get_query_var( 'my_custom_var', false );
    
        // Validate the value of the custom query var
        if ( $value !== false ) {
          if ( !is_valid_custom_var( $value ) ) {
            // If invalid, force a 404 error
            $query->set_404();
            status_header( 404 );
            nocache_headers();
          }
        }
      }
    }
    add_action( 'pre_get_posts', 'validate_custom_query_var' );
    

    Define Your Validation Function: Implement the is_valid_custom_var function to validate the custom query variable’s value according to your requirements.

    function is_valid_custom_var( $value ) {
      // Define your validation logic here
      // Return true if valid, false otherwise
      return in_array($value, ['allowed_value1', 'allowed_value2']); // Example
    }
    

    Remember to replace 'my_custom_var' with your actual custom query variable name and modify the validation logic in is_valid_custom_var to suit your specific requirements.

Viewing 1 replies (of 1 total)
  • The topic ‘How to validate url query var?’ is closed to new replies.