Skip to content

Instantly share code, notes, and snippets.

@lmeyer
Created April 9, 2019 14:28
Show Gist options
  • Save lmeyer/1ccc94c306f3cccf267ec3d42fd80899 to your computer and use it in GitHub Desktop.
Save lmeyer/1ccc94c306f3cccf267ec3d42fd80899 to your computer and use it in GitHub Desktop.
VC Autocomplete with multiple ajax sources
<?php
add_filter( 'vc_autocomplete_hdco_featured_featureds_callback', 'get_hdco_autocomplete_featureds', 10, 1 );
function get_hdco_autocomplete_featureds($query) {
$query = sanitize_text_field($query);
$items_array = [];
$args = array(
"post_type" => "post",
"s" => $query
);
$wpquery = new WP_Query($args);
$posts = $wpquery->get_posts();
foreach($posts as $post) :
$items_array[] = array( 'label' => "Article : " . get_the_title($post->ID), 'value' => 'post_' . $post->ID ) ;
endforeach;
$index = algolia_get_index();
$filters = algolia_get_default_filters();
$more = true;
$page = 0;
while($more) {
$res = $index->search($query, [
'filters' => $filters,
'page' => $page
]);
foreach($res['hits'] as $book) :
$items_array[] = array( 'label' => "Ouvrage : " . $book['title'], 'value' => 'book_' . $book['objectID'] ) ;
endforeach;
$page++;
if($res['nbPages'] == $page) {
$more = false;
}
}
return $items_array;
}
add_filter( 'vc_autocomplete_hdco_featured_featureds_render', 'hdco_autocomplete_hdco_featured_featureds_render', 10, 1 );
function hdco_autocomplete_hdco_featured_featureds_render( $query ) {
if(!empty( $query )) {
$index = algolia_get_index();
$value = trim($query['value']);
if(0 === strpos($value, 'book_')) {
$value = substr($value, 5);
$res = $index->getObject($value);
if ( is_array( $res ) ) {
$data = array();
$data['value'] = 'book_' . $res['objectID'];
$data['label'] = 'Ouvrage : ' . $res['title'];
return ! empty( $data ) ? $data : false;
}
} else if(0 === strpos($value, 'post_')) {
$value = substr($value, 5);
$post = get_post($value);
if ( is_object( $post ) ) {
$data = array();
$data['value'] = 'post_' . $post->ID;
$data['label'] = 'Article : ' . get_the_title($post->ID);
return ! empty( $data ) ? $data : false;
}
}
}
return false;
}
<?php
vc_map(
array(
"name" => __("Slider de mise en avant", "hdco"),
"base" => "hdco_featured",
"category" => "Lextenso",
"icon" => "icon-wpb-slideshow",
"params" => array(
array(
'type' => 'autocomplete',
'heading' => __('Ouvrages ou articles', 'hdco'),
'description' => __('Il est possible de sélectionner plusieurs éléments et de les réorganiser.', 'hdco'),
'param_name' => 'featureds',
'settings' => array(
'multiple' => true,
'sortable' => true,
),
),
array(
'type' => 'attach_image',
'heading' => __('Image de fond', 'hdco'),
'param_name' => 'background',
),
array(
'param_name' => 'html',
'type' => 'custom_markup',
'value' => 'Ce bloc nécessite une rangée : Stretch row and content (no paddings)',
),
),
)
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment