回显短码函数中的自定义字段值

时间:2011-12-13 作者:Dean Elliott

我一定是做错了什么。我想显示自定义字段"pw_featured_note" &;"pw_featured_price"

这是我目前的代码

function featured() {

query_posts(\'post_type=property&posts_per_page=2\');
    if (have_posts()) :
    while (have_posts()) : the_post();
    echo "<div class=\\"singlefeatured group\\">";
    if ( get_post_meta($post->ID, \'pw_featured_property\', true) ) ;
    echo "<a href=\'".get_permalink()."\'>";
    the_post_thumbnail(\'home-thumb\');
    echo "</a>";
    echo "<h2><a href=\'".get_permalink()."\'>".get_the_title()."</a></h2>";
    echo "<p>".get_post_meta($post->ID, \'pw_featured_property\', true)."</p>";
    echo "<p> goodbye </p>";
    echo "</div>";
    endwhile;
    endif; 
    wp_reset_query();

}

add_shortcode(\'featuredproperty\', \'featured\');
任何帮助都将不胜感激。

3 个回复
最合适的回答,由SO网友:Rutwick Gangurde 整理而成

尝试此代码,我已删除query_posts 并已使用get_posts 而是因为我不确定query_posts 将在短代码中工作并使用get_posts 更安全。

function featured()
{
    $posts = get_posts(array(\'post_type\' => \'property\', \'posts_per_page\' => 2));

    if(isset($posts) && !empty($posts))
    {
        foreach($posts as $post)
        {
            echo "<div class=\\"singlefeatured group\\">";

            //I wasn\'t sure what you wanted to get inside this if statement, please correct this
            if ( get_post_meta($post->ID, \'pw_featured_property\', true))
            {
                echo "<a href=\'".get_permalink($post->ID)."\'>";
                    echo get_the_post_thumbnail($post->ID, \'home-thumb\');
                echo "</a>";
            }
            echo "<h2><a href=\'".get_permalink($post->ID)."\'>".get_the_title($post->ID)."</a></h2>";
            echo "<p>".get_post_meta($post->ID, \'pw_featured_property\', true)."</p>";
            echo "<p> goodbye </p>";
            echo "</div>";
        }

    }
}

add_shortcode(\'featuredproperty\', \'featured\');
确保你检查了里面的东西if 声明,我刚把a 标签

SO网友:Daniel

我可以从您的代码中看到,您打开了两个“if”,但只关闭了一个。

SO网友:Alpesh Navadiya

将此代码添加到functions.php:

function foobar_func( $atts ){
     global $post;
     $key=$atts[\'name\'];
     if(empty($key)) return;
    return get_post_meta($post->ID, $key, true);
}
add_shortcode( \'foobar\', \'foobar_func\' );
对于显示,添加[foobar name=custom_field_name] 到您的帖子或页面。

结束

相关推荐

Shortcodes don't work online

我创建了一些已包含到函数中的短代码。php这是短代码。我使用过的php代码:// alert box function alertBox($atts, $content = null) { extract(shortcode_atts(array( \"bgcolor\" => \'#ffffff\' ), $atts)); return \'<div class=\"alertBox\" style=\"bac