ACF를 사용하여 사용자 정의 발언에 맵 표시 - WordPress
55470 단어 WordPressgooglemapsacftech
(20221.02) 추가
나는 지도를 표시하는 스크립트 (Googlemap.js-jQuery) 를pure JS로 고쳤다.
발언 설정 사용자 정의
참고 가치가 있는 보도.
[WordPress] 플러그인 없이 사용자 정의 게시 형식에 사용자 정의 필드(텍스트 및 이미지)를 추가하는 방법
register_post_type() - WordPress Developer Resources
functions.php에 기술하다.
function create_post_type() {
register_post_type(
'shops',
array(
'label' => '店舗情報',
'public' => true,
'has_archive' => true,
'menu_position' => 3,
'supports' => array(
'title',
'editor',
'author',
'thumbnail',
'revisions'
),
'show_in_rest' => true
)
);
}
add_action('init', 'create_post_type');
ACF 설정
Advanced Custom Fields 플러그인을 설치하고 활성화합니다.
필드 그룹 편집
필드 유형
Googleマップ
을 선택합니다.투고 유형으로 선택
店舗情報
.ACF에서 Google Maps를 사용하기 위한 준비
참고 가치가 있는 보도.
WordPress 기고 페이지에 Google Map을 표시하는 방법
Field Types > Google Map - ACF Documentation
스타일 설정
style.css
에서 설명합니다..acf-map {
width: 100%;
height: 400px;
}
.acf-map img {
max-width: inherit !important;
}
스크립트 만들기
ACF
의 템플릿을 직접 사용합니다.js/googlemap.js
에서 설명합니다.(function( $ ) {
/**
* initMap
*
* Renders a Google Map onto the selected jQuery element
*
* @date 22/10/19
* @since 5.8.6
*
* @param jQuery $el The jQuery element.
* @return object The map instance.
*/
function initMap( $el ) {
// Find marker elements within map.
var $markers = $el.find('.marker');
// Create gerenic map.
var mapArgs = {
zoom : $el.data('zoom') || 16,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map( $el[0], mapArgs );
// Add markers.
map.markers = [];
$markers.each(function(){
initMarker( $(this), map );
});
// Center map based on markers.
centerMap( map );
// Return map instance.
return map;
}
/**
* initMarker
*
* Creates a marker for the given jQuery element and map.
*
* @date 22/10/19
* @since 5.8.6
*
* @param jQuery $el The jQuery element.
* @param object The map instance.
* @return object The marker instance.
*/
function initMarker( $marker, map ) {
// Get position from marker.
var lat = $marker.data('lat');
var lng = $marker.data('lng');
var latLng = {
lat: parseFloat( lat ),
lng: parseFloat( lng )
};
// Create marker instance.
var marker = new google.maps.Marker({
position : latLng,
map: map
});
// Append to reference for later use.
map.markers.push( marker );
// If marker contains HTML, add it to an infoWindow.
if( $marker.html() ){
// Create info window.
var infowindow = new google.maps.InfoWindow({
content: $marker.html()
});
// Show info window when marker is clicked.
google.maps.event.addListener(marker, 'click', function() {
infowindow.open( map, marker );
});
}
}
/**
* centerMap
*
* Centers the map showing all markers in view.
*
* @date 22/10/19
* @since 5.8.6
*
* @param object The map instance.
* @return void
*/
function centerMap( map ) {
// Create map boundaries from all map markers.
var bounds = new google.maps.LatLngBounds();
map.markers.forEach(function( marker ){
bounds.extend({
lat: marker.position.lat(),
lng: marker.position.lng()
});
});
// Case: Single marker.
if( map.markers.length == 1 ){
map.setCenter( bounds.getCenter() );
// Case: Multiple markers.
} else{
map.fitBounds( bounds );
}
}
// Render maps on page load.
$(document).ready(function(){
$('.acf-map').each(function(){
var map = initMap( $(this) );
});
});
})(jQuery);
Google Maps API 키 획득 및 설정
Get an API Key - Google Maps Platform
위 페이지의 설명에 따라 항목을 선택(또는 제작)하고
Credentials
페이지를 엽니다.Create credentials > API key
에서 키를 생성합니다.Application restrictions
HTTP referrers (web sites)
Website restrictions
example.com
(맵을 설치할 도메인 설정)활성화할 API
스크립트 불러오기
functions.php
에서 설명합니다.function my_api_key() {
return 'MY_API_KEY';
}
function my_acf_google_map_api( $api ) {
$api['key'] = my_api_key();
return $api;
}
add_filter('acf/fields/google_map/api', 'my_acf_google_map_api');
function add_my_scripts() {
wp_enqueue_script(
'googlemap-script',
get_theme_file_uri( '/js/googlemap.js' ),
array( 'jquery' ),
filemtime( get_theme_file_path( '/js/googlemap.js' ) ),
true
);
wp_enqueue_script(
'googlemapsapi',
'//maps.googleapis.com/maps/api/js?key=' . my_api_key(),
array(),
'',
true
);
}
add_action('wp_enqueue_scripts', 'add_my_scripts');
[2020-12-29]햄버거 메뉴(스펀지 초밥 지원)는 움직이지 않을 수도 있다
jQuery(core, migrate)
는 표시WordPress
의 초기 상태를 그대로 사용했다.(다음 추가 섹션 삭제) wp_deregister_script( 'jquery' );
wp_enqueue_script(
'jquery',
'//ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js',
array(),
'3.5.1',
true
);
사용자 정의 투고 템플릿 보이기
파일 구조와 스타일 지정 등은 적당히 다시 읽어 주십시오.
복제
single.php
제작single-shops.php
.복제
template-parts/content.php
제작template-parts/content-shops.php
.template-parts/content-shops.php
(일부) the_content( /*...*/ );
$map = get_field('map');
if( $map ): ?>
<div class="acf-map" data-zoom="16">
<div class="marker" data-lat="<?php echo esc_attr($map['lat']); ?>" data-lng="<?php echo esc_attr($map['lng']); ?>"></div>
</div>
<?php endif;
여러 태그 표시
이 글은 견본의 출처를 공개했다.
Create Multiple Marker Map from ACF Google Map Location Field from a CPT
짧은 코드로 이루어진 것도 있다
Multiple shortcode [themeprefix_multiple_marker]
.post_type
합치면 바로 사용할 수 있습니다.사용자 지정 태그
Customizing a Google Map: Custom Markers - Google Maps Platform
이 문장 편집을 참고하시오
js/googlemap.js
.function initMarker( $marker, map ) {
// Get position from marker.
var lat = $marker.data('lat');
var lng = $marker.data('lng');
var latLng = {
lat: parseFloat( lat ),
lng: parseFloat( lng )
};
const iconBase = "//developers.google.com/maps/documentation/javascript/examples/full/images/";
const icons = {
parking: {
icon: iconBase + "parking_lot_maps.png",
},
library: {
icon: iconBase + "library_maps.png",
},
info: {
icon: iconBase + "info-i_maps.png",
},
};
// Create marker instance.
var marker = new google.maps.Marker({
position : latLng,
icon: icons["parking"].icon,
map: map
});
// Append to reference for later use.
map.markers.push( marker );
// If marker contains HTML, add it to an infoWindow.
if( $marker.html() ){
// Create info window.
var infowindow = new google.maps.InfoWindow({
content: $marker.html()
});
// Show info window when marker is clicked.
google.maps.event.addListener(marker, 'click', function() {
infowindow.open( map, marker );
});
}
}
pure JS로 바꿔보도록 하겠습니다.
js/googlemap.js
function initMap( acfMap ) {
var markers = acfMap.querySelectorAll( '.marker' );
var mapArgs = {
zoom : acfMap.dataset.zoom || 16,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map( acfMap, mapArgs );
// Add markers.
map.markers = [];
markers.forEach( function( mkr, index ){
initMarker( mkr, map );
});
centerMap( map );
return map;
}
function initMarker( mkr, map ) {
var lat = mkr.dataset.lat;
var lng = mkr.dataset.lng;
var latLng = {
lat: parseFloat( lat ),
lng: parseFloat( lng )
};
const iconBase =
"//developers.google.com/maps/documentation/javascript/examples/full/images/";
const icons = {
parking: {
icon: iconBase + "parking_lot_maps.png",
},
library: {
icon: iconBase + "library_maps.png",
},
info: {
icon: iconBase + "info-i_maps.png",
},
};
// Create marker instance.
var marker = new google.maps.Marker({
position : latLng,
icon: icons[ "parking" ].icon,
map: map
});
// Append to reference for later use.
map.markers.push( marker );
// If marker contains HTML, add it to an infoWindow.
if( mkr.innerHTML ){
// Create info window.
var infowindow = new google.maps.InfoWindow({
content: mkr.innerHTML
});
// Show info window when marker is clicked.
google.maps.event.addListener(marker, 'click', function() {
infowindow.open( map, marker );
});
}
}
function centerMap( map ) {
// Create map boundaries from all map markers.
var bounds = new google.maps.LatLngBounds();
map.markers.forEach(function( marker ){
bounds.extend({
lat: marker.position.lat(),
lng: marker.position.lng()
});
});
// Case: Single marker.
if( map.markers.length == 1 ) {
map.setCenter( bounds.getCenter() );
// Case: Multiple markers.
} else {
map.fitBounds( bounds );
}
}
document.addEventListener("DOMContentLoaded", function(event){
var acfMaps = document.querySelectorAll('.acf-map');
acfMaps.forEach( function( acfMap, index ){
var map = initMap( acfMap );
});
});
는 js/googlemap.js
를 통해 상기wp_enqueue_script()
를 읽는다.wp_enqueue_script(
'googlemap-script',
get_theme_file_uri( '/js/googlemap.js' ),
array(),
filemtime( get_theme_file_path( '/js/googlemap.js' ) ),
true
);
함수 참조/wp enqueue script 따라서
js/googlemap.js
는 jQuery
에 의존하지 않고 このスクリプトが依存するスクリプトのハンドルの配列
는 공array(),
으로 바뀌었다.참고 문장 총결산
Reference
이 문제에 관하여(ACF를 사용하여 사용자 정의 발언에 맵 표시 - WordPress), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://zenn.dev/kazweda/articles/daf15e8c70e051텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)