2010-11-24 122 views
0

我正在研究一个WordPress主题,我试图调用父类别的名称来提取相应的页面模板。如何在另一个wordpress函数中嵌套wordpress函数?

我可以获得调用函数来回显正确的名称,但是当我尝试嵌套它时,函数不会运行。我看到我需要使用{},因为我已经在php内部,但它仍然不能正常工作。有人能把我拉直吗?

这给正确的输出:

<?php $category = get_the_category(); 
$parent = get_cat_name($category[0]->category_parent); 
if (!empty($parent)) { 
echo '' . $parent; 
} else { 
echo '' . $category[0]->cat_name; 
} 
?> 

。 。 。所以我创建了一个category_parent.php文件。

这就是我想窝它:

<?php get_template_part(' '); ?> 

像这样:

1.

<?php get_template_part('<?php get_template_part('category_parent'); ?>'); ?> 

或本

2.

<?php get_template_part('{get_template_part('category_parent'); }'); ?> 

两者均无效。

回答

1

我真的不知道这是你想要的,因为我没有试图理解你在做什么。然而,一般来说,你这样做:

<?php get_template_part(get_template_part('category_parent')); ?> 

编辑:

我抬头什么get_template_part()确实在WP,我觉得费利克斯·克林的答案是你所需要的。将某些内容发送到屏幕并将其分配给一个变量有很大的区别。

<?php 
    echo 'filename'; 
?> 

如果包含该文件,您将在浏览器中看到filename。 PHP对此一无所知。 (好吧,它可能如果你利用了输出缓冲功能,但是这是除了点...)

但是,如果你这样做:

<?php 
    $x = 'filename'; 
?> 

现在,您可以在您的函数中使用它:

<?php 
    get_template_part($x); 
?> 

那么菲利克斯告诉你要做的就是把你现在的逻辑放到一个函数中。在这个例子中:

<?php 
    function foo() 
    { 
    return 'filename'; 
    } 

    get_template_part(foo()); 
?> 

现在无论价值foo()收益将被发送到您的get_template_part()

以你的代码:

$category = get_the_category(); 
$parent = get_cat_name($category[0]->category_parent); 
if (!empty($parent)) { 
    $name = $parent; 
} else { 
    $name = $category[0]->cat_name; 
} 

get_template_part($name); 

你可以采取Felix的答案,并把它放到一个名为category_parent.php文件,然后使用它像:

require_once 'category_parent.php' 
get_template_part(getName()); 
+0

的“category_parent”部分仍然死在该实例。它试图找到“category_parent.php”,而不是找到“categoryname.php” – Jason 2010-11-24 23:42:01

+0

也许我问的是错误的问题?我希望调用的类别父脚本和答案是其他get_template_part – Jason 2010-11-24 23:46:32

+0

的一部分我已更新我的答案。 – Matthew 2010-11-25 02:18:18

-1

当在PHP字符串中使用变量,将需要使用双引号(“),我认为选项2应该工作然后

1

老实说,我不是很熟悉Wordpress,但在我看来,你可以这样做:

function getName() { 
    $category = get_the_category(); 
    $parent = get_cat_name($category[0]->category_parent); 
    if (!empty($parent)) { 
     return '' . $parent; 
    } else { 
     return '' . $category[0]->cat_name; 
    } 
} 

get_template_part(getName()); 
1

konforce对于语法是正确的,就像konforce一样,我不知道你在做什么。您不需要使用{},因为您不想使用{}动态地命名变量,并且您肯定不需要使用<?php ?>转义为php,因为(1)您已经在php中,并且(2)它将停止解释PHP并假设第二个html命中第一个'?>'。

嵌套函数没有特殊的语法。只是:

get_template_part(get_template_part('category_parent')); 

是语法,但我不知道该函数是什么或做什么,所以我不知道这是否会工作。

要调试,你为什么不试试这个:

$parent = get_template_part('category_parent'); 
echo 'parent: ' . $parent . '<br />'; 
$result = get_template_part($parent); 
echo 'result: ' . $result . '<br />'; 
相关问题