Skip to content

Instantly share code, notes, and snippets.

@dasbairagya
Created August 25, 2018 11:36
Show Gist options
  • Select an option

  • Save dasbairagya/ea64a0141c0504221c157f046f7d47f7 to your computer and use it in GitHub Desktop.

Select an option

Save dasbairagya/ea64a0141c0504221c157f046f7d47f7 to your computer and use it in GitHub Desktop.
Create meta-box to fetch all the cities from the database
<?php
/**
* Register meta box(es).
*/
add_action( 'add_meta_boxes', 'city_register_meta_boxes' );
function city_register_meta_boxes() {
$post_type = get_post_type();
add_meta_box( 'city', 'City', 'city_display_callback', $post_type, "side", "low", 'default');
}
function city_display_callback($post){
wp_nonce_field(basename(__FILE__), "meta-box-nonce");
?>
<div style="overflow: auto;width: 100%; height: 200px;">
<!--- -->
<?php
global $post,$wpdb;
$countries = $wpdb->get_results( "SELECT * FROM wp_city" ); ?>
<ul id="ads_catchecklist">
<?php
$cities = get_post_meta($post->ID,"city", true);
$cities = explode(',',$cities);
foreach($countries as $country)
{
?>
<li style="list-style-type: none;" id="ads_city_<?php echo $city->id; ?>" class="popular-city">
<label class="selectit">
<input name="city[]" type="checkbox" value="<?php echo $country->cityname;?>"
<?php if (in_array( $country->cityname, $cities)){ echo 'checked'; } ?> >
<?php echo $country->cityname; ?>
</label>
</li>
<?php
}
?>
</div>
</ul>
<?php
}
function save_global_notice_meta_box_data( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return; }
if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return;
}
}
else {
if ( ! current_user_can( 'edit_post', $post_id ) ) { return; }
}
$my_data = $_POST['city'];
$my_data = implode(',',$my_data);
update_post_meta( $post_id, 'city', $my_data );
}
add_action( 'save_post', 'save_global_notice_meta_box_data' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment