简体   繁体   English

Wordpress:如何获取特定类别的链接

[英]Wordpress: How to get the link of a particular category

Okay, on my blog I have four categories that the user can click to. 好的,在我的博客上,用户可以单击四个类别。 Management, Industry News, Productivity etc. 管理,行业新闻,生产力等

Here: http://imgur.com/a/wHqqc 此处: http//imgur.com/a/wHqqc

Requirement : I need to find a way using php to link to each category page. 要求 :我需要找到一种使用php链接到每个类别页面的方法。

        <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. 问题:页面css损坏并且无法正常工作,目前,我可以链接到类别的唯一方法是对其进行硬编码。

Ideas? 有想法吗?

You are missing an equal sign ( = ) in the if -condition in your foreach . 你缺少一个等号( =中) if在你的-condition 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. 找到结果后,您也应该break ,以免循环其他类别。

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. 我不确定Wordpress中是否有更好的功能来执行此操作,但是您可以将所有链接保存在关联数组中以一次获取所有链接。

$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'];

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM