Customizer – loading settings/controls/sections/panels based on a id/page id

The most robust way to do this is to do JavaScript-based instantiation of the sections, controls, and settings dynamically in response to the URL being previewed. Since you can navigate around the site in the preview, this will ensure that the post/page-specific sections and controls will be created as you need them when you navigate around the site. This depends on the preview communicating to the controls pane parent window with the URL being previewed (and the queried post ID). Both of these are implemented in the Customize Posts feature plugin, and more details on the message passing from the preview can be seen in #36582.

Nevertheless, since you’re probably looking for a more static PHP solution, the easiest way to ensure both the controls window and the preview window are able to see the same post ID is to not use a custom query var like apageid but rather to use the actual url parameter that is used to tell the customizer which URL to load into the preview. For example when you are on the frontend on a page or singular post and you click Customize, the url param will be the permalink. With that in hand, you can then read from the url param and pass it through url_to_postid() to get the post ID.

There is one other piece needed here and that is to implement dynamic settings. Because a setting is dynamically created in PHP based on whether or not you are on a given page, once you try updating or publishing the changeset you’ll see an error message about the setting not being recognized. By implementing dynamic settings you can tell PHP how to recognize settings based on patterns in their IDs and register them just in time.

Here’s a full working example plugin which adds a section for the initially-loaded loaded post and adds a checkbox control for indicating whether the post content should be made all uppercase or not: https://gist.github.com/westonruter/9e9510c7f57dfbd37eb8c0162b971aa2

You may also want to consider checking out Resetting the Customizer to a Blank Slate.