Reputation:
I'm here with a little challenge.
I am working for a company where I am building a new website for them. It is being built in Wordpress, btw everthing is going ok.
The website has a news and blog page with posts on there. BUT a in some special cases a news post can also be part of the blog page.
So when that happens we set the 2 categories and put the primary at on of the categories.
When I visit a post with multiple categories I can either go to:
http://example.com/blog/news_post
or
http://example.com/news/news_post
But there are some values on the page that are depended on the name of the category. (I know that is usually not a good idea but I have no other choice in this matter).
When I visit a page I want to get the category that is used to get the field values I need.
So, when going to the news page I would like to get "news" as category name when use a function to get the name.
I have tried multiple things the internet said could do the trick but they either don't work or (what happens most) aren't meant for multi category posts but for getting all the cat of the page.
If you need any more info please let me know.
PS. I would rather not us the url but if that is the best option I will take it. Hope you guys can help
I just managed to do it. Although in the end I still used the url it beats the other options with lots of coding.
I came to this solution after this post by René Schubert
I was just out of options when I saw someone there with an answer I tried it and it worked after a little tweak.
This is the code I have now.
$url = add_query_arg( $wp->query_string, '', home_url( $wp->request ) );
$category = substr($url, strpos($url, "category_name=") + 14);
If you have a better way than please let me know :) I'm all for better ways.
Upvotes: 2
Views: 640
Reputation: 74
You wants to display posts from specific category and get its category name right?
I don't guess how you are getting, but to avoid confusion you can create a separate category template by creating category-news.php file. Refer this. It will display posts only from news category. Here, you will the get the category name to display posts.
<?php
$cat_name=get_category($cat);
echo $cat_name;// diplay cat name
$cat_id=$cat_name->cat_ID;
?>
<div>
<?php query_posts("cat=$cat_id&order=ASC&orderby=date"); ?>
<h4><?php single_cat_title(); ?></h4><hr>
<ul>
<?php while (have_posts()) : the_post();
?>
<li><a href="<?php the_permalink() ?>"><?php the_title(); ?></a>
</li>
<?php endwhile; ?>
</ul>
</div>
Upvotes: 0