WP基于高德地图的门店功能,增加获取门店json函数,支持短代码

前端怎么做自己研究吧,我自己是上网扒了个并且整了个三级联动的,高德地图api需要看文档,按文档自己申请填上,一共需要3个

<?php
/* 增加门店发布类型 */
//增加门店类型文章
add_action( 'init', 'create_store_type' );
function create_store_type() {
    $labels = array(
        'name'                  => _x( '门店', 'post type general name', 'textdomain' ),
        'singular_name'         => _x( '门店', 'post type singular name', 'textdomain' ),
        'menu_name'             => _x( '门店', 'admin menu', 'textdomain' ),
        'name_admin_bar'        => _x( '门店', 'add new on admin bar', 'textdomain' ),
        'add_new'               => _x( '添加门店', 'store', 'textdomain' ),
        'add_new_item'          => __( '添加门店', 'textdomain' ),
        'new_item'              => __( '新门店', 'textdomain' ),
        'edit_item'             => __( '编辑门店', 'textdomain' ),
        'view_item'             => __( '查看门店', 'textdomain' ),
        'all_items'             => __( '所有门店', 'textdomain' ),
        'search_items'          => __( '搜索门店', 'textdomain' ),
        'parent_item_colon'     => __( '父级门店:', 'textdomain' ),
        'not_found'             => __( '未找到门店', 'textdomain' ),
        'not_found_in_trash'    => __( '回收站中未找到门店', 'textdomain' ),
        'featured_image'        => _x( '门店封面图', 'Overrides the “Featured Image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'set_featured_image'    => _x( '设置门店封面图', 'Overrides the “Set featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'remove_featured_image' => _x( '移除门店封面图', 'Overrides the “Remove featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'use_featured_image'    => _x( '使用门店封面图', 'Overrides the “Use as featured image” phrase for this post type. Added in 4.3', 'textdomain' ),
        'archives'              => _x( '门店存档', 'The post type archive label used in nav menus. Default “Post Archives”. Added in 4.4', 'textdomain' ),
        'insert_into_item'      => _x( '插入门店', 'Overrides the “Insert into post”/”Insert into page” phrase (used when inserting media into a post). Added in 4.4', 'textdomain' ),
        'uploaded_to_this_item' => _x( '上传到此门店', 'Overrides the “Uploaded to this post”/”Uploaded to this page” phrase (used when viewing media attached to a post). Added in 4.4', 'textdomain' ),
        'filter_items_list'     => _x( '筛选门店列表', 'Screen reader text for the filter links heading on the post type listing screen. Default “Filter posts list”/”Filter pages list”. Added in 4.4', 'textdomain' ),
        'items_list_navigation' => _x( '门店列表导航', 'Screen reader text for the pagination heading on the post type listing screen. Default “Posts list navigation”/”Pages list navigation”. Added in 4.4', 'textdomain' ),
        'items_list'            => _x( '门店列表', 'Screen reader text for the items list heading on the post type listing screen. Default “Posts list”/”Pages list”. Added in 4.4', 'textdomain' ),
    );

    $args = array(
        'label'                 => __( '门店', 'textdomain' ),
        'description'           => __( '这是一个门店类型', 'textdomain' ),
        'labels'                => $labels,
        'supports'              => array( 'title', 'editor', 'excerpt', 'author', 'thumbnail', 'comments', 'revisions' ), // 添加 'revisions' 支持
        'taxonomies'            => array( 'store_type', 'post_tag' ), // 添加支持的分类法
        'hierarchical'          => false,
        'public'                => true,
        'show_ui'               => true,
        'show_in_menu'          => true,
        'menu_position'         => 5,
        'show_in_admin_bar'     => true,
        'show_in_nav_menus'     => true,
        'can_export'            => true,
        'has_archive'           => true,
        'exclude_from_search'   => false,
        'publicly_queryable'    => true,
        'show_in_rest'          => true,
        'rest_base'             => 'store',
        'rest_controller_class' => 'WP_REST_Posts_Controller', // 指定 REST API 控制器类名
    );

    register_post_type( 'store', $args );
}


// // 门店自定义分类,如果需要可开启,开启后需要增加single-archive-store.php
// function store_taxonomies() {
//     register_taxonomy(
//         'store_category',    //自定义分类名
//         'store',                //自定义类型
//         array(
//             'labels' => array(
//                 'name' => '门店分类',
//                 'add_new_item' => '添加门店分类',
//                 'new_item_name' => '新门店分类',
//             ),
//             'show_ui' => true,          //后台显示
//             'show_tagcloud' => false,   //是否显示标签云
//             'hierarchical' => true,     //控制分类法格式
//         )
//     );
// }
// add_action( 'init', 'store_taxonomies', 0 );


// 指定门店页面模板,子主题根目录下single-store的模板;
// 列表页模板为single-archive,暂时没有,如有需要可增加
function store_template( $template_path ) {
    if ( get_post_type() == 'store' ) {
        if ( is_single() ) {
            $theme_file = locate_template( array ( 'single-store.php' ) );
            $template_path = $theme_file;
        } elseif ( is_archive() ) {
            $theme_file = locate_template( array ( 'page-stores.php' ) );
            $template_path = $theme_file;
        }
    }
    return $template_path;
}
add_filter( 'template_include', 'store_template', 1 );


function mymetabox_get_meta( $value ) {
    global $post;
 
    $field = get_post_meta( $post->ID, $value, true );
    if ( ! empty( $field ) ) {
        return is_array( $field ) ? stripslashes_deep( $field ) : stripslashes( wp_kses_decode_entities( $field ) );
    } else {
        return false;
    }
}

//门店自定义字段metabox
/**
 * Generated by the WordPress Meta Box Generator
 * https://jeremyhixon.com/tool/wordpress-meta-box-generator/
 * 
 * Retrieving the values:
 * Label1 = get_post_meta( get_the_ID(), 'Keylabel1', true )
 * Label2 = get_post_meta( get_the_ID(), 'Keylabel2', true )
 * Label3 = get_post_meta( get_the_ID(), 'Keylabel3', true )
 */
//门店自定义字段metabox
/**
 * Generated by the WordPress Meta Box Generator
 * https://jeremyhixon.com/tool/wordpress-meta-box-generator/
 * 
 * Retrieving the values:
 * Label1 = get_post_meta( get_the_ID(), 'Keylabel1', true )
 * Label2 = get_post_meta( get_the_ID(), 'Keylabel2', true )
 * Label3 = get_post_meta( get_the_ID(), 'Keylabel3', true )
 */
class storeMetabox {
	private $config = '{"title":"门店信息","description":"","prefix":"Key","domain":"Text","class_name":"Text","post-type":["store"],"context":"normal","priority":"high","cpt":"Custom","fields":[{"type":"text","label":"门店地址(必填)","default":"请输入门店地址","id":"store_address", "required": true},{"type":"text","label":"门店经纬度(必填)","default":"请输入门店经纬度","id":"store_coordinate", "required": true},{"type":"text","label":"门店电话","default":"123123123","id":"store_phone", "required":false}]}';

	public function __construct() {
		$this->config = json_decode( $this->config, true );
		$this->process_cpts();
		add_action( 'add_meta_boxes', [ $this, 'add_meta_boxes' ] );
		add_action( 'admin_head', [ $this, 'admin_head' ] );
		add_action( 'save_post', [ $this, 'save_post' ] );
		add_action( 'rest_api_init', [ $this, 'register_rest_field' ] ); // 注册 REST API 的字段
	}

	public function process_cpts() {
		if ( !empty( $this->config['cpt'] ) ) {
			if ( empty( $this->config['post-type'] ) ) {
				$this->config['post-type'] = [];
			}
			$parts = explode( ',', $this->config['cpt'] );
			$parts = array_map( 'trim', $parts );
			$this->config['post-type'] = array_merge( $this->config['post-type'], $parts );
		}
	}

	public function add_meta_boxes() {
		foreach ( $this->config['post-type'] as $screen ) {
			add_meta_box(
				sanitize_title( $this->config['title'] ),
				$this->config['title'],
				[ $this, 'add_meta_box_callback' ],
				$screen,
				$this->config['context'],
				$this->config['priority']
			);
		}
	}

	public function admin_head() {
		global $typenow;
		if ( in_array( $typenow, $this->config['post-type'] ) ) {
			?>config['fields'] as $field ) {
			switch ( $field['type'] ) {
				default:
					if ( isset( $_POST[ $field['id'] ] ) ) {
						$sanitized = sanitize_text_field( $_POST[ $field['id'] ] );
						update_post_meta( $post_id, $field['id'], $sanitized );
					}
			}
		}
	}

	public function add_meta_box_callback() {
		$tips='点击使用高德地图获取经纬度 
zke:需要填写完整地址,包含【省/自治区、市/区】,便于前端地图正确显示,如:北京市海淀区xxxxxxxxx
'; echo '
' . $this->config['description'] . '
'; echo ''.$tips.''; $this->fields_table(); } private function fields_table() { ?>config['fields'] as $field ) { ?>%s', $field['id'], $field['label'] ); } } private function field( $field ) { switch ( $field['type'] ) { default: $this->input( $field ); } } private function input( $field ) { printf( '', isset( $field['class'] ) ? $field['class'] : 'form-control', $field['id'], $field['id'], isset( $field['pattern'] ) ? "pattern='{$field['pattern']}'" : '', $field['type'], $this->value( $field ), isset( $field['required'] ) && $field['required'] ? 'required="required"' : '' // 根据字段的 required 设置动态添加 required 属性 ); } private function value( $field ) { global $post; if ( metadata_exists( 'post', $post->ID, $field['id'] ) ) { $value = get_post_meta( $post->ID, $field['id'], true ); } else if ( isset( $field['default'] ) ) { $value = $field['default']; } else { return ''; } return str_replace( '\u0027', "'", $value ); } public function register_rest_field() { foreach ( $this->config['post-type'] as $post_type ) { register_rest_field( $post_type, 'store_info', [ 'get_callback' => [ $this, 'get_store_info' ], 'update_callback' => [ $this, 'update_store_info' ], 'schema' => null, ] ); } } public function get_store_info( $post ) { $store_info = [ 'store_address' => get_post_meta( $post['id'], 'store_address', true ), 'store_coordinate' => get_post_meta( $post['id'], 'store_coordinate', true ), 'store_phone' => get_post_meta( $post['id'], 'store_phone', true ), ]; return $store_info; } public function update_store_info( $store_info, $post ) { if ( isset( $store_info['store_address'] ) ) { update_post_meta( $post->ID, 'store_address', sanitize_text_field( $store_info['store_address'] ) ); } if ( isset( $store_info['store_coordinate'] ) ) { update_post_meta( $post->ID, 'store_coordinate', sanitize_text_field( $store_info['store_coordinate'] ) ); } if ( isset( $store_info['store_phone'] ) ) { update_post_meta( $post->ID, 'store_phone', sanitize_text_field( $store_info['store_phone'] ) ); } return $this->get_store_info( $post ); } } new storeMetabox; /* === 门店地图功能 === Contributors: zke Tags: map, zkemaps, Donate link: http://www.zkcoi.com Requires at least: 1.6 Tested up to: 4.3.1 Stable tag: trunk License: GPL 3.0 License URI: http://www.gnu.org/licenses/gpl-3.0.html 基于高德地图的地图功能,在single-store.php使用的短代码调用 == Description == 基于高德地图的WordPress插件,利用短代码可以在任何你想插入地图的地方插入有标记的地图。支持自定义尺寸大小,自定义其他描述 = 使用 = `vii Or `[zkemaps lon='126.633286' lat='45.747425' address='北航学院路校区' info='这是一个很好的大学']` Or `[zkemaps address='北航学院路校区' info='这是一个很好的大学']` Or `[zkemaps lon='126.633286' lat='45.747425' info='这是一个很好的大学']` Or `[zkemaps address='北航学院路校区']` = 参数说明 = with `id`, you can customize style for map with `w` and `h`, you can customize weight and height for map */ if(!function_exists('zkemaps_init')) { add_action('init', 'wp_zkemaps_init'); } function wp_zkemaps_init() { add_shortcode('zkemaps', 'wp_zkemaps_content_init'); } function wp_zkemaps_content_init($atts, $content = null) { extract(shortcode_atts(array( 'id' => '', 'w'=>'', 'h'=>'', 'lon'=>'', 'lat'=>'', 'address'=>'', 'info' => '', ) ,$atts)); $store_info=get_post_custom(get_the_ID()); $store_name = get_post($id)->post_title; $store_address=get_post_custom_values('store_address')[0]; $store_coordinate=get_post_custom_values('store_coordinate')[0]; $store_phone=get_post_custom_values('store_phone')[0]; $lnglat = explode(",",$store_coordinate); $store_lng = number_format($lnglat[0],6); $store_lat = number_format($lnglat[1],6); $id = $id ? $id : 'wp_zkemaps'; $w = $w ? $w : '100vh'; $h = $h ? $h : '70vh'; $lon = $lon ? $lon : $store_lng; $lat = $lat ? $lat : $store_lat; $address = $address ? $address : $store_address; $info = $info ? $info : $store_name; $str1 = '<div id="amap-link" style="padding:15px;font-size: 14px; font-weight: 300; margin-bottom: 4px; background-color: rgb(240, 240, 240); border-radius: 12px; color: rgb(29, 29, 31); display: inline-block; padding: 4px 9px;"><a href="https://uri.amap.com/marker?position='.$lon.','.$lat.'&name=zke渠道门店-'.$store_name.'&src=www.zkcoi.com&callnative=1" target="_blank" rel="nofollow">点击查看路线</a></div><div class="wp_zkemaps" ><div id="'.$id.'"><div id="container"></div></div></div>'; $str2 = '<link rel="stylesheet" href="https://cache.amap.com/lbs/static/main1119.css"/><script src="https://webapi.amap.com/maps?v=1.3&key=【这里填写高德地图的密钥】"></script><script type="text/javascript" src="https://cache.amap.com/lbs/static/addToolbar.js"></script><style type="text/css">.amap-container{width:'.$w.'!important;height:'.$h.'!important;position:relative!important;}.amap-icon img {margin: 0 !important;}.amap-marker-label {border: 2px solid #f5f5f5;background-color: #f5f5f5;padding-right: 20px;}</style><script>var map = new AMap.Map("container", {resizeEnable: true,center: ['; $str3 = '],zoom: 13});var marker = new AMap.Marker({position: map.getCenter()});marker.setMap(map);marker.setTitle("'; $str4 = '");marker.setLabel({offset: new AMap.Pixel(20, 20),content: "'; $str5 = '"});</script>'; if (($lon && $lat) || $address) { $output = $str1; $output .= $str2; if($lon && $lat) { $output .= $lon.','.$lat; if (! $address) { $tep = file_get_contents("http://restapi.amap.com/v3/geocode/regeo?output=json&location=".$lon.",".$lat."&key=【这里填写高德地图的密钥】&radius=1000"); $tep = json_decode($tep); $address = $tep->regeocode->formatted_address; } } else if ($address){ $tep = file_get_contents("http://restapi.amap.com/v3/geocode/geo?address=".$address."&output=json&key=【这里填写高德地图的密钥】"); $tep = json_decode($tep); $tep = $tep->geocodes[0]->location; $output .= $tep; } $output .= $str3; $output .= $address; $output .= $str4; if ($info) { $output .= $info; } else { $output .= $address; } $output .= $str5; return $output; echo $output; } } //获取门店jason数据,在page-stores.php调用 function get_store(){ $args = array( 'post_type'=>'store','posts_per_page' => 99); //创建数组参数, $loop = new WP_Query( $args ); //获取所有门店 while ( $loop->have_posts() ) ://循环输出所有门店 $loop->the_post(); $store_address = get_post_custom_values('store_address')[0]; $store_phone = "<br>电话:".get_post_custom_values('store_phone')[0]; $store_info = get_address($store_address); $link = "<a target=\"_blank\" href=" . get_permalink() . ">" . get_the_title() . '</a>'; $store_info['store_title'] = $link . '<br><p class="storeinfo">地址:' . $store_address . $store_phone . '</p>' ; $map_info = json_encode( $store_info ,320); print_r($map_info); echo ","; endwhile; }

 

本文作者:𝙕𝙆𝘾𝙊𝙄

文章名称:WP基于高德地图的门店功能,增加获取门店json函数,支持短代码

文章链接:https://www.zkcoi.com/365up/program/2342.html

本站资源仅供个人学习交流,请于下载后24小时内删除,不允许用于商业用途,否则法律问题自行承担。

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
𝙕𝙆𝘾𝙊𝙄𝙕𝙆𝘾𝙊𝙄
上一篇 2022年10月19日
下一篇 2022年10月19日

相关推荐

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注

私聊博主

立即联系
一般有空就回复

qrcode_web

微信扫码联系我

分享本页
返回顶部