Skip to content

Commit

Permalink
Merge pull request #10 from alexis-magina/1.1.2
Browse files Browse the repository at this point in the history
1.1.2
  • Loading branch information
alexis-magina authored Mar 24, 2017
2 parents 980116a + 2205a15 commit 169c925
Show file tree
Hide file tree
Showing 3 changed files with 176 additions and 138 deletions.
21 changes: 21 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,20 @@ Options :
- sortable (bool, default = false) : Allow selected posts to be sort
- query_args (array) : setup the ajax search query : pass a wp_query args array.

Filter : (since 1.1.2)
Ajax results can be filtered to customize returned text and posts values.
Use filter "mag_cmb_post_search_ajax_result", for example :
```
function example_callback( $arr ) {
// $arr['data'] : contains post_id
// $arr['guid'] : contains admin edit post url
// $arr['value'] : contains post title
$arr['value'] = 'Custom string '.$arr['value'];
return $arr;
}
add_filter( 'mag_cmb_post_search_ajax_result', 'example_callback' );
```

## Usage - FrontEnd

You can retrieve the meta data using get_post_meta( get_the_ID(), 'your_field_id', true );
Expand All @@ -43,3 +57,10 @@ If field limit == 1, this will return only the single attached post ID.

### 1.1.1-sebask
* Fixed a minor bug which caused the use of an undefined constant.

### 1.1.2
* Fixed issue #2 : no way to delete value for fields with limit = 1
* Added a class exists check (issue #3)
* Added a filter "mag_cmb_post_search_ajax_result" to allow customize ajax results
* Fixed a minor bug of encoding chars in autocomplete results

273 changes: 139 additions & 134 deletions cmb-field-post-search-ajax.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
Plugin URI: https://github.com/alexis-magina/cmb2-field-post-search-ajax
GitHub Plugin URI: https://github.com/alexis-magina/cmb2-field-post-search-ajax
Description: CMB2 field type to attach posts to each others.
Version: 1.1.1-sebask
Version: 1.1.2
Author: Magina
Author URI: http://magina.fr/
License: GPLv2+
Expand All @@ -13,157 +13,162 @@
/**
* Class MAG_CMB2_Field_Post_Search_Ajax
*/
class MAG_CMB2_Field_Post_Search_Ajax {
if( ! class_exists( 'MAG_CMB2_Field_Post_Search_Ajax' ) ) {

class MAG_CMB2_Field_Post_Search_Ajax {

/**
* Current version number
*/
const VERSION = '1.1.1-sebask';
/**
* Current version number
*/
const VERSION = '1.1.2';

/**
* The url which is used to load local resources
*/
protected static $url = '';

/**
* Initialize the plugin by hooking into CMB2
*/
public function __construct() {
add_action( 'cmb2_render_post_search_ajax', array( $this, 'render' ), 10, 5 );
add_action( 'cmb2_sanitize_post_search_ajax', array( $this, 'sanitize' ), 10, 4 );
add_action( 'wp_ajax_cmb_post_search_ajax_get_results', array( $this, 'cmb_post_search_ajax_get_results' ) );
}
/**
* The url which is used to load local resources
*/
protected static $url = '';

/**
* Render field
*/
public function render( $field, $value, $object_id, $object_type, $field_type ) {
$this->setup_admin_scripts();
$field_name = $field->_name();

if($field->args( 'limit' ) > 1){
echo '<ul class="cmb-post-search-ajax-results" id="' . $field_name . '_results">';
if( isset($value) && !empty($value) ){
if( !is_array($value) ){ $value = array($value); }
foreach($value as $val){
$handle = ($field->args( 'sortable' )) ? '<span class="hndl"></span>' : '';
echo '<li>'.$handle.'<input type="hidden" name="'.$field_name.'_results[]" value="'.$val.'"><a href="'.get_edit_post_link($val).'" target="_blank" class="edit-link">'.get_the_title($val).'</a><a class="remover"><span class="dashicons dashicons-no"></span><span class="dashicons dashicons-dismiss"></span></a></li>';
/**
* Initialize the plugin by hooking into CMB2
*/
public function __construct() {
add_action( 'cmb2_render_post_search_ajax', array( $this, 'render' ), 10, 5 );
add_action( 'cmb2_sanitize_post_search_ajax', array( $this, 'sanitize' ), 10, 4 );
add_action( 'wp_ajax_cmb_post_search_ajax_get_results', array( $this, 'cmb_post_search_ajax_get_results' ) );
}

/**
* Render field
*/
public function render( $field, $value, $object_id, $object_type, $field_type ) {
$this->setup_admin_scripts();
$field_name = $field->_name();

if($field->args( 'limit' ) > 1){
echo '<ul class="cmb-post-search-ajax-results" id="' . $field_name . '_results">';
if( isset($value) && !empty($value) ){
if( !is_array($value) ){ $value = array($value); }
foreach($value as $val){
$handle = ($field->args( 'sortable' )) ? '<span class="hndl"></span>' : '';
echo '<li>'.$handle.'<input type="hidden" name="'.$field_name.'_results[]" value="'.$val.'"><a href="'.get_edit_post_link($val).'" target="_blank" class="edit-link">'.get_the_title($val).'</a><a class="remover"><span class="dashicons dashicons-no"></span><span class="dashicons dashicons-dismiss"></span></a></li>';
}
}
echo '</ul>';
$field_value = '';
}
echo '</ul>';
$field_value = '';
}
else{
if(is_array($value)){ $value = $value[0]; }
$field_value = ($value ? get_the_title($value) : '');
else{
if(is_array($value)){ $value = $value[0]; }
$field_value = ($value ? get_the_title($value) : '');
echo $field_type->input( array(
'type' => 'hidden',
'name' => $field_name . '_results',
'value' => $value,
'desc' => false
) );
}

echo $field_type->input( array(
'type' => 'hidden',
'name' => $field_name . '_results',
'value' => $value,
'desc' => false
'type' => 'text',
'name' => $field_name,
'id' => $field_name,
'class' => 'cmb-post-search-ajax',
'value' => $field_value,
'desc' => false,
'data-limit' => $field->args( 'limit' ) ? $field->args( 'limit' ) : '1',
'data-sortable' => $field->args( 'sortable' ) ? $field->args( 'sortable' ) : '0',
'data-queryargs'=> $field->args( 'query_args' ) ? htmlspecialchars( json_encode( $field->args( 'query_args' ) ), ENT_QUOTES, 'UTF-8' ) : ''
) );
}

echo $field_type->input( array(
'type' => 'text',
'name' => $field_name,
'id' => $field_name,
'class' => 'cmb-post-search-ajax',
'value' => $field_value,
'desc' => false,
'data-limit' => $field->args( 'limit' ) ? $field->args( 'limit' ) : '1',
'data-sortable' => $field->args( 'sortable' ) ? $field->args( 'sortable' ) : '0',
'data-queryargs'=> $field->args( 'query_args' ) ? htmlspecialchars( json_encode( $field->args( 'query_args' ) ), ENT_QUOTES, 'UTF-8' ) : ''
) );

echo '<img src="'.admin_url( 'images/spinner.gif' ).'" class="cmb-post-search-ajax-spinner" />';

$field_type->_desc( true, true );

}

/**
* Optionally save the latitude/longitude values into two custom fields
*/
public function sanitize( $override_value, $value, $object_id, $field_args ) {
$fid = $field_args['id'];
if($field_args['render_row_cb'][0]->data_to_save[$fid.'_results']){
$value = $field_args['render_row_cb'][0]->data_to_save[$fid.'_results'];
echo '<img src="'.admin_url( 'images/spinner.gif' ).'" class="cmb-post-search-ajax-spinner" />';

$field_type->_desc( true, true );

}
else{
$value = false;

/**
* Optionally save the latitude/longitude values into two custom fields
*/
public function sanitize( $override_value, $value, $object_id, $field_args ) {
$fid = $field_args['id'];
if($field_args['render_row_cb'][0]->data_to_save[$fid.'_results']){
$value = $field_args['render_row_cb'][0]->data_to_save[$fid.'_results'];
}
else{
$value = false;
}
return $value;
}
return $value;
}

/**
* Defines the url which is used to load local resources. Based on, and uses,
* the CMB2_Utils class from the CMB2 library.
*/
public static function url( $path = '' ) {
if ( self::$url ) {
/**
* Defines the url which is used to load local resources. Based on, and uses,
* the CMB2_Utils class from the CMB2 library.
*/
public static function url( $path = '' ) {
if ( self::$url ) {
return self::$url . $path;
}

/**
* Set the variable cmb2_fpsa_dir
*/
$cmb2_fpsa_dir = trailingslashit( dirname( __FILE__ ) );

/**
* Use CMB2_Utils to gather the url from cmb2_fpsa_dir
*/
$cmb2_fpsa_url = CMB2_Utils::get_url_from_dir( $cmb2_fpsa_dir );

/**
* Filter the CMB2 FPSA location url
*/
self::$url = trailingslashit( apply_filters( 'cmb2_fpsa_url', $cmb2_fpsa_url, self::VERSION ) );

return self::$url . $path;
}

/**
* Set the variable cmb2_fpsa_dir
* Enqueue scripts and styles
*/
$cmb2_fpsa_dir = trailingslashit( dirname( __FILE__ ) );

/**
* Use CMB2_Utils to gather the url from cmb2_fpsa_dir
*/
$cmb2_fpsa_url = CMB2_Utils::get_url_from_dir( $cmb2_fpsa_dir );

public function setup_admin_scripts() {

wp_register_script( 'jquery-autocomplete', self::url( 'js/jquery.autocomplete.min.js' ), array( 'jquery' ), self::VERSION );
wp_register_script( 'mag-post-search-ajax', self::url( 'js/mag-post-search-ajax.js' ), array( 'jquery', 'jquery-autocomplete', 'jquery-ui-sortable' ), self::VERSION );
wp_localize_script( 'mag-post-search-ajax', 'psa', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'mag_cmb_post_search_ajax_get_results' )
) );
wp_enqueue_script( 'mag-post-search-ajax' );
wp_enqueue_style( 'mag-post-search-ajax', self::url( 'css/mag-post-search-ajax.css' ), array(), self::VERSION );

}

/**
* Filter the CMB2 FPSA location url
* Ajax request : get results
*/
self::$url = trailingslashit( apply_filters( 'cmb2_fpsa_url', $cmb2_fpsa_url, self::VERSION ) );

return self::$url . $path;
}

/**
* Enqueue scripts and styles
*/
public function setup_admin_scripts() {

wp_register_script( 'jquery-autocomplete', self::url( 'js/jquery.autocomplete.min.js' ), array( 'jquery' ), self::VERSION );
wp_register_script( 'mag-post-search-ajax', self::url( 'js/mag-post-search-ajax.js' ), array( 'jquery', 'jquery-autocomplete', 'jquery-ui-sortable' ), self::VERSION );
wp_localize_script( 'mag-post-search-ajax', 'psa', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'nonce' => wp_create_nonce( 'mag_cmb_post_search_ajax_get_results' )
) );
wp_enqueue_script( 'mag-post-search-ajax' );
wp_enqueue_style( 'mag-post-search-ajax', self::url( 'css/mag-post-search-ajax.css' ), array(), self::VERSION );

}

/**
* Ajax request : get results
*/
public function cmb_post_search_ajax_get_results() {
$nonce = $_POST['psacheck'];
if ( ! wp_verify_nonce( $nonce, 'mag_cmb_post_search_ajax_get_results' ) ) {
die( json_encode( array( 'error' => __( 'Error : Unauthorized action' ) ) ) );
}
else {
$args = json_decode(stripslashes(htmlspecialchars_decode($_POST['query_args'])), true);
$args['s'] = $_POST['query'];
$results = new WP_Query( $args );
$datas = array();
if ( $results->have_posts() ) :
while ( $results->have_posts() ) : $results->the_post();
$datas[] = array(
'value' => get_the_title(),
'data' => get_the_ID(),
'guid' => get_edit_post_link()
);
endwhile;
endif;
wp_reset_postdata();
die( json_encode( $datas ) );
public function cmb_post_search_ajax_get_results() {
$nonce = $_POST['psacheck'];
if ( ! wp_verify_nonce( $nonce, 'mag_cmb_post_search_ajax_get_results' ) ) {
die( json_encode( array( 'error' => __( 'Error : Unauthorized action' ) ) ) );
}
else {
$args = json_decode(stripslashes(htmlspecialchars_decode($_POST['query_args'])), true);
$args['s'] = $_POST['query'];
$results = new WP_Query( $args );
$datas = array();
if ( $results->have_posts() ) :
while ( $results->have_posts() ) : $results->the_post();
// Define filter "mag_cmb_post_search_ajax_result" to allow customize ajax results.
$datas[] = apply_filters( 'mag_cmb_post_search_ajax_result', array(
'value' => get_the_title(),
'data' => get_the_ID(),
'guid' => get_edit_post_link()
) );
endwhile;
endif;
wp_reset_postdata();
die( json_encode( $datas ) );
}
}

}

}
Expand Down
20 changes: 16 additions & 4 deletions js/mag-post-search-ajax.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@
}
});
}
$(suggestions).each(function(ri, re){
re.value = $('<textarea />').html(re.value).text();
});
return {suggestions: suggestions};
},
params:{
Expand All @@ -45,10 +48,10 @@
var limit = $(this).attr('data-limit');
var sortable = $(this).attr('data-sortable');
if( limit > 1 ){
var handle = (sortable == 1) ? '<span class="hndl"></span>' : '';
var handle = (sortable === 1) ? '<span class="hndl"></span>' : '';
$('#'+lid).append('<li>'+handle+'<input type="hidden" name="'+lid+'[]" value="'+suggestion.data+'"><a href="'+suggestion.guid+'" target="_blank" class="edit-link">'+suggestion.value+'</a><a class="remover"><span class="dashicons dashicons-no"></span><span class="dashicons dashicons-dismiss"></span></a></li>');
$(this).val('');
if( limit == $('#' + lid + ' li').length ){
if( limit === $('#' + lid + ' li').length ){
$(this).prop( 'disabled', 'disabled' );
}
else{
Expand All @@ -61,13 +64,22 @@
}
});

if($(this).attr('data-sortable') == 1){
if($(this).attr('data-sortable') === 1){
$('#'+fid+'_results').sortable({
handle : '.hndl',
placeholder : 'ui-state-highlight',
forcePlaceholderSize : true
});
}

if($(this).attr('data-limit') === 1){
$(this).on('blur', function(){
if($(this).val() === ''){
var lid = $(this).attr('id') + '_results';
$('input[name='+lid+']').val('');
}
});
}

}
);
Expand All @@ -82,4 +94,4 @@
});

});
})(jQuery);
})(jQuery);

0 comments on commit 169c925

Please sign in to comment.