I've impletend this code that creates a custom metabox to choose a related article for a specific post type. It creates a list of 1000 articles to choose from.
Since I have a lot of articles I would like to replace the list with the same search form wp uses in nav-menus edit page (wp-admin/nav-menus.php), where I can search trough pages and click on a checkbox to select the page to link.
Here is my code:
// Add the Meta Box
function add_related_article_meta_box() {
add_meta_box(
'related_article_meta_box', // $id
'Related Article', // $title
'show_related_article_meta_box', // $callback
'wpdmpro', // $post type
'side', // $position
'high'); // $priority
}
add_action('add_meta_boxes', 'add_related_article_meta_box');
// Array field
$prefix = 'related_article_';
$custom_meta_fields = array(
array(
'label' => 'Post List',
'desc' => 'Select your article',
'id' => $prefix.'post_id',
'type' => 'post_list',
'post_type' => array('post')
)
);
// Callback
function show_related_article_meta_box() {
global $custom_meta_fields, $post;
// nonce verify
echo '<input type="hidden" name="related_article_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';
// form table start and loop
echo '<table class="form-table">';
foreach ($custom_meta_fields as $field) {
// get filed value if exists
$meta = get_post_meta($post->ID, $field['id'], true);
// table tr start
echo '<tr>
<td>';
switch($field['type']) {
// Post List
case 'post_list':
$items = get_posts( array (
'post_type' => $field['post_type'],
'posts_per_page' => 1000
));
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">
<option value="">Select</option>'; // Post Select
foreach($items as $item) {
$custom_post_date = date_i18n( 'd-m-Y', strtotime($item->post_date));
echo '<option value="'.$item->ID.'"',$meta == $item->ID ? ' selected="selected"' : '','>' .$custom_post_date. '- ' .$item->post_title.'</option>';
} // end foreach
echo '</select><br /><span class="description">'.$field['desc'].'</span>';
break;
} //end switch
echo '</td></tr>';
} // end foreach
echo '</table>'; // end tabella
}
// Save data
function save_custom_meta($post_id) {
global $custom_meta_fields;
// verifica nonce
if (!wp_verify_nonce($_POST['related_article_meta_box_nonce'], basename(__FILE__)))
return $post_id;
// check autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)
return $post_id;
// check permessions
if ('page' == $_POST['post_type']) {
if (!current_user_can('edit_page', $post_id))
return $post_id;
} elseif (!current_user_can('edit_post', $post_id)) {
return $post_id;
}
// loop into fields and save
foreach ($custom_meta_fields as $field) {
$old = get_post_meta($post_id, $field['id'], true);
$new = $_POST[$field['id']];
if ($new && $new != $old) {
update_post_meta($post_id, $field['id'], $new);
} elseif ('' == $new && $old) {
delete_post_meta($post_id, $field['id'], $old);
}
} // end foreach
// save taxonomies
$post = get_post($post_id);
$category = $_POST['category'];
wp_set_object_terms( $post_id, $category, 'category' );
}
add_action('save_post', 'save_custom_meta');
Any hint on how to edit callback function (and save data function) in order to get this kind of result would be appreciated.
Thank you for your help.
Related
Good afternoon devs, I developed a favorite system using Wordpress and php, it works as follows, clicking on the add favorites icon I send an ajax request to php with the favorite id and the user id logged in. php processes this by saving in user_meta the information with number of favorite users and in the logged user an array with the ids of the favorites. Anyway, the question is, the system is working, but whenever I develop something I keep wondering if there is a way to improve the code, if there is a way to do it in a better way, I will leave my code here.
All this for learning ok?
HTML
<div class="stats -favorites">
<a class="icon -click <?php echo is_favorite(get_current_user_id(), $user_ID) ? 'fa' : 'far' ?> fa-heart" data-js="favorite" data-favorite="<?php echo $user_ID; ?>" data-user="<?php echo get_current_user_id(); ?>"></a>
<span class="label" data-js="favorite_label">
<?php echo get_favorites_num( $user_ID ); ?>
</span>
<span class="value">favoritos</span>
</div>
JS
function setFavorite(userid, favoriteid) {
var favorite_field = $('[data-js="favorite"]');
var favorite_label = $('[data-js="favorite_label"]');
$.ajax({
url : appmeninas_ajax_params.ajaxurl,
data : {
'action' : 'setfavorite',
'userid' : userid,
'favoriteid' : favoriteid,
},
dataType : 'json',
type : 'POST',
cache : false,
beforeSend : function( xhr ) {
favorite_field.removeClass('far fa fa-heart').addClass('fas fa-circle-notch fa-spin');
},
success : function( data ) {
var icon = (data.is_favorite) ? 'fa fa-heart' : 'far fa-heart';
favorite_field.removeClass('fas fa-circle-notch fa-spin');
favorite_field.addClass(icon);
favorite_label.html('');
favorite_label.append(data.favorites_num);
}
});
};
$('[data-js=favorite]').click(function() {
var favoriteid = $(this).data('favorite');
var userid = $(this).data('user');
setFavorite(userid, favoriteid);
});
PHP
function setfavorite() {
$userid = $_POST['userid'];
$favoriteid = $_POST['favoriteid'];
// user require favorite
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
$favorites_num = get_field( 'favorites', 'user_' .$favoriteid );
if ( !$favorites_list ) {
$favorites_list = [];
}
// profile favorite
if ( in_array( $favoriteid, $favorites_list ) ) {
$favorites_num--;
$tmp = array_search( $userid, $favorites_list );
array_splice( $favorites_list, $tmp, 1 );
$is_favorite = false;
} else {
$favorites_num++;
$favorites_list[] = $favoriteid;
$is_favorite = true;
}
// set favorite counter
update_user_meta( $favoriteid, 'favorites', $favorites_num );
// set favorite list
update_user_meta( $userid, 'favorites_list', $favorites_list );
echo json_encode( array(
'favorites_num' => $favorites_num,
'favorites_list' => $favorites_list,
'is_favorite' => $is_favorite,
) );
die();
}
function is_favorite($userid, $favoriteid) {
$favorites_list = get_field( 'favorites_list', 'user_' .$userid );
return in_array( $favoriteid, $favorites_list );
}
function get_favorites_num( $userid ) {
if ( get_field( 'favorites', 'user_' .$userid ) ) {
return get_field( 'favorites', 'user_' .$userid );
} else {
return '0';
}
}
add_action('wp_ajax_setfavorite', 'setfavorite');
add_action('wp_ajax_nopriv_setfavorite', 'setfavorite');
i maybe will implement a same function in the next 2 months. i allready started researching plugins but as your question states, it does not seems to be very hard.
I try to come back then but first i need a frontend profile page where i can list the favorites.
The first impression looks good so far but first i would give attention to the $_POST array and sanitize and maybe validate the values because sometimes not only your ajax will call.
if ( isset($_POST['userid']) && isset($_POST['favoriteid']) ) { // Both $_POST values exist
$userid = filter_var($_POST['userid'], FILTER_SANITIZE_NUMBER_INT);
$favoriteid = filter_var($_POST['favoriteid'], FILTER_SANITIZE_NUMBER_INT);
if ( filter_var($userid, FILTER_VALIDATE_INT) && filter_var($favoriteid, FILTER_VALIDATE_INT) ) {
// $_POST was save, both values are Integers
}
}
The second one is related to get_field which is a function provided by the ACF Plugin. therefor when deactivating it or it gets replaced with JCF, it may cause errors.
You can avoid this by using if ( function_exists('get_field') ) {. Then your code only stops working when ACF gets deactivated.
Otherwise it seems not neccessary to use the ACF function and you can use the WP native function get_user_meta instead:
function is_favorite($userid, $favoriteid){
$favorites_list = get_user_meta($userid, 'favorites_list', true);
// check the new output instead of get_field
return in_array( $favoriteid, $favorites_list );
}
and also all calls to get_field('favorites', 'user_' .$favoriteid) seem to be wrong then. The ACF Docs say the the second parameter of get_field ist a post ID so i don't know what 'user_' means then. I would call:
function get_favorites_num($favoriteid){
return get_user_meta($favoriteid, 'favorites', true) || 0;
}
i now have my own favorite system ready where users can favorite posts from a specific post_type
HTML
<?php while ( have_posts() ) : the_post() ?>
<?php
$customPostsMeta = get_post_custom();
$favorite_class = 'favorite-me disabled';
$fav_count = isset($customPostsMeta['_favorites']) ? intval($customPostsMeta['_favorites'][0]) : 0;
$fav_count_text = $fav_count > 0 ? '(' . $fav_count . ')' : '';
$fav_count = ' <span class="fav-count clearfix">' . $fav_count_text . '</span>';
$favorite_title = '';
if ( is_user_logged_in() ) {
$user = wp_get_current_user();
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
$fav_key = array_search($post_id, $favorites);
$is_favorite = ( $fav_key !== false );
if ( $is_favorite ) {
$favorite_class .= ' is-favorite';
$favorite_title = ' title="' . get_the_title() . ' ' . __('favorisieren', 'myTheme') . '"';
} else {
$favorite_title = ' title="' . get_the_title() . ' ' . __('nicht mehr favorisieren', 'myTheme') . '"';
}
}
?>
<a class="<?php echo $favorite_class; ?>" href="#post-<?php the_ID() ?>"<?php echo $favorite_title; ?>><?php echo __('Favorit', 'myTheme')?><?php echo $fav_count; ?></a>
<?php endwhile; ?>
JS
// i use a small self written JS module frame where this is included as module
// favorite.setup() is fired imediatly, favorite.ready() fires on document ready
// you can see a full version here: https://dev.alphabetisierung.at/wp-content/themes/sandbox_2017/js/actions.js
// line 732
/**
* Favorites ajax system
* =====================
* https://stackoverflow.com/questions/60468237
*/
favorite: {
options: {
selectors: {
link: '.favorite-me',
fav_count: '.fav-count'
},
classNames: {
disabled: 'disabled',
is_favorite: 'is-favorite',
}
},
events: function(){
var options = this.options,
selectors = options.selectors,
classNames = options.classNames,
info = this.info;
this.$favorites.on('click', function(event){
var post_id = this.hash.replace('#post-', ''),
$favorite_link = $(this).addClass(classNames.disabled),
$fav_count = $favorite_link.children(selectors.fav_count),
$favorite = $.ajax({
url: myTheme.page.urls.ajax,
type: 'post',
data: {
action: info.name, // derived from the module name "favorite"
verify: myTheme.page.verify, // https://developer.wordpress.org/reference/functions/check_ajax_referer/
post_id: post_id
// user_id of user who takes the action is not necessary
}
});
$favorite.done(function(data){
var fav_count = data.hasOwnProperty('fav_count') ? parseInt(data.fav_count) : 0,
fav_count_text = '',
is_favorite = data.hasOwnProperty('is_favorite') ? data.is_favorite : false;
if ( fav_count > 0 ) {
fav_count_text = '(' + fav_count + ')';
}
$fav_count.html(fav_count_text);
if ( is_favorite && !$favorite_link.is('.' + classNames.is_favorite) ) {
$favorite_link.addClass(classNames.is_favorite);
} else {
$favorite_link.removeClass(classNames.is_favorite);
}
$favorite_link.removeClass(classNames.disabled);
});
event.preventDefault();
});
},
ready: function ready(){
var selectors = this.options.selectors,
classNames = this.options.classNames;
this.$favorites = $(selectors.link).removeClass(classNames.disabled);
this.events();
},
setup: function setup(){
var setup = myTheme.info.is_user_logged_in && myTheme.info.post_type === 'my_custom_post_type';
return setup; // only for my post_type
}
PHP
add_action('wp_enqueue_scripts', 'myTheme_enqueue_scripts');
add_action('wp_ajax_favorite', 'myTheme_set_favorite');
// wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
function myTheme_enqueue_scripts(){
$data = array(
'id' => get_the_ID(),
'urls' => array(
'ajax' => admin_url('admin-ajax.php'),
'template' => get_stylesheet_directory_uri(),
),
'verify' => wp_create_nonce('myThemeOrAction_ajax_call'), // used for check_ajax_referer()
// ...
'info' => array(
// ...
'is_user_logged_in' => is_user_logged_in(),
'post_type' => get_post_type(),
),
);
// ...
wp_localize_script('actions', 'myTheme_data', $data );
}
function myTheme_set_favorite(){
check_ajax_referer('myThemeOrAction_ajax_call', 'verify');
if ( isset($_POST['post_id']) ) {
$user = wp_get_current_user(); // here we get the user ID of the current user
$post_id = filter_var($_POST['post_id'], FILTER_SANITIZE_NUMBER_INT);
$post = get_post($post_id);
// $fav_id = filter_var($_POST['fav_id'], FILTER_SANITIZE_NUMBER_INT);
// $fav_user = get_userdata($fav_id); // WP_User
$is_favorite = false;
if ( $post instanceof WP_Post ) { // post ID is valid
// for user favorites it would be
// if ( $fav_user instanceof WP_User ) {
$fav_count = intval(get_post_meta($post->ID, '_favorites', true));
$favorites = get_user_meta($user->ID, '_favorite_posts', true);
if ( !filter_var($fav_count, FILTER_VALIDATE_INT) ) {
$fav_count = 0;
}
if ( !is_array($favorites) || empty($favorites) ) {
$favorites = array();
}
$fav_key = array_search($post->ID, $favorites);
if ( $fav_key !== false ) { // is favorite, remove it
$fav_count--;
unset($favorites[$fav_key]);
} else { // is no favorite, add it
$fav_count++;
$favorites[] = $post->ID;
$is_favorite = true;
}
// set favorite counter
update_post_meta($post->ID, '_favorites', $fav_count);
// set favorite list
update_user_meta($user->ID, '_favorite_posts', $favorites);
// Output
$json = array(
'fav_count' => $fav_count,
'favorites' => $favorites,
'error' => false,
'is_favorite' => $is_favorite,
);
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'Invalid Post ID');
}
} else {
$json = array('is_favorite' => $is_favorite, 'error' => true, 'message' => 'No post_id Post ID sent');
}
// wp_send_json sets the http header and ends the request
wp_send_json($json);
}
this are the things i noticed on the way:
verify referer with wp_create_nonce() and check_ajax_referer()
check JSON result data keys for existance with data.hasOwnProperty('key') to avoid possible JS errors
check valid WP_User or WP_Post object
current users ID with is not necessary to send with POST
wp_ajax_nopriv_{action} is not necessary when feature is only for logged in users
use wp_send_json() for ending the response
kind regards
tom
I have an ajax form that filters posts based on the category.
Setup:
HTML form
PHP function to echo ouput
jQuery ajax request to load php
function
Question: How can I parse a value to the php function ($test, see below) from within the jQuery ajax function?
Form - Outputs html select field and button to filter posts
<form action="<?php echo site_url() ?>/wp-admin/admin-ajax.php" method="POST" id="filter">
<?php
if( $terms = get_terms( 'category', 'orderby=name' ) ) : // to make it simple I use default categories
echo '<select name="categoryfilter"><option>Select category...</option>';
foreach ( $terms as $term ) :
echo '<option value="' . $term->term_id . '">' . $term->name . '</option>'; // ID of the category as the value of an option
endforeach;
echo '</select>';
endif;
?>
<button>Apply filter</button>
<input type="hidden" name="action" value="myfilter">
</form>
<div id="response"></div>
PHP function - Outputs result on button click in HTML form
function misha_filter_function($test){
// Do something with $test, but how to parse it with jQuery into this php function?
$args = array(
'orderby' => 'date', // we will sort posts by date
'order' => $_POST['date'] // ASC или DESC
);
// for taxonomies / categories
if( isset( $_POST['categoryfilter'] ) )
$args['tax_query'] = array(
array(
'taxonomy' => 'category',
'field' => 'id',
'terms' => $_POST['categoryfilter']
)
);
$query = new WP_Query( $args );
if( $query->have_posts() ) :
while( $query->have_posts() ): $query->the_post();
echo '<h2>' . $query->post->post_title . '</h2>';
endwhile;
wp_reset_postdata();
else :
echo 'No posts found';
endif;
die();
}
add_action('wp_ajax_myfilter', 'misha_filter_function');
add_action('wp_ajax_nopriv_myfilter', 'misha_filter_function');
jQuery - Question: how to parse php value $test to the above php function?
jQuery(function($){
$('#filter').submit(function(){
var filter = $('#filter');
$.ajax({
url:filter.attr('action'),
data:filter.serialize(), // form data
type:filter.attr('method'), // POST
beforeSend:function(xhr){
filter.find('button').text('Processing...'); // changing the button label
},
success:function(data){
filter.find('button').text('Apply filter'); // changing the button label back
$('#response').html(data); // insert data
}
});
return false;
});
});
You serialize data so accesed by:
parse_str($_POST['data'], $inputValues); //$inputValues will be array with your form fields
I have currently implemented a live search (search as you type) function on text fields. The flow is something like this.
Call a .js file inside the page.
Set the id of the text field to "client-search".
Inside the .js file it is currently listening for on key up events of the "client-search" text field.
If the on key up event is fired, the .js file calls a PHP file that searches the database and returns the output as a list item in an unordered list underneath the "client-search" text field.
This setup currently works but how do implement it in multiple fields inside a single page, since it works using "id" and obviously I can't have multiple IDs in a single page.
HTML:
<div class="input-group">
<input type="text" id="client-search" class="form-control" placeholder="Search for manager...">
<ul class="livesearch" id="client-result" onclick="clickResult()"></ul>
</div>
JS
/* JS File */
// Start Ready
$j(document).ready(function() {
// Icon Click Focus
$j('div.icon').click(function(){
$j('input#client-search').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#client-search').val();
$j('b#search-string').text(query_value);
if(query_value !== ''){
$j.ajax({
type: "POST",
url: "clientsearch.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#client-result").html(html);
}
});
}return false;
}
$j("input#client-search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$j("ul#client-result").fadeOut();
}else{
$j("ul#client-result").fadeIn();
$j(this).data('timer', setTimeout(search, 100));
};
});
});
PHP:
<?php
$serverName = "(local)";
$connectionInfo = array( "Database"=>"CMS");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn ) {
} else {
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$html = '';
$html .= '<li value="myLi" class="myLi">';
$html .= '<small>nameString</small>';
$html .= '<small></small>';
$html .= '</li>';
$search_string = $_POST['query'];
//$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$sql = "SELECT TOP 10 ClientName FROM Client WHERE ClientName LIKE '%" . $search_string . "%'";
$params = array($search_string);
$stmt = sqlsrv_query( $conn, $sql);
while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) {
$results_array[] = $row;
}
if (isset($results_array)) {
foreach ($results_array as $result) {
$display_function = $result['ClientName'];
$display_name = $result['ClientName'];
$output = str_replace('nameString', $display_name, $html);
//$output = str_replace('functionString', $display_function, $output);
echo($output);
}
}else{
$output = str_replace('nameString', '<b>No Results Found.</b>', $html);
$output = str_replace('functionString', 'Sorry :(', $output);
echo($output);
}
}
?>
I want to show a message displaying the result of each iteration of a for loop in php.
I have tried several methods using jquery, ajax etc but they doesn't seem to fit my needs or either i am not getting to work around with them.
What my script does?
It scans a website, grab some links, then visits each link one by one and grab an image from each page and finally send it to my wordpress including its title and image.
What's the problem?
The problem is that as there can be several links (more than 200), so even though my scripts displays message regarding the success but it shows the messages after the whole loop is finished executing.
What I want to do?
Now, what i want to do that during each iteration the message should be shown on the browser rather than waiting for the loop to complete i.e. during 1st iteration (Posted Successfully) then during 2nd (Not Posted) and so on...
Here is the code:
<?php
$category = array();
for ($i = 0; $i < count($result); $i++)
{
set_time_limit(30);
// Check if post already exists
global $wpdb;
$query = $wpdb->prepare('SELECT ID FROM ' . $wpdb->posts .
' WHERE post_name = %s',sanitize_title_with_dashes($result[$i]->title));
$cID = $wpdb->get_var($query);
if (!empty($cID))
{
echo $result[$i]->title .
" <font style='color:#FF0000; font-weight:bold;'>Already Exists.</font><br />";
} else
{
$inner_html = file_get_html($result[$i]->href);
$inner_result_image = $inner_html->find('meta[property=og:image]',1);
$inner_result_cats = $inner_html->find('a[rel=category tag]');
$title = $result[$i]->title;
$body = "<a href='$inner_result_image->content'><img src='$inner_result_image->content' /></a>";
// Automatically Create new Category if it doesn't exist.
foreach ($inner_result_cats as $cats)
{
if (!($cats->innertext == "Jobs"))
{
array_push($category,$cats->innertext);
$count = 0;
// For Cities
if (search_city($cats->innertext))
{
wp_insert_term($cats->innertext,'category',array(
'description' => '',
'slug' => '',
'parent' => '14')); // Jobs by City
} else
{
$count += 1;
}
// For Qualification
if (search_qualification($cats->innertext))
{
wp_insert_term($cats->innertext,'category',array(
'description' => '',
'slug' => '',
'parent' => '51')); // Jobs by Qualification
} else
{
$count += 1;
}
// International Jobs
if (check_international(parse_url($cats->href,PHP_URL_PATH)))
{
wp_insert_term($cats->innertext,'category',array(
'description' => '',
'slug' => '',
'parent' => '52')); // International Jobs
} else
{
$count += 1;
}
if ($count == 3)
{
wp_insert_term($cats->innertext,'category',array('description' => '','slug' =>
''));
}
} // End if NewsPaper Check
} // End if Auto Category
echo "<br />";
$postdate = new IXR_Date(strtotime($date));
$title = htmlentities($title,ENT_NOQUOTES,"UTF-8");
$content = array(
'title' => $title,
'description' => $body,
'mt_allow_comments' => 1, // 1 to allow comments
'mt_allow_pings' => 1, // 1 to allow trackbacks
'post_type' => 'post',
'date_created_gmt' => $postdate,
'categories' => $category,
);
// Create the client object
$client = new IXR_Client('http://localhost/FDJ/xmlrpc.php');
$username = "Admin";
$password = "Password";
$params = array(0,
$username,
$password,
$content,
true); // Last parameter is 'true' which means post immediately, to save as draft set it as 'false'
// Run a query for PHP
if (!$client->query('metaWeblog.newPost',$params))
{
die('Something went wrong - ' . $client->getErrorCode() . ' : ' . $client->
getErrorMessage());
echo $title . " <font style='color:#FF0000; font-weight:bold;'>Not Posted.</font><br />";
} else
echo $title . " <font style='color:#00FF00; font-weight:bold;'>Posted Successfully.</font><br />";
}
} // End if Main
?>
P.S. This question is long as there's lot of code. Thank you for your patience and time. I appreciate it.
I am using ultimate wp query search filter plugin on my wordpress site. I would like to use chosen plugin instead of default select boxes. The select boxes already on the page are working perfectly with this code.
(function($){
$(".first-ddwn, .second-ddwn, .third-ddwn, .main-ddwn, .posts_ajax select").chosen({
no_results_text: "Oops, nothing found!",
width: "50%"
});
})(jQuery);
I have changed the result html for AJAX search as mentioned by the plugin author so that I get a dropdown of result posts.
add_filter('uwpqsf_result_tempt', 'customize_output', '', 4);
function customize_output($results , $arg, $id, $getdata ){
// The Query
global $post;
$apiclass = new uwpqsfprocess();
$query = new WP_Query( $arg );
ob_start(); $result = '';?>
<form action="<? bloginfo('url'); ?>" method="get"><?php
echo '<select name="page_id" id="page_id">';
echo '<option value="">Select</option>';
// The Loop
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post(); ?>
<option value="<? echo $post->ID; ?>"><?php echo the_title(); ?></option>
<?php }
echo '</select>';
echo '<input type="submit" name="submit" value="view" />';
echo '</form>';
} else {
echo 'no post found';
}
/* Restore original Post Data */
wp_reset_postdata();
$results = ob_get_clean();
return $results;
}
However, chosen doesn't get applied to this result dropdown. I have tried the option of using settimeout after the AJAX call as mentioned http://davidwalsh.name/jquery-chosen#comment-29299 but it didn't work. maybe I did it wrong. Also when I run it after ajax call like below, chosen does get applied to the select but is all broken.
jQuery.ajax({
type: 'POST',
url: ajax.url,
timeout:3000,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty();res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
$(".content select").chosen();
}
});
This is what I get
This is plugin's uwpqsfscript.js file
jQuery(document).ready(function($) {
$('body').on('click','.usearchbtn', function(e) {
process_data($(this));
return false;
});
$('body').on('click','.upagievent', function(e) {
var pagenumber = $(this).attr('id');
var formid = $('#curuform').val();
upagi_ajax(pagenumber, formid);
return false;
});
$('body').on('keypress','.uwpqsftext',function(e) {
if(e.keyCode == 13){
e.preventDefault();
process_data($(this));
}
});
window.process_data = function ($obj) {
var ajxdiv = $obj.closest("form").find("#uajaxdiv").val();
var res = {loader:$('<div />',{'class':'umloading'}),container : $(''+ajxdiv+'')};
var getdata = $obj.closest("form").serialize();
var pagenum = '1';
jQuery.ajax({
type: 'POST',
url: ajax.url,
timeout:3000,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty();res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
}
});
}
window.upagi_ajax = function (pagenum, formid) {
var ajxdiv = $(''+formid+'').find("#uajaxdiv").val();
var res = {loader:$('<div />',{'class':'umloading'}),container : $(''+ajxdiv+'')};
var getdata = $(''+formid+'').serialize();
jQuery.ajax({
type: 'POST',
url: ajax.url,
data: ({action : 'uwpqsf_ajax',getdata:getdata, pagenum:pagenum }),
beforeSend:function() {$(''+ajxdiv+'').empty(); res.container.append(res.loader);},
success: function(html) {
res.container.find(res.loader).remove();
$(''+ajxdiv+'').html(html);
//res.container.find(res.loader).remove();
}
});
}
$('body').on('click', '.chktaxoall,.chkcmfall',function () {
$(this).closest('.togglecheck').find('input:checkbox').prop('checked', this.checked);
});
});//end of script
And some relevant code (maybe?) from uwpqsf-process-class.php
//front ajax
add_action( 'wp_ajax_nopriv_uwpqsf_ajax', array($this, 'uwpqsf_ajax') );
add_action( 'wp_ajax_uwpqsf_ajax', array($this, 'uwpqsf_ajax') );
add_action( 'pre_get_posts', array($this ,'uwpqsf_search_query'),1000);
}
function uwpqsf_ajax(){
$postdata =parse_str($_POST['getdata'], $getdata);
$taxo = (isset($getdata['taxo']) && !empty($getdata['taxo'])) ? $getdata['taxo'] : null;
$cmf = (isset($getdata['cmf']) && !empty($getdata['cmf'])) ? $getdata['cmf'] : null;
$formid = $getdata['uformid'];
$nonce = $getdata['unonce'];
$pagenumber = isset($_POST['pagenum']) ? $_POST['pagenum'] : null;
if(isset($formid) && wp_verify_nonce($nonce, 'uwpsfsearch')){
$id = absint($formid);
$options = get_post_meta($id, 'uwpqsf-option', true);
$cpts = get_post_meta($id, 'uwpqsf-cpt', true);
$pagenumber = isset($_POST['pagenum']) ? $_POST['pagenum'] : null;
$default_number = get_option('posts_per_page');
$cpt = !empty($cpts) ? $cpts : 'any';
$ordermeta = !empty($options[0]['smetekey']) ? $options[0]['smetekey'] : null;
$ordertype = (!empty($options[0]['otype']) ) ? $options[0]['otype'] : null;
$order = !empty($options[0]['sorder']) ? $options[0]['sorder'] : null;
$number = !empty($options[0]['resultc']) ? $options[0]['resultc'] : $default_number;
$keyword = !empty($getdata['skeyword']) ? sanitize_text_field($getdata['skeyword']) : null;
$get_tax = $this->get_uwqsf_taxo($id, $taxo);
$get_meta = $this->get_uwqsf_cmf($id, $cmf);
if($options[0]['snf'] != '1' && !empty($keyword)){
$get_tax = $get_meta = null;
}
$ordermeta = apply_filters('uwpqsf_ometa_query',$ordermeta,$getdata,$id);
$ordervalue = apply_filters('uwpqsf_ometa_type',$ordertype,$getdata,$id);
$order = apply_filters('uwpqsf_order_query',$order,$getdata,$id);
$number = apply_filters('uwpqsf_pnum_query',$number,$getdata,$id);
$args = array(
'post_type' => $cpt,
'post_status' => 'publish',
'meta_key'=> $ordermeta,
'orderby' => $ordertype,
'order' => $order,
'paged'=> $pagenumber,
'posts_per_page' => $number,
'meta_query' => $get_meta,
'tax_query' => $get_tax,
's' => esc_html($keyword),
);
$arg = apply_filters( 'uwpqsf_query_args', $args, $id,$getdata);
$results = $this->uajax_result($arg, $id,$pagenumber,$getdata);
$result = apply_filters( 'uwpqsf_result_tempt',$results , $arg, $id, $getdata );
echo $result;
}else{ echo 'There is error here';}
die;
}//end ajax
function uajax_result($arg, $id,$pagenumber,$getdata){
$query = new WP_Query( $arg );
$html = '';
//print_r($query); // The Loop
if ( $query->have_posts() ) {
$html .= '<h1>'.__('Search Results :', 'UWPQSF' ).'</h1>';
while ( $query->have_posts() ) {
$query->the_post();global $post;
$html .= '<article><header class="entry-header">'.get_the_post_thumbnail().'';
$html .= '<h1 class="entry-title">'.get_the_title().'</h1>';
$html .= '</header>';
$html .= '<div class="entry-summary">'.get_the_excerpt().'</div></article>';
}
$html .= $this->ajax_pagination($pagenumber,$query->max_num_pages, 4, $id,$getdata);
} else {
$html .= __( 'Nothing Found', 'UWPQSF' );
}
/* Restore original Post Data */
wp_reset_postdata();
return $html;
}//end result
I have been searching for days and have tried many things to make this work. I have no knowledge of jquery,so maybe someone will help me out.
Many Thanks