2011-11-14 59 views
1

自定义字段的值,我用这个代码functions.php文件:获得从具体职位

function get_custom_field_value($szKey, $bPrint = false) { 
global $post; 
$szValue = get_post_meta($post->ID, $szKey, true); 
if ($bPrint == false) return $szValue; else echo $szValue;} 

,这一次在我的HTML引用它,当我需要得到一个自定义字段:

<?php if (function_exists('get_custom_field_value')){ 
    get_custom_field_value('now_location', true);} ?> 

但是,只有当我在帖子中使用它时才起作用,因为它需要当前帖子的字段值。

如何从一个确切的帖子中获得字段值(或多个)? 我想它与帖子的ID有关,但我不知道要更改/添加到代码中。

+0

你在用什么?什么是$ post,cus它与$ _POST – Niels

+0

不一样$ $ post是如何工作的? –

+0

我刚刚从[这里]复制了代码(http://www.wprecipes.com/how-to-easily-get-the-value-of-a-custom-field)。 正如我所说的,当我在帖子中使用它时它工作正常,但当我想要从特定帖子获取特定字段值并在单独的'div'中显示值时,它不会正常工作。 – rlesko

回答

1

As @janw建议将帖子ID作为参数传递以获取特定帖子的自定义字段是很好的做法。

function get_custom_field_value($szKey,$postId, $bPrint = false) { 
$szValue = get_post_meta($postId, $szKey, true); 
if ($bPrint == false) return $szValue; else echo $szValue;} 
+0

我是否将其作为新功能添加到现有的功能中? 如果是,在HTML中引用该函数时应该使用哪些PHP代码?我只需添加我的帖子ID就可以了:'... get_custom_field_value($ szKey,$ 23,$ bPrint = false)...' – rlesko

+0

如果帖子ID是23,并且您要在我的评论中使用该函数,这里是代码get_custom_field_value($ szKey,23,$ bPrint = false); –

+0

工程很好,稍作修改。我必须在引用函数时写'get_custom_field_value($ szKey,23,true);'。 为什么会有'$ bPrint = false'? 现在我在帖子里引用这个函数时有问题,它根本没有显示它。 – rlesko