Problem: retrieving parent category’s first post

The problem is in the logic. A post may have several terms, not all of which will be child terms. For instance, consider the parent > child term relationships:

a > b > c
d > e
f

And let’s suppose that our post has the terms c,e and f attached to them.

Now the following loop goes through c,e and f in turn. But the $parentcat (and $parentcat_nam) value are over-ridden by each time:

 foreach((get_the_category()) as $childcat) {
            $parentcat = $childcat->category_parent;
            $parentcat_name = get_cat_name($parentcat);
    }

So the $parentcat will be set to the ID of the parent of the last term in get_the_category(). If that were c it would the ID of b. But if it were f, it would 0 and so ‘fails to find a parent category’.

It’s not clear what you want to do in the case of multiple terms with parents. If you want just one parent, then you can break out of the foreach loop.

 foreach((get_the_category()) as $childcat) {
            if( !empty($childcat->category_parent) ){
                $parentcat = $childcat->category_parent;
                $parentcat_name = get_cat_name($parentcat);
                break;
            }
    }
    //$parentcat is set the ID of the parent of one of the terms, 0 if all terms have no parent.

If you wanted to store the IDs of all parents of the post’s terms, you can store them in an array

 $parentcat_arr=array();
 foreach((get_the_category()) as $childcat) {
            if( !empty($childcat->category_parent) ){
                $parentcat_arr[] = $childcat->category_parent;
                break;
            }
    }
  //$parentcat_arr stores array of IDs corresponding to the parents of the post's terms
  //If its empty, then the post has no terms with parents.