繁体   English   中英

处理要在get_posts()中使用的JSON解码

[英]Processing JSON decode to use in get_posts()

我一直在努力尝试使用自定义字段中的数据来返回帖子。 这是我在functions.php中拥有的函数。 我可以返回我的帖子,除了它们不限于$ json变量中定义的帖子。 我可以解码json并返回数组...但是我似乎无法以将它正确填充在$ dishes_arg中“ posts__in”数组中的方式进行转换。

谁能帮助我确定我做错了什么?

add_action ('woo_loop_before', 'hgf_home_menu');

function hgf_home_menu () {

if (is_home() || is_front_page()) {
    wp_reset_query();

    global $posts;

    $menu_args = array(
        'post_type'=>'single_menu',
        'posts_per_page' => 1,
        'meta_key'    => 'orderby_date', 
        'meta_query' => array(
        'relation' => 'AND',
            array(
            'key' => 'orderby_date', // Order-By Date field is upcoming
             'value' => date("Y-m-d"),  
            'compare' => '>=' 
                        ),
            array(
            'key' => 'orderby_date', // Order-By Date isn't more than two weeks out
            'value' => date("Y-m-d", strtotime( "+2 weeks")),  
            'compare' => '<=' 
                        )
                        ),
                    );
    // Get menu that meets criteria 
    $menus = new WP_Query( $menu_args );

    // Show menu that meets criteria
    if ( $menus->have_posts() ) {
        while ( $menus->have_posts() ) {
        $menus->the_post();
        }
        wp_reset_postdata();

    // Get the menu's product/post listing
        $json = '[{"id":"435"},{"id":"527"},{"id":"563"},{"id":"568"}]';
        $array = json_decode($json);

        $include = array();
        foreach($array as $a) {
        $include[] = $a->ID;
        }

        $args = array(
        'posts_per_page' => -1, 
        'include' => $include);
        $posts = get_posts($args);

        $dish_args = array(
        'post_type' => 'product',
        'post__in' => $posts,               
        );

        // Get dishes in menu listing
        $dishes = get_posts( $dish_args );
        if ($dishes) {
        foreach ($dishes as $dish) {
        }
        }
        } else { // no posts found }
        /* Restore original Post Data */
        wp_reset_postdata();

}       
}

您的jSon属性是ID而不是ID

$include[] = $a->ID;

应该

$include[] = $a->ID;

jSon在哪里/为什么在那里? 这是从别的东西来的吗? 否则,那可能只是一个简单的定界列表,甚至是普通的PHP数组。

我想通了...结果原来我只需要剪掉一堆妨碍代码的代码:$ include = array()... $ args = array()... $ dish_args = array() ... $ dishes = get_posts()。 这是更正的部分:

    $json = '[{"id":"435"},{"id":"527"},{"id":"563"},{"id":"568"}]';
    $dishes = json_decode($json);

    if ($dishes) {
    foreach ($dishes as $dish) {
// Echo titles and permalinks

    }
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM