在一个页面上多次使用WP_QUERY的快捷码

时间:2017-02-25 作者:Ondřej Doněk

我有一个好几天都无法解决的问题-我有一个快捷码,它用我的CPT 贴子,它可以独立工作(在一页/贴子上使用短代码时),但在一页或贴子上使用多次时则不行(没有错误,只打印第一个短代码)

这是我的代码:

if ( ! function_exists( \'odwpdp_add_shortcode_1\' ) ) :
    function odwpdp_add_shortcode_1( $atts, $content = null ) {    
        global $wp;

        // Collect attributes
        $attrs = shortcode_atts( array(
            \'count\'           => 5,
            \'title\'           => __( \'Soubory ke stažení\', ODWPDP_SLUG ),
            \'show_title\'      => 1,
            \'show_pagination\' => 1,
            \'orderby\'         => \'title\',
            \'order\'           => \'ASC\',
            \'enable_sort\'     => 1,
        ), $atts );

        // Sanitize attributes
        $attrs[\'count\'] = (int) $attrs[\'count\'] <= 0 ? -1 : (int) $attrs[\'count\'];
        $attrs[\'show_title\'] = (bool) $attrs[\'show_title\'];
        $attrs[\'show_pagination\'] = (bool) $attrs[\'show_pagination\'];
        $attrs[\'enable_sort\'] = (bool) $attrs[\'enable_sort\'];

        $orderby = filter_input( INPUT_GET, \'odwpdp_orderby\' );
        $order = filter_input( INPUT_GET, \'odwpdp_order\' );

        $attrs[\'orderby\'] = isset( $_GET[\'odwpdp_orderby\'] ) ? $_GET[\'odwpdp_orderby\'] : $attrs[\'orderby\'];
        $attrs[\'order\'] = isset( $_GET[\'odwpdp_order\'] ) ? $_GET[\'odwpdp_order\'] : $attrs[\'order\'];
        $attrs[\'orderby\'] = ! in_array( $attrs[\'orderby\'], array_keys( odwpdp_get_avail_orderby_vals() ) ) ? \'title\' : $attrs[\'orderby\'];
        $attrs[\'order\'] = ! in_array( $attrs[\'order\'], array_keys( odwpdp_get_avail_order_vals() ) ) ? \'DESC\' : $attrs[\'order\'];

        // Prepare query arguments
        $query_args = array();
        $query_args[\'post_type\'] = ODWPDP_CPT;
        $query_args[\'nopaging\']  = ! $attrs[\'show_pagination\'];
        $query_args[\'posts_per_page\'] = $attrs[\'count\'];
        $query_args[\'order\'] = $attrs[\'order\'];

        if ( $attrs[\'orderby\'] == \'title\' ) {
            $query_args[\'orderby\'] = \'title\';
        }
        else {
            $query_args[\'meta_query\'] = array();
            $query_args[\'meta_query\'][] = array(
                \'key\' => \'odwpdp-metabox-1\',
                \'type\' => \'DATE\'
            );
        }

        $odwpdp_paged = (int) filter_input( INPUT_GET, \'odwpdp_paged\', FILTER_VALIDATE_INT );
        $query_args[\'paged\'] = max( 1, $odwpdp_paged );

        // Create query
        $query = new WP_Query( $query_args );

        // Current URL
        $current_url = home_url( add_query_arg( array(), $wp->request ) );

        // Render template
        ob_start( function() {} );
        include_once( ODWPDP_PATH . \'/templates/shortcode-1.phtml\' );
        $html = ob_get_flush();

        return $html;
    }
endif;
add_shortcode( \'soubory_ke_stazeni\', \'odwpdp_add_shortcode_1\' );
这是模板文件(shortcode-1.phtml):

<?php
/**
 * Template file for shortcode "Soubory ke stažení".
 * 
 * @todo Format dates by WordPress inner function!
 * 
 * Used variables (initialized in {@see odwpdp_add_shortcode_1()}).
 *
 * @var array    $attrs
 * @var string   $current_url
 * @var WP_Query $query
 * @var integer  $odwpdp_paged
 */

if ( ! defined( \'ABSPATH\' ) ) {
    exit();
}

$self_url = $current_url . \'?odwpdp_paged=\' . $odwpdp_paged;

/**
 * @internal Prints order arrows in files table head.
 * @param string $url
 * @param array  $atrs
 * @param string $cur
 * @return void
 */
function print_order( $url, $atrs, $cur ) {
?>
<span class="order-icons">
    <?php if ( $atrs[\'orderby\'] == $cur && $atrs[\'order\'] == \'ASC\' ) : ?>
    <span title="<?php _e( \'Seřazeno vzestupně\', ODWPDP_SLUG ); ?>" class="arrow-up used-order"></span>
    <?php  else : ?>
    <a href="<?php echo $url . \'&amp;odwpdp_orderby=\' . $cur . \'&amp;odwpdp_order=ASC\'; ?>" title="<?php _e( \'Seřadit vzestupně\', ODWPDP_SLUG ); ?>" class="arrow-up"></a>
    <?php endif; ?>
    <?php if ( $atrs[\'orderby\'] == $cur && $atrs[\'order\'] == \'DESC\' ) : ?>
    <span title="<?php _e( \'Seřazeno sestupně\', ODWPDP_SLUG ); ?>" class="arrow-down used-order"></span>
    <?php else : ?>
    <a href="<?php echo $url . \'&amp;odwpdp_orderby=\' . $cur . \'&amp;odwpdp_order=DESC\'; ?>" title="<?php _e( \'Seřadit sestupně\', ODWPDP_SLUG ); ?>" class="arrow-down"></a>
    <?php endif; ?>
</span>
<?php
}

?><div class="odwpdp-shortcode-1">
    <?php if ( (bool) $attrs[\'show_title\'] === true && ! empty( $attrs[\'title\'] ) ) : ?>
    <h2 class="odwpdp-shortcode-1-title"><?php echo esc_html( $attrs[\'title\'] ); ?></h2>
    <?php endif;?>
    <table class="files-table">
        <thead>
            <tr>
                <th scope="col">
                    <span class="col-title"><?php _e( \'Název a velikost souboru\', ODWPDP_SLUG ); ?></span>
                    <?php if ( $attrs[\'enable_sort\'] === true ) : ?>
                        <?php print_order( $self_url, $attrs, \'title\' ); ?>
                    <?php endif; ?>
                </th>
                <th scope="col">
                    <span class="col-title"><?php _e( \'Datum vyvěšení\', ODWPDP_SLUG ); ?></span>
                    <?php if ( $attrs[\'enable_sort\'] === true ) : ?>
                        <?php print_order( $self_url, $attrs, \'puton_date\' ); ?>
                    <?php endif; ?>
                </th>
                <th scope="col">
                    <span class="col-title"><?php _e( \'Datum stažení\', ODWPDP_SLUG ); ?></span>
                    <?php if ( $attrs[\'enable_sort\'] === true ) : ?>
                        <?php print_order( $self_url, $attrs, \'putoff_date\' ); ?>
                    <?php endif; ?>
                </th>
            </tr>
        </thead>
        <tbody>
        <?php if( $query->post_count > 0 ) : $posts = $query->get_posts(); ?>
            <?php foreach( $posts as $post ) :
                $puton_date   = get_post_meta( $post->ID, \'odwpdp-metabox-1\', true );
                $putoff_date  = get_post_meta( $post->ID, \'odwpdp-metabox-2\', true );
                $file_info    = odwpdp_get_file_info( $post->ID ); ?>
            <tr>
                <th scope="row">
                    <div class="file-info-cont">
                        <img src="<?php echo $file_info[\'icon_32\']; ?>" class="file-icon">
                        <span class="file-info">
                            <?php printf(
                                \'<a href="%s" class="file-link">%s</a><br><span class="file-size">%s %s</span>\',
                                $file_info[\'url\'],
                                $post->post_title,
                                __( \'Velikost:\', ODWPDP_SLUG ), $file_info[\'size\']
                            ); ?>
                        </span>
                    </div>
                </th>
                <td>
                    <?php if ( ! empty( $puton_date ) ) : ?>
                    <?php echo date( \'j.n.Y\', strtotime( $puton_date ) ); ?>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ( ! empty( $putoff_date ) ) : ?>
                    <?php echo date( \'j.n.Y\', strtotime( $putoff_date ) ); ?>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
        <?php else: ?>
            <tr>
                <td colspan="3" class="no_items-row">
                    <p><?php _e( \'Nebyly nalezeny žádné soubory ke stažení.\', ODWPDP_SLUG ); ?></p>
                </td>
            </tr>
        <?php endif; ?>
        </tbody>
        <?php if ( $attrs[\'show_pagination\'] === true && $query->max_num_pages > 0 ) : ?>
        <tfoot>
            <tr>
                <td>
                    <?php printf( __( \'Celkem zobrazeno %d z %d položek.\', ODWPDP_SLUG ), $query->post_count, $query->found_posts ); ?>
                </td>
                <td colspan="2">
                    <div class="pagination">
                        <?php if ( $odwpdp_paged <= 1 ) : ?>
                        <span title="<?php _e( \'První stránka\', ODWPDP_SLUG ); ?>"><span>&laquo;</span></span>
                        <span title="<?php _e( \'Předchozí stránka\', ODWPDP_SLUG ); ?>"><span>&lsaquo;</span></span>
                        <?php else : ?>
                        <a href="<?php echo $current_url . \'?odwpdp_paged=1\'; ?>" title="<?php _e( \'První stránka\', ODWPDP_SLUG ); ?>"><span>&laquo;</span></a>
                        <a href="<?php echo $current_url . \'?odwpdp_paged=\' . ( $odwpdp_paged - 1 ); ?>" title="<?php _e( \'Předchozí stránka\', ODWPDP_SLUG ); ?>"><span>&lsaquo;</span></a>
                        <?php endif; ?>
                        <?php for ( $i = 1; $i <= $query->max_num_pages; $i++ ) : ?>
                        <?php if ( $odwpdp_paged == $i ) : ?>
                        <span title="<?php _e( \'Aktuální stránka\', ODWPDP_SLUG ); ?>"><span><?php echo $i; ?></span></span>
                        <?php else : ?>
                        <a href="<?php echo $current_url . \'?odwpdp_paged=\' . $i; ?>" title="<?php printf( __( \'Stránka číslo %d\', ODWPDP_SLUG ), $i ); ?>"><span><?php echo $i; ?></span></a>
                        <?php endif; ?>
                        <?php endfor; ?>
                        <?php if ( $odwpdp_paged >= $query->max_num_pages ) : ?>
                        <span title="<?php _e( \'Následující stránka\', ODWPDP_SLUG ); ?>"><span>&rsaquo;</span></span>
                        <span title="<?php _e( \'Poslední stránka\', ODWPDP_SLUG ); ?>"><span>&raquo;</span></span>
                        <?php else : ?>
                        <a href="<?php echo $current_url . \'?odwpdp_paged=\' . ( $odwpdp_paged + 1 ); ?>" title="<?php _e( \'Následující stránka\', ODWPDP_SLUG ); ?>"><span>&rsaquo;</span></a>
                        <a href="<?php echo $current_url . \'?odwpdp_paged=\' . $query->max_num_pages; ?>" title="<?php _e( \'Poslední stránka\', ODWPDP_SLUG ); ?>"><span>&raquo;</span></a>
                        <?php endif; ?>
                    </div>
                </td>
            </tr>
        </tfoot>
        <?php endif; ?>
    </table>
</div>
谢谢你的帮助。完整代码打开GitHub.

1 个回复
最合适的回答,由SO网友:Paul \'Sparrow Hawk\' Biron 整理而成

你问题中的代码太多了,很难理解。此外,您不会说在给定页面/帖子中多次使用该快捷码会发生什么)。

因此,我不能确定,但我认为问题是你需要打电话:

wp_reset_postdata () ;
在shortcode函数的末尾,由于您的shortcode导致Nested Loop.

编辑:使用新解决方案时,问题是:

include_once( ODWPDP_PATH . \'/templates/shortcode-1.phtml\' );
正如PHP func名称所暗示的那样,该文件仅在您的odwpdp_add_shortcode_1() 快捷码函数为调用。。。由于该文件是生成输出的文件,所以除了第一次使用短代码之外,没有其他输出。

因此,您需要执行以下操作:

在中shortcode-1.phtml

包装函数定义print_order() 是一个!function_exists(), 如下所示:

if (!function_exists (\'print_order\')) :
    function
    print_order ($url, $atrs, $cur)
    {
       // existing code for body of print_order()
    }
endif;

<!-- existing markup here -->
在定义odwpdp\\u add\\u shortcode\\u 1()的文件中

include_once( ODWPDP_PATH . \'/templates/shortcode-1.phtml\' );

include ( ODWPDP_PATH . \'/templates/shortcode-1.phtml\' );
你应该是金色的。

希望这有帮助。

相关推荐

Namespaced shortcode?

我正在改造一个旧的WP站点,该站点有许多自定义的短代码,显然由于代码当前的组织方式,这些短代码在性能方面付出了代价。当然,我可以修复优化不好的代码,使用十几个短代码,并且一天就可以完成,但我想知道如何更好地组织它们。根据WordPress\'documentation, 建议将它们放在插件中并在上初始化init. 我们可以通过这样“命名”它们来减少这个钩子中的负载吗?[com.company shortcode attr=\"attr\" prop=\"prop\"] 有人尝试过这样的解决方案吗