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 />';