I’m working on a wordpress theme and I’m trying to call the parent category’s name to pull the appropriate page template.
I can get the call function to echo the correct name, but when I try to nest it the function doesn’t run. I saw that I needed to use { } since I was already inside php but it still isn’t working right. Can someone straighten me out?
This gives the correct output:
<?php $category = get_the_category();
$parent = get_cat_name($category[0]->category_parent);
if (!empty($parent)) {
echo '' . $parent;
} else {
echo '' . $category[0]->cat_name;
}
?>
. . . so I created a category_parent.php file with that in it.
This is what I’m trying to nest it in:
<?php get_template_part( ' ' ); ?>
Like this:
1.
<?php get_template_part( '<?php get_template_part( 'category_parent' ); ?>' ); ?>
or this
2.
<?php get_template_part( '{get_template_part( 'category_parent' ); }' ); ?>
Neither one works.
I really don’t know if this is what you want as I did not try to make sense of what you are doing. However, generally speaking, you do this:
Edit:
I looked up what
get_template_part()does in WP, and I think Felix Kling’s answer is what you need. There is a big difference between sending something to the screen and assigning it to a variable.If you include that file, you will see
filenamein the browser. PHP knows nothing about it. (Okay, it could if you made use of output buffering functions, but that’s besides the point…)However if you do something like:
You can now use it in your function:
So what Felix is telling you to do is to put the logic that you currently have into a function. In this example:
Now whatever value
foo()returns will be sent to yourget_template_part().Taking your code:
You could take Felix’s answer and put it into a file called
category_parent.php, and then use it like: