How can I add script and PHP code to the <head>
section of a theme template of a particular Category that utilizes the built-in block editor in WP?
Here's an example:
<script type="text/javascript">
let map;
function initMap() {
map = new google.maps.Map(document.getElementById("gmap"), {
<?php
$lat= get_post_meta($post->ID, 'gmap-latitude', true);
$lon= get_post_meta($post->ID, 'gmap-longitude', true);
echo 'center: {lat: '.$lat.', lng: '.$lon.'},';?>
zoom: 14,
});
}
window.initMap = initMap;
</script>
Some background info:
I'm trying to transition the theme of my website using old-school template files (ex., single-map.php) to the new twenty twenty-three WP theme using its built-in block editor.
And one of my website's Category ("Map") has 3.000+ pages, all of which with the above code in their <head>
section (and another script in the <body>
). Then, in the post editing screen of each page, I entered latitude and longitude values using Custom Fields.
Besides a solution for my initial problem, if there's a better way of doing this, I'm eager to know!
<head>
section. Just tested it with the Twenty Twenty-Three theme and it works with that.center
JSON,data
attributes can do this already, and you can already use WP APIs to attach data to objects without having to manually print it out like that so this approach is already not ideal in a classic theme . Take a look at developer.wordpress.org/reference/functions/… and also consider usingdata
attributes as right now this approach makes multiple maps impossible. Similarly in non-block themes you're meant to use filters to put stuff in the head