I have a problem checking if a post's category has a parent category, and if so retrieving the first post post of that category. Inside the the_post part:
This is my code:
foreach((get_the_category()) as $childcat) {
$parentcat = $childcat->category_parent;
$parentcat_name = get_cat_name($parentcat);
}
echo "ID of parent category: ".$childcat->category_parent."<br />";
if ($parentcat) { // is there a parent? If so, this is a child post:
$tmp_post = $post; // assign orginal post to tmp_post variable for later use
//link name of parent category to first post in parent category
global $post;
$the_slug = 'my_slug';
$args = array(
'category' => $parentcat,
'numberposts' => 1,
'order' => 'ASC'
);
$my_posts = get_posts($args);
if( $my_posts ) {
$parentpost_link = $my_posts[0]->guid;
}
?>
<h2 class='cat-parent'><a href="<?php echo $parentpost_link ?>"><?php echo $parentcat_name; ?></a></h2>
The strange thing is that this works ok with one or two categories. While on another occation, when in a child category post, it fails to find that there is a parentcategory.
There is a similar problem with identifying a parentcategory's first childcategory, but I suppose the reason is similar to my problems with this one.
What I want is:
- To get the ID of the childcategory, either the one that the current post belongs to, or the only child category of this post. Then I make a slideshow consisting of all the posts in this category
- If the current post is a child-category, I need the ID of that category. The posts should not belong to more than max 2 categories: if the first found is the wrong one, I continue to find the next, which should be the correct one.
- If the post is in a child-category, I also want to find the permalink to the first post in the parentcategory, for navigation. This last task has also been a great difficulty. Strangely, this works perfectly with the first parent-child categories I set up, but not so with the other categories, although the database structure is correct.