This post shows you how to create a shortcode that will display a map with markers of all the child pages of the current page. There is also a shortcode attribute to choose the parent page ID for the map, if you want to show the map elsewhere.
Create our Google Map field
First, lets create our map field.
Make sure you set the metabox ‘Location’ accordingly. I chose to only show the field if the parent page is ‘Data Centers’.
Next, you need to make sure you have child pages of that page. I created a page for each data center location my client had.
Set the location of child pages
On each of those child pages, set a location via the ACF Google Map field.
Now, the fun part… code.
Most of it was taken from the ACF Google Map page.
The contents of my map.js file is:
Register our scripts (don’t enqueue yet)
Next, we need to register our scripts, and only enqueue them when our shortcode runs.
Scribu taught me how to register scripts like a Jedi Knight. Scribu’s method isn’t valid anymore according to Nacin (since WP 3.3). I updated my original code to follow Mike Jolley’s more current/relevant method. Thanks for the heads up Damien Carbery.
This method allows us to set $map_scripts to true in our shortcode, so the scripts are only loaded when the shortcode is used. Love it.
Create our Google Map shortcode
Now, for the best part… let’s build our shortcode to grab our map data.
This handles all the heavy lifting.
Here, we can use our new shortcode: [child_pages_map]
It defaults to showing child pages of the page the shortcode is used on, but we can also put the shortcode anywhere, and specify the parent page we want to use.
Naturally, change the parent ID to the one you want.
That’s it! You can easily tweak this code to grab locations of posts or a CPT, or a specific term in a taxonomy. It’s a great starting point to getting your google map how you want it, and where you want it.
Let me know how it works for you!