I have a problem to get category id of current post. We are using <?php get_the_category( $id ) ?>
for finding out category of current post.
If a post like ‘demo’ has 2 category like cat1 and cat2. When i open a cat1 page and then go to demo page, i want different layout.. and when i open a cat2 page and then go to demo page, i want to open this demo page with other layout. It can be only done when i will identify.. from which post has called.. but how??
5 comments
Comments are closed.
WordPress has a function
wp_get_referer
, which gets the referring url from the http-header. So, if you go from a category archive to a single post, the name of the category will normally be included in that url. This means you can start yoursingle.php
like this:Depending on your setup this solution may need some tweaking, but the general idea is clear, I hope.
This will return an array of categories, which you can get the id from, like so:
This will be for the first category in the array if there is more than one.
Information on usage can be found in the codex
As mentioned by Gaffen : “changing a posts layout depending on what category is was visited from”
First on the category template page in your theme (i.e. category.php)
get the category id and store it in the WordPress Transient option.
now on single.php or the single post display template page.
get the value from Transient and change display acccordingly
Hope it helps.
In your single.php you could use for example
Better yet, use get_template_part so you don’t just flood your single.php with all kinds of silly code.
First get category ID:
Then get category name:
Then you can decide depending on category name what to do: