简体   繁体   English

在Wordpress中通过父类别动态设置single.php的样式

[英]Styling single.php dynamically by it's parent category in Wordpress

I'm developing a site using Wordpress which uses Categories for main sections with sub categories. 我正在使用Wordpress开发一个站点,该站点将类别用于带有子类别的主要部分。 Each main section is styled differently so I'm using the parent category slug for each sub category to add an id to the body tag. 每个主要部分的样式都不同,因此我对每个子类别都使用父类别子句,以便向body标签添加ID。 This works fine and allows all sub category pages to be styled the same as their parent category. 这可以正常工作,并允许所有子类别页面的样式都与其父类别相同。

My issue is when you load a single post from a sub category page it uses the single.php template and I need to load the posts parent category slug into the body tag as an id so I can style the post in the same way as it's category page. 我的问题是,当您从子类别页面加载单个帖子时,它会使用single.php模板,并且我需要将帖子的父类别子条目作为id加载到body标签中,以便我可以使用与帖子相同的样式类别页面。

As an example the sort of structure I have is News as a parent category with Press Releases and Latest News as sub cats. 举例来说,我所拥有的结构是新闻作为父类别,新闻稿和最新新闻作为子目录。

Help much appreciated! 帮助非常感谢!

You just need to call get_the_category() to get a structure describing the category. 您只需要调用get_the_category()即可获得描述类别的结构。 One of the members of that structure is the ID of the parent category. 该结构的成员之一是父类别的ID。 You can then call get_the_category() again to get the info you need (like the name) on the parent cateogry. 然后,您可以再次调用get_the_category()来获取父cateogry你需要(好像是这个名字)的信息。 See: 看到:

http://codex.wordpress.org/Function_Reference/get_the_category http://codex.wordpress.org/Function_Reference/get_the_category

Thanks for the quick answers. 感谢您的快速解答。

Eric, I used your idea and expanded upon it to get what I need. 埃里克(Eric),我使用了您的想法,并在此基础上进行了扩展,以获取所需的信息。 Might not be the cleanest way to do it but it works! 可能不是最干净的方法,但是它可行!

I added this function: 我添加了此功能:

function get_cat_slug($cat_id) {
    $cat_id = (int) $cat_id;
    $category = &get_category($cat_id);
    return $category->slug;
}

Then used this code to get the parent Id and echo out the slug: 然后使用此代码获取父ID并回显该段代码:

$getcategory = get_the_category() ;
$parentcatid = $getcategory[0]->category_parent;
echo get_cat_slug($parentcatid);

That's done the trick. 达到目的了。

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

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