[英]Adding dropdown selection to WP Custom Post Type
我正在嘗試在自定義帖子類型內的元框中添加“價格范圍”下拉選擇。 會有三種選擇:$ / $$ / $$$
這是我當前用於創建選擇框的內容:
<p>
<label for="price_range" class="prfx-row-title"><?php _e( 'Price Range', 'prfx-textdomain' )?></label><br/>
<select type="text" name="price_range" id="website_url" value="<?php if ( isset ( $prfx_stored_meta['price_range'] ) ) echo $prfx_stored_meta['price_range'][0]; ?>" />
<option>$</option>
<option>$$</option>
<option>$$$</option>
</select>
</p>
這是我當前用於保存選擇框的內容:
if( isset( $_POST[ 'price_range' ] ) ) {
update_post_meta( $post_id, 'price_range', sanitize_text_field( $_POST[ 'price_range' ] ) );
}
選擇框在WP中顯示正常,但是在發布帖子時不會保存我的選擇。
最后,這是我必須在頁面模板中顯示價格范圍的內容:
<!-- DISPLAY PRICE RANGE IF ONE EXISTS -->
<?php if ( get_post_meta($post->ID, 'price_range', true) ) { ?>
<strong>Price Range: </strong>
<?php $meta_value = get_post_meta( get_the_ID(), 'price_range', true ); // Retrieves the stored value from the database
if( !empty( $meta_value ) ) { // Checks and displays the retrieved value
echo $meta_value;
}
?>
<?php } ?>
我尚未對此進行測試,因為我尚未成功保存價格范圍元數據–這項工作有效嗎?
您必須添加保存條目時執行的功能
add_action( 'save_post', 'save_custom_meta' );
function save_custom_meta( ) {
global $post;
if( isset( $_POST[ 'price_range' ] ) ) {
update_post_meta( $post->ID, 'price_range', sanitize_text_field( $_POST[ 'price_range' ] ) );
}
}
我發現哪里出了問題:
<p>
<label for="meta-select" class="prfx-row-title"><?php _e( 'Example Select Input', 'prfx-textdomain' )?></label>
<select name="meta-select" id="meta-select">
<option value="select-one" <?php if ( isset ( $prfx_stored_meta['meta-select'] ) ) selected( $prfx_stored_meta['meta-select'][0], 'select-one' ); ?>><?php _e( 'One', 'prfx-textdomain' )?></option>';
<option value="select-two" <?php if ( isset ( $prfx_stored_meta['meta-select'] ) ) selected( $prfx_stored_meta['meta-select'][0], 'select-two' ); ?>><?php _e( 'Two', 'prfx-textdomain' )?></option>';
</select>
接着:
if( isset( $_POST[ 'price_range' ] ) ) {
update_post_meta( $post_id, 'price_range', $_POST[ 'price_range' ] );
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.