【问题标题】:Show post title and custom fields in sidebar with shortcode in widget - Wordpress在小部件中使用简码在侧边栏中显示帖子标题和自定义字段 - Wordpress
【发布时间】:2013-01-06 00:17:08
【问题描述】:

我想用简码在 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>

【问题讨论】:

    标签: plugins wordpress custom-fields shortcode


    【解决方案1】:

    试试这个:

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

    如果您回显一个为 false 的值,它将等于 ''(无),因此您不必检查它们是否已设置。

    【讨论】:

      【解决方案2】:

      而且这也很完美:

      <?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; ?>
      

      这段代码有什么“错误”吗?

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-10-30
        • 2020-11-11
        • 1970-01-01
        • 2014-02-07
        • 1970-01-01
        • 1970-01-01
        • 2019-07-03
        • 2019-04-18
        相关资源
        最近更新 更多