【问题标题】:How to save posts to transient?如何将帖子保存到瞬态?
【发布时间】:2020-08-08 21:42:37
【问题描述】:

我的代码:

if (!empty($packs = get_post_meta(get_the_ID(), 'pack', true))):
    if ( false === ( $q = get_transient( 'packs_list' ) ) ) {
        $params = array(
            'post_type' => 'product',
            'posts_per_page' => '7',

            'meta_query' => array(
                array(
                    'key' => 'package_pack',
                    'value' => $packs,
                    'compare' => 'IN'
                )
            )
        );

        $wp_query = new WP_Query($params);

        echo '<div class="products list_">';
            while ($wp_query->have_posts()) : $wp_query->the_post();
                $q = include(rh_locate_template('inc/parts/main.php'));
            endwhile;  

        echo '</div>';

        set_transient( 'packs_list', $q, 1 * HOUR_IN_SECONDS ); 
        wp_reset_postdata();    

    }
endif;

我正在尝试将整个生成的帖子列表保存为瞬态的 html,但不起作用。如何将此循环的 html 输出保存到瞬态?

【问题讨论】:

    标签: wordpress transient


    【解决方案1】:

    虽然我不确定您包含的内容,但您遇到的第一个问题是您无法将输出回显到您想要保存为瞬态的字符串。您必须将 $q 连接成一个包含所有 HTML 输出的长字符串。

    此外,您可能希望使用输出缓冲来获取包含的文件模板的内容。

    if (!empty($packs = get_post_meta(get_the_ID(), 'pack', true))):
        if ( false === ( $q = get_transient( 'packs_list' ) ) ) {
            $params = array(
                'post_type' => 'product',
                'posts_per_page' => '7',
    
                'meta_query' => array(
                    array(
                        'key' => 'package_pack',
                        'value' => $packs,
                        'compare' => 'IN'
                    )
                )
            );
    
            $wp_query = new WP_Query($params);
    
            $q = '<div class="products list_">';
                while ($wp_query->have_posts()) : $wp_query->the_post();
                    ob_start();
                    include(rh_locate_template('inc/parts/main.php'));
                    $q .= ob_get_clean();
                endwhile;  
    
            $q .= '</div>';
    
            set_transient( 'packs_list', $q, 1 * HOUR_IN_SECONDS ); 
            wp_reset_postdata();    
    
        }
    endif;
    

    如果在这个过程中还需要将$q输出到屏幕上,就可以了

    echo $q;
    

    您需要的地方。

    【讨论】:

      猜你喜欢
      • 2015-07-16
      • 2020-09-20
      • 2019-12-07
      • 2013-05-06
      • 2014-12-18
      • 1970-01-01
      • 2022-11-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多