1

So this is a zany thing that I'm attempting to do, but what I am trying to achieve is querying out some info in WordPress with categories. If a post comes back with a parent category, then echo that out with the child category with a | seperator. If no parent category then just echo out the category.

Here's what I'm trying so far:

<?php
$categories = get_the_category();
$catName = $categories[0]->name;
$catParent = get_cat_name($categories[0]->category_parent);

        if($catParent) {
            $fullCat = $catParent '|' $catName;
        } else {
            $fullCat = $catName;

echo $fullCat;
?>

I know this is incorrect, but basically, I'm trying to wrap my head around how to accomplish this. I'm not sure how to combine two variables to use one and then add the separator within the two.

Was also wondering if maybe a ternary operator might be better here too? That was more of thought than anything and probably not that necessary to make this work correctly.

3 Answers 3

2

You're wanting to check if $catParent is empty so you can use the empty() function to do that check for you. Quick edit...you need periods (.) in between things you are concatenating.

Link to the docs.

    if(empty($catParent)) {
        $fullCat = $catParent . '|' . $catName;
    } else {
        $fullCat = $catName;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

ahhh, you know what...I had my . flip flopped. That could explain a few things...
Well, it's good to know that I was on the correct path tho. Thanks!
0

You must use '.' to concat.

Example:

$fullCat = $catParent. ' | '. $catName;

Comments

0

You can use . (Concatenation) operator to achieve this. Look at the code below.

<?php
$categories = get_the_category();
$catName = $categories[0]->name;
$catParent = get_cat_name($categories[0]->category_parent);

        if($catParent) {
            $fullCat = $catParent . '|' . $catName;
        } else {
            $fullCat = $catName;

echo $fullCat;
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.