两个不同的get_posts()返回相同的帖子

两个不同的get_posts()返回相同的帖子

问题描述:

I am using Wordpress and trying to create some boxes retrieving information from Adanvec Customs Fields on a custom post type.

I have this code:

<div class="col-sm-2 hidden-xs">
    <?php
    $box1 = get_front_page_box("Box 1");
    $style_front = get_box_style($box1->ID, "front");
    echo $box1->ID;
    ?>
    <div id="front-box-1" class="front-box height-low <?php echo $box1->ID; if(has_back_panel($box1->ID)) echo "flip"; ?>">
        <div class="front" style="<?php echo $style_front; ?>"><a href="#">Banana</a></div>
        <?php
        if(has_back_panel($box1->ID)):
            $style_back = get_box_style($box1->ID, "back");
        ?>
        <div class="back" style="<?php echo $style_back; ?>"></div>
        <?php endif; ?>
    </div>
</div>
<div class="col-sm-5 hidden-xs">
    <?php
    $box2 = get_front_page_box("Box 2");
    $style_front = get_box_style($box2->ID, "front");
    echo $box2->ID;
    ?>
    <div id="front-box-2" class="front-box height-low <?php echo $box2->ID; if(has_back_panel($box2->ID)) echo "flip"; ?>">
        <div class="front" style="<?php echo $style_front; ?>"><a href="#">Banana</a></div>
        <?php
        if(has_back_panel($box2->ID)):
            $style_back = get_box_style($box2->ID, "back");
        ?>
        <div class="back" style="<?php echo $style_back; ?>"></div>
        <?php endif; ?>
    </div>
</div>

And these functions:

function get_front_page_box($name) {
    $args = array(
        'post_title'   => $name,
        'post_type'    => 'front-page-box',
        'post_status'  => 'publish'
    );

    $box_array = get_posts($args);

    $box = $box_array ? $box_array[0] : false;

    print_array($box);
    return $box;
}

function get_box_style($id, $side) {
    $style = "";
    if(get_field($side."_panel_background_color", $id)) $style = "background-color:".get_field($side."_panel_background_color", $id).";";

    return $style;
}   

But for some reason both boxes have the same details (both from Box 2). Any idea why these are returning the same info? Both posts ("Box 1" and "Box 2" exist under the front-page-boxcustom post type.

Seems the post_title is not a valid filter. But found out there's a specific function to get posts by title.

get_page_by_title

Used $box1 = get_page_by_title("Box 1", NULL, "front-page-box");

Just for check, if you add another Box named "Box 3", all boxes have results from "Box 2" or "Box 3" ?

A better way to do this would be to use the post ID as the parameter in get_front_page_box().