在小工具标题上方显示的档案快捷码

时间:2018-01-19 作者:Troy Templeman

我正在使用以下函数创建一个快捷码,用于显示post类型存档的下拉列表:

// Email Archives Shortcode
function email_archives_shortcode() { ?>
    <select name="archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
    <option value=""><?php echo esc_attr( __( \'Select Month\' ) ); ?></option> 
    <?php wp_get_archives( array( \'type\' => \'monthly\', \'format\' => \'option\', \'show_post_count\' => 1, \'post_type\' => \'emails\' ) ); ?>
    </select>
<?php }
add_shortcode(\'email-archives\', \'email_archives_shortcode\');
它工作得很好,除非我在小部件中插入短代码,它显示在小部件标题上方,而不是下方。

1 个回复
最合适的回答,由SO网友:Nathan Johnson 整理而成

使用输出缓冲:

// Email Archives Shortcode
function email_archives_shortcode() { 
    ob_start(); ?>
    <select name="archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
    <option value=""><?php echo esc_attr( __( \'Select Month\' ) ); ?></option> 
    <?php wp_get_archives( array( \'type\' => \'monthly\', \'format\' => \'option\', \'show_post_count\' => 1, \'post_type\' => \'emails\' ) ); ?>
    </select>
    <?php return ob_get_clean();
}
add_shortcode(\'email-archives\', \'email_archives_shortcode\');
或字符串

function email_archives_shortcode() {
  return sprintf(
    \'<select name="archive-dropdown" onchange="document.location.href=this.options[this.selectedIndex].value;">
    <option value="">%1$s</option>
    %2$s
    </select>\',
    esc_attr( __( \'Select Month\' ) ),
    wp_get_archives( array( 
      \'type\' => \'monthly\', 
      \'format\' => \'option\', 
      \'show_post_count\' => 1, 
      \'post_type\' => \'emails\', 
      echo => false, 
    ) )
  );
}
add_shortcode(\'email-archives\', \'email_archives_shortcode\');

结束