available_post_types = array_diff( $post_types, $excluded ); $this->options = get_option( 'address_geocoder_options' ); // Set some default options if none are already set if( ! $this->options ) { $this->options = $this->available_post_types; } // Actions add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) ); add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ) ); add_action( 'save_post', array( $this, 'save_post' ), 10, 2 ); // Settings register_setting( 'address_geocoder_options', 'address_geocoder_options', array( $this, 'validate_options' ) ); } /** * Register the menu item under "Settings" */ function admin_menu() { add_options_page( 'Address Geocoder', 'Address Geocoder', 'manage_options', 'address-geocoder-options', array( $this, 'options_page' ) ); } /** * Enqueue admin scripts */ function admin_enqueue_scripts() { // Load scripts only when necessary if ( $this->is_geocoder_needed() ) { $address_geocoder_options = get_option('address_geocoder_options'); $apikey = $address_geocoder_options['apikey']; if ( ! empty( $apikey ) ) { $mapsapi = '//maps.googleapis.com/maps/api/js?key=' . $apikey; wp_register_script( 'googlemaps', $mapsapi ); wp_register_script( 'marty_geocode_js', plugins_url( '/address-geocoder.js', __FILE__ ) ); wp_enqueue_script( 'googlemaps' ); wp_enqueue_script( 'marty_geocode_js' ); } } } /** * Determine whether the geocoder metabox appears on the current page */ function is_geocoder_needed() { $pagenow = isset( $GLOBALS['pagenow'] ) ? $GLOBALS['pagenow'] : ''; if ( 'post.php' == $pagenow ) { $post_type = get_post_type( $_GET['post'] ); } elseif ( 'post-new.php' == $pagenow ) { $post_type = isset( $_GET['post_type'] ) ? $_GET['post_type'] : 'post'; } if ( !empty( $post_type ) && ! empty( $this->options ) ) { if ( in_array( $post_type, $this->available_post_types ) && 'exclude' != $this->options[ $post_type ] ) { return true; } } return false; } /** * Add the "Geocoder" meta box to the appropriate pages */ function add_meta_boxes( $post_type ) { if ( in_array( $post_type, $this->available_post_types ) && 'exclude' != $this->options[ $post_type ] ) { $current_post_type = get_post_type_object( $post_type ); $metabox_title = empty( $this->options['meta-box-title'] ) ? $current_post_type->labels->singular_name . ' Location' : $this->options['meta-box-title']; add_meta_box( 'martygeocoder', $metabox_title, array( $this, 'meta_box_html' ), $post_type, 'normal', 'high' ); } } /** * Generate the meta box HTML */ function meta_box_html( $object, $box ) { wp_nonce_field( 'save_latlng', 'geocoder_nonce' ); $address_geocoder_options = get_option('address_geocoder_options'); $apikey = $address_geocoder_options['apikey']; if ( $apikey && $apikey != '' ): ?>
A Google Maps API Key is required. Go to Settings.
options['apikey'] ) ? '' : $this->options['apikey']; ?>