问题描述
使用以下代码,我试图将Rating添加到自定义post_type中,并且打算根据评级数显示星号:
Using the following code I managaed to add Rating to my custom post_type and I intend to show star signs according to number of rating:
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' );
在我的模板文件中,根据选择的数量,我使用它来查看起点:
Inside my template file I used this to view the starts according to their amount chosen:
<?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次更新后开始。
When I view the page I see that only the else statement is being executed.Another thing is that when I go select a rating in the backend, it keeps showing me 5 starts after updating even though is not 5 that I chose.
这是我尝试保存的metabox数据:
This is what I tried to save the metabox data:
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 );
我的评分是否有误?
推荐答案
$ nb_stars
可能为空,因为您没有使用正确的密钥保存元数据。
$nb_stars
is probably empty because you're not saving your meta with the proper key.
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
应该获得正确的帖子元值。
The meta key you're updating must match the key you're fetching. Now $nb_stars
should get the proper post meta value.
这篇关于自定义帖子类型评分不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!