Search code examples
phpwordpressurl-parameters

Show / hide multiple divs on a page based on a url parameter


Looking for a way to display multiple divs, and hide the rest, based on URL parameters.

website.com/?product=11

Display div 1 (Widget 1) if product parameter is 11, 15 or 23

Display div 2 (Widget 2) if product parameter is 33, 35 or 41

Display div 3 (Widget 3) if product parameter is 11, 50 or 60

Notice how "11" would trigger both Div 1 and Div 3 to display.

Other option might be to have an ID for each div that was associated with each product blurb. This would require ability to allow for multiple product parameters in URL:

website.com/?product=widget1,widget3

Purpose of this is for a product recommender form (Ninja Forms + Conditional Logic add-on) to send the user to a "recommendations page" with the URL parameters set based on the form input. This page would include divs that each contain one of our 10 products, but it would only display the products recommended based on the URL parameter output by the form. Open to any suggestions to achieve this.


Solution

  • You can achieve the desired effect with three simple steps.

    1) Read the "product" parameter from your URL :

    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
    
    var product = getParameterByName("product", url);
    

    2) Add a class to the body of your HTML page corresponding with that product :

    document.body.className += ' ' + 'product' + product;
    

    3) Define the CSS of your divs like this :

    .div1 {
       display : none;
    } 
    
    .product11 .div1, .product15 .div1, .product23 .div1 {
       display : block;
    }
    

    DEMO

    function getParameterByName(name, url) {
        if (!url) url = window.location.href;
        name = name.replace(/[\[\]]/g, "\\$&");
        var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
            results = regex.exec(url);
        if (!results) return null;
        if (!results[2]) return '';
        return decodeURIComponent(results[2].replace(/\+/g, " "));
    }
    
    var url = "website.com/?product=11";
    var product = getParameterByName("product", url);
    document.body.className += ' ' + 'product' + product;
    .div1, .div2, .div3 {
       display : none;
    } 
    
    .product11 .div1, .product15 .div1, .product23 .div1,
    .product33 .div2, .product35 .div2, .product41 .div2,
    .product11 .div3, .product50 .div3, .product60 .div3 {
       display : block;
    }
    <div class="div1">
      DIV1
    </div>
    <div class="div2">
      DIV2
    </div>
    <div class="div3">
      DIV3
    </div>

    See also this Fiddle.