0

使用以下代码,我设法将 Rating 添加到我的自定义 post_type 中,并且我打算根据评分数量显示星号:

function display_game_meta_box( $game ) {
    // Retrieve current name of the Author and Game Rating based on review ID
    $game_Author = esc_html( get_post_meta( $game->ID, 'game_Author', true ) );
    $game_rating = intval( get_post_meta( $game->ID, 'game_rating', true ) );
    ?>
    <table>
        <tr>
            <td style="width: 100%">Game Author</td>
            <td><input type="text" size="80" name="game_Author_name" value="<?php echo $game_Author; ?>" /></td>
        </tr>
        <tr>
            <td style="width: 150px">Game Rating</td>
            <td>
                <select style="width: 100px" name="game_rating">
                <?php
                // Generate all items of drop-down list
                for ( $rating = 5; $rating >= 1; $rating -- ) {
                ?>
                    <option value="<?php echo $rating; ?>" <?php echo selected( $rating, $game_rating ); ?>>
                    <?php echo $rating; ?> stars <?php } ?>
                </select>
            </td>
        </tr>
    </table>
    <?php
}

function my_admin() {
    add_meta_box( 'game_meta_box',
        'Game Details',
        'display_game_meta_box',
        'games', 'normal', 'high'
    );
}
add_action( 'admin_init', 'my_admin' );

在我的模板文件中,我使用它来根据选择的数量查看开始:

<?php
$nb_stars = intval( get_post_meta( get_the_ID(), 'game_rating', true ) );
for ( $star_counter = 1; $star_counter <= 5; $star_counter++ ) {
    if ( $star_counter <= $nb_stars ) {
        echo 'star';
    } else {
        echo 'grey';
    }
}
?>

当我查看页面时,我看到只有 else 语句正在执行。另一件事是,当我在后端选择评分时,它会在更新后一直显示 5 次启动,即使我选择的不是 5。

这是我试图保存元框数据:

function add_movie_review_fields( $game_id, $game ) {
    // Check post type for movie reviews
    if ( $game->post_type == 'games' ) {

        if ( isset( $_POST['game_rating'] ) && $_POST['game_rating'] != '' ) {
            update_post_meta( $game_id, 'games', $_POST['game_rating'] );
        }
    }
}

add_action( 'save_post', 'add_movie_review_fields', 10, 2 );

有什么我可能对评级做错了吗?

4

1 回答 1

1

$nb_stars可能是空的,因为您没有使用正确的密钥保存元数据。

function add_movie_review_fields( $game_id, $game ) {
    // Check post type for movie reviews
    if ( $game->post_type == 'games' ) {

        if ( isset( $_POST['game_rating'] ) && $_POST['game_rating'] != '' ) {
            update_post_meta( $game_id, 'game_rating', $_POST['game_rating'] ); // changed meta key
        }
    }
}

add_action( 'save_post', 'add_movie_review_fields', 10, 2 );

您正在更新的元密钥必须与您正在获取的密钥相匹配。现在$nb_stars应该得到正确的帖子元值。

于 2017-10-31T15:06:10.420 回答