Loading CPT if Module is Enabled

I am trying to load a CPT if module is enabled in the Page Builder settings, and then disable if the module is disabled.

This is the php I am working with

$enabled_modules = FLBuilderModel::get_enabled_modules();

 if (in_array('bb-sw-masonry', $enabled_modules)) {
 }

I have tried wrapping the entire CPT within the in_array, as well as just the add_action for the register_post_type function.

$enabled_modules = FLBuilderModel::get_enabled_modules();

 if (in_array('bb-sw-masonry', $enabled_modules)) {
      add_action( 'init', 'sw_gallery_post_type' );
 }

I have tried including the php file within the in_array

$enabled_modules = FLBuilderModel::get_enabled_modules();

 if (in_array('bb-sw-masonry', $enabled_modules)) {
      include( dirname( __FILE__ ) . '/modules/bb-sw-masonry-module/includes/bb-sw-gallery-cpt.php');
 }

But whenever I do, the CPT is not registered.

However if I do this I get the expected results when module is loaded or not

<?php 
$enabled_modules = FLBuilderModel::get_enabled_modules();

 if (in_array('bb-sw-masonry', $enabled_modules)) {
      echo 'Loaded';
 } else {
      echo 'Not Loaded';
}

Is your code wrapped in a function and hooked on init? It may be executing after init which would be too late to register a CPT. Try something like this:

add_action('init', 'conditionally_load_gallery_cpt');
function conditionally_load_gallery_cpt() {
	$enabled_modules = FLBuilderModel::get_enabled_modules();
 	if (in_array('bb-sw-masonry', $enabled_modules)) {
		register_post_type( ... );
 	}
}

Hey Jon,

I think Josh is correct about wrapping your code in an action. Give that a shot and let me know how it goes.

Thanks for chiming in, Josh!

Justin