0

We need to style a single page differently depending on what user journey you take. Currently we have event posts listed in WP, they are either under the "get involved > events" page or "urban innovation center > attend an event" some events are listed in both. If you come from "get involved > events" we need the single event page to have a light background and if you come from "urban innovation center > attend an event" we need the single event page to have a dark background. We dont want to have to duplicate the events in WP.

https://futurecities.catapult.org.uk/events/

  • @jdm2112 not really sure where to start with this? – bwalkernz Aug 24 '16 at 19:53
1

You could listen for the $_SERVER['HTTP_REFERER'] and add a class to the body depending on that referer

add_filter( 'body_class','wpse_body_classes' );
function wpse_body_classes( $classes ) { 

  if ( is_page( 'event' ) ){ // event is the page slug of the page we wish to add the class for


    if( wp_get_referer() == '/url/of/get_involved' ){

      $classes[] = 'my-light-bg';

    }

    elseif( wp_get_referer() == '/url/of/urban_innovation_center' ){

      $classes[] = 'my-dark-bg';

    }

    else {

      $classes[] = 'my-default-bg';

    }    

  }

  return $classes;

}

EDIT

Updated the code to

  • make use of wp_get_referer
  • check if we are on the event page so the filter only runs on that page
  • add a default body class to that page if no referrer is set
  • 1
    WP has a function for this: wp_get_referer. – vancoder Aug 24 '16 at 19:58
  • Also you'd need a default - in case someone is coming from a search engine or a bookmark. – vancoder Aug 24 '16 at 19:59
  • @vancoder good comment, I wasn't aware of that function. updated the answer to reflect this – bynicolas Aug 24 '16 at 20:08
  • A problem you might have is that, as no useful referer will be available when someone visits from Google, your page will have to "guess" what colour to show in that case. – vancoder Aug 24 '16 at 20:16
  • I think my update takes care of that now. I think a switch/case could also be used here and set a default case to take care of that issue. – bynicolas Aug 24 '16 at 20:26
1

Keeping in mind the issues with checking referers, I'd probably approach this differently.

I'd append a parameter to the permalink using add_query_arg. The param added would be different for each referring page - eg, get involved > events might add class=my-light-bg, whereas urban innovation center > attend an event might add class=my-dark-bg.

Your event page itself could then retrieve that parameter by looking at $_GET[ 'class' ].

The advantage here is that, even when coming from a bookmark or search engine result, the correct style will be presented.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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