Reputation: 1493
Okay, on my blog I have four categories that the user can click to. Management, Industry News, Productivity etc.
Here: https://i.sstatic.net/w9GuR.jpg
Requirement: I need to find a way using php to link to each category page.
<div class="categories-section">
<div class="category">
<?php
$categories = get_categories();
foreach ($categories as $cat) {
if($cat->cat_name = 'MANAGEMENT') {
$category_link = get_category_link($cat->cat_ID);
}
}
?>
<a href="#"><img class="category-icon" src="<?php bloginfo('template_url');?>/img/desktop/images/category-icon-1.jpg">
<h3> INDUSTRY NEWS</h3></a>
</div>
<div class="category">
<a href="<?php echo $category_link; ?>"><img class="category-icon" src="<?php bloginfo('template_url');?>/img/desktop/images/category-icon-2.jpg">
<h3> MANAGEMENT</h3></a>
</div>
<div class="category">
<a href="http://localhost/wordpress/category/PRODUCTIVITY/"><img class="category-icon" src="<?php bloginfo('template_url');?>/img/desktop/images/category-icon-1.jpg">
<h3> PRODUCTIVITY</h3></a>
</div>
<div class="category">
<a href="http://localhost/wordpress/category/PERSONAL-DEVELOPEMENT/"><img class="category-icon" src="<?php bloginfo('template_url');?>/img/desktop/images/category-icon-2.jpg">
<h3> PERSONAL DEVELOPEMENT</h3></a>
</div>
</div>
Problem: The page css is breaking and it's not working, currently the only way I can to link to category is to hard code it.
Ideas?
Upvotes: 0
Views: 162
Reputation: 33186
You are missing an equal sign (=
) in the if
-condition in your foreach
.
if ($cat->cat_name == 'MANAGEMENT') {
$category_link = get_category_link($cat->cat_ID);
break;
}
You should also break
after the result has been found so you don't loop over the other categories.
Update:
I'm not sure if there is a better function in Wordpress to do this, but you could save all links in an associative array to get all links at once.
$wp_categories = get_categories();
$categories = [];
foreach ($wp_categories as $cat)
$categories[$cat->cat_name] = get_category_link($cat->cat_ID);
Now you can do the following:
// Management link:
echo $categories['MANAGEMENT'];
Upvotes: 2