Getting query parameters from URL. It works and it doesn't

Support MB Views Getting query parameters from URL. It works and it doesn'tResolved

Viewing 3 posts - 1 through 3 (of 3 total)
  • Author
    Posts
  • #48750
    EddyPiVEddyPiV
    Participant

    I want to show messages that we exchanged with a user. The username is a query parameter in the URL.
    I'm using the free plugin url-parms for getting the value of the username from the query string.

    The username will be shown and used to filter the messages.
    Showing the username works, but filtering causes a critical error.
    This is my code:

    {% set username = [urlparam param = 'username' /] %}
    
    <h1>Chat with <strong>[urlparam param = 'username' /]</strong></h1>
    
    {% set args = {
        post_type: 'tg-message',
        posts_per_page: 50,
        orderby: 'date',
        order: 'DESC',
        title: username
    } %}
    
    {% set messages = mb.get_posts(args) | reverse %} {# Reverse the array for ascending display #}

    This is the error: PHP Fatal error: Uncaught eLightUp\Twig\Error\SyntaxError: An array element must be followed by a comma. Unexpected token "name" of value "param" ("punctuation" expected with value ",") in ....

    How to get the value from the query parameter working?

    #48757
    PeterPeter
    Moderator

    Hello Eddy,

    It isn't possible to assign a variable to a shortcode like that. You have to assign a value to a variable: string, number, array, object ... For example:

    {% set username = 'my-name' %}

    or a function that returns the expected value:

    {% set username = mb.my_function_name() %}

    If you are not familiar with this, we offer a customization service with an extra fee. Please contact us here https://metabox.io/contact/ for more details.

    #48758
    EddyPiVEddyPiV
    Participant

    OK, I was hoping / expecting that there would be an easy way to get this.

    Gemini helped me.
    This is the function I added to my functions.php:

    /**
     * Gets a specific query string value from the URL.
     *
     * @param string $param_name The name of the query parameter to retrieve.
     * @return string|null The sanitized value or null if the parameter is not found.
     */
    function get_query_param($param_name) {
        if (isset($_GET[$param_name])) {
            // Use sanitize_text_field to prevent security issues.
            return sanitize_text_field($_GET[$param_name]);
        }
    
        return null;
    }
    

    With mb.get_query_param('username') it's working nicely.

    Perhaps others may benefit of this code, too.

Viewing 3 posts - 1 through 3 (of 3 total)
  • You must be logged in to reply to this topic.