How can I add script and PHP code to the section of a theme template of a particular Category that utilizes the built-in block editor in WP?
The same way you were always supposed to in classic themes, nothing has changed!
Use the wp_head
action in combination with the is_category
action.
Note that while classic themes allowed you to modify the head
tag directly via header.php
, block themes don’t, but doing that was never best practice to begin with.
Other notes:
- manually constructing JSON like that is dangerous! It’s much easier to do
<?php echo wp_json_encode( [ 'center' => [ 'lat' => ...], 'zoom' => 14 ) ); ?>
, now the contents of those post meta can’t break your JS and give you syntax errors - that JS should be in a javascript file, not inline, I can see it was included in the header so that you could print out the post meta values, but this should have been done in
data
attributes read off ofdocument.getElementById("gmap")
e.g.<div data-lat="123" data-long="456">
- A simple block named
Ferienflieger/map-block
that printed out lat and long on adiv
using a server side rendered block could be done entirely with PHP and ablock.json
file. This would make inserting blocks easier, optimise your site by allowing WP to only add the JS when the block is used, allow multiple maps if you so wanted, eliminate the need to put anything in the header, and avoid mistakes in the site editor. You could even give it a pretty map icon that shows up in the outliner