1

How can I tell the customizer to only load certain customizer options based on the post type that is being previewed?

i.e. using:

is_woocommerce
is_shop
is_cart
etc.

When adding customizer option fields, I can check to ensure woocommerce is in the "active_plugins" array so those options are only provided if woocommerce is installed and active, however I need to find a way to only load those fields into the customizer when actually viewing a shop, product, cart, etc. type page.

My only workaround for now is using js/css to show/hide the fields but optimally when navigating among pages in the customizer preview, and since each gets a full refresh anyway, it would be much leaner to dynamically load those options only when necessary based on the post_type being previewed.

1

Customizer Controls can be displayed based on context. With active_callback API introduced in WordPres 4.0, you can control where to show your specific options. Add your customizer options like this with the optional active_callback argument.

$wp_customize->add_control( 'wc_cart_page_option', array(
'label'           => esc_html__( 'Cart Page Options' ),
'section'         => 'wc_cart',
'active_callback' => 'estore_is_cart',
));

Now create a function called 'estore_is_cart' to check if user is previewing the cart page.

function estore_is_cart(){
  if( is_cart() ) {
    return true;
  } else {
    return false;
  }
}

Note: You can also directly pass is_cart function check to 'active_callback' argument.

Check contextual controls section in the blog post: https://make.wordpress.org/core/2014/07/08/customizer-improvements-in-4-0/

  • 2
    Advice: never use the word "new" in technical context. The new of today is the old of tommorow. Instead specify actual release number (it is cool not to know since when, but you can say something like "in version 4.4" instead of new) – Mark Kaplun Apr 8 '16 at 6:40
  • 1
    Thanks @RajeebTheGreat it appears, using your example, you can use in_cart as the callback and shortcut the custom call back altogether but thanks for providing a complete example too. – Philip Ingram Apr 8 '16 at 6:54
  • @MarkKaplun Thanks for your advice. I'll keep that in mind. – Rajeeb Apr 8 '16 at 9:23
  • @PhilipIngram Yeah. That's possible too. Glad I could help. – Rajeeb Apr 8 '16 at 9:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.