在侧边栏中显示帖子标题和自定义字段,其中包含小部件中的短代码 - Wordpress

时间:2013-01-06 00:17:09

标签: wordpress plugins wordpress-plugin custom-fields shortcode

我想在HTML /文本小部件中显示包含短代码的某些数据。

我已经在我的functions.php中创建了include php调用:

function event_widget($atts) {

// turn on output buffering to capture script output

ob_start();

// include file (contents will get saved in output buffer)

include("wp-content/themes/mytheme/widgets/event.php");

// save and return the content that has been output

$content = ob_get_clean();
return $content;
}
//register the Shortcode handler
add_shortcode('event', 'event_widget');

如果我只将纯文本添加到event.php,它会将数据传递给小部件,因此调用正确完成,但我不知道如何编写event.php来获取此数据:

// the loop
<?php if (have_posts()) :
        while (have_posts()) : the_post(); ?>

<ul>
<li>
<?php if( get_post_meta($post->ID, "customfield1", true) ): ?>
<?php echo get_post_meta($post->ID, "customfield1", true); ?>
<?php endif; ?>
</li>

<li>
<?php if( get_post_meta($post->ID, "customfield2", true) ): ?>
<?php echo get_post_meta($post->ID, "customfield2", true); ?>
<?php endif; ?>
</li>
</ul>

2 个答案:

答案 0 :(得分:1)

试试这个:

global $post;
echo get_post_meta($post->ID, "customfield1", true);
echo get_post_meta($post->ID, "customfield2", true);

如果你回显一个假的值,它将等于''(无),所以你不必检查它们是否被设置。

答案 1 :(得分:0)

这也很完美:

<?php
global $post;

$args = array('category' => 37, 'post_type' => 'post' ); 
$postslist = get_posts( $args ); 
foreach ($postslist as $post) : setup_postdata($post); 
?> 
<?php if( get_post_meta($post->ID, "customfield1", true) ): ?>
<?php echo get_post_meta($post->ID, "customfield1", true); ?></span>
<?php endif; ?>

此代码有什么“错误”吗?