Skip to content

Make Templatera Template Select Field Searchable (Autocomplete)

Selecting templates in the WPBakery Page Builder Templatera element can be cumbersome when you have a long list. By turning the template select field into a searchable autocomplete input, you can quickly find and select the template you need, saving time and reducing frustration. The following snippet will turn the default select dropdown into an auto complete field.

// Turn the Templatera template select dropdown into a searchable field.
add_action( 'wp_loaded', function() {
	if ( ! function_exists( 'vc_update_shortcode_param' ) || ! class_exists( 'WPBMap' ) ) {
		return;
	}
	if ( $param = WPBMap::getParam( 'templatera', 'id' ) ) {
		$param['type'] = 'autocomplete';
		$param['settings'] = [
			'multiple' => false,
			'min_length' => 1,
			'groups' => false,
			'unique_values' => true,
			'display_inline' => false,
			'delay' => 0,
			'auto_focus' => true,
		];
		vc_update_shortcode_param( 'templatera', $param );
	}
}, 100 );

// Templatera auto complete callbacks
add_filter(
	'vc_autocomplete_templatera_id_callback',
	function( $search_string ) {
		$query = $search_string;
		$data = [];
		$args = [
			's' => $query,
			'post_type' => 'templatera',
		];
		$args['vc_search_by_title_only'] = true;
		$args['numberposts'] = - 1;
		if ( 0 === strlen( $args['s'] ) ) {
			unset( $args['s'] );
		}
		add_filter( 'posts_search', 'vc_search_by_title_only', 500, 2 );
		$posts = get_posts( $args );
		if ( is_array( $posts ) && ! empty( $posts ) ) {
			foreach ( $posts as $post ) {
				$data[] = [
					'value' => $post->ID,
					'label' => $post->post_title,
					'group' => $post->post_type,
				];
			}
		}

		return $data;
	}
);
add_filter(
	'vc_autocomplete_templatera_id_render',
	function( $value ) {
		$post = get_post( $value['value'] );
		return is_null( $post ) ? false : [
			'label' => $post->post_title,
			'value' => $post->ID,
			'group' => $post->post_type,
		];
	}
);
All PHP snippets should be added via child theme's functions.php file or via a plugin.
We recommend Code Snippets (100% Free) or WPCode (sponsored)
Related Snippets
No related snippets found
Back To Top