i need to perform 2 different searches for 2 different pages
This is first one, and second one would be 10 posts per page and different post type, i've tried using is_page() but it doesn't work since it trows 0 results and i've checked if there are any
function ja_ajax_search() {
$results = new WP_Query( array(
'post_type' => array( 'post', 'page' ),
'posts_per_page' => 5,
's' => stripslashes( $_POST['search'] ),
) );
$items = array();
if ( ! empty( $results->posts ) ) {
foreach ( $results->posts as $result ) {
$items[] = $result->post_title;
}
}
wp_send_json_success( $items );
}
add_action( 'wp_ajax_search_site', 'ja_ajax_search' );
add_action( 'wp_ajax_nopriv_search_site', 'ja_ajax_search' );
/*eslint-disable */
jQuery(function ($) {
var searchRequest;
$('#ses').autoComplete({
minChars: 3,
source: function (term, suggest) {
searchRequest = $.post(global.ajax, {search: term, action: 'search_site',tip_pretrage: 'cards'}, function (res) {
suggest(res.data);
});
},
})
});
Related
im doing a lazy loading with WP_Query Pagination
it's working fine but the content duplicate itself when it reaches it's end
and when i search for a specific result it shows the result correctly
but after that it still want to do lazy load so it load random data
here is my code
lazy-load.php
<?php
add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');
add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');
function load_posts_by_ajax_callback(){
// check_ajax_referer( 'load_more_posts', 'security' );
$paged = $_POST['page'];
$args = array(
'post_type' => 'unit',
'post_status' => 'publish',
'posts_per_page' => 4,
'paged' => $paged
);
if ( !empty($_POST['taxonomy']) && !empty($_POST['term_id']) ){
$args['tax_query'] = array (
array(
'taxonomy' => $_POST['taxonomy'],
'terms' => $_POST['term_id'],
),
);
}
if ( ! is_null($_POST['offer']) ) {
$args['meta_query'][] = array(
'key' => 'WAKEB_hot',
'value' => '1',
'compare' => '=',
);
}
if ( ! is_null($_POST['purpose']) ) {
$args['meta_query'][] = array(
'key' => 'WAKEB_vacation',
'value' => '1',
'compare' => '=',
);
}
if (!empty($_POST['project'])){
$args['meta_query'] = array (
array(
'key' => 'WAKEB_project',
'value' => $_POST['project'],
'compare' => '='
),
);
}
// start buffer
ob_start();
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while($query->have_posts()){ $query->the_post();
get_template_part("template-parts/units");
}
endif; wp_reset_postdata();
// start buffered data in data variable
$data = ob_get_clean();
wp_send_json_success( $data );
wp_die();
}
add_action('wp_ajax_nopriv_load_projects_by_ajax', 'load_projects_by_ajax_callback');
add_action('wp_ajax_load_projects_by_ajax', 'load_projects_by_ajax_callback');
function load_projects_by_ajax_callback(){
// check_ajax_referer( 'load_more_posts', 'security' );
$paged = $_POST['page'];
$args = array(
'post_type' => 'project',
'post_status' => 'publish',
'posts_per_page' => 4,
'paged' => $paged
);
if ( ! is_null($_POST['ptype']) ) {
$args['tax_query'] = array (
array(
'taxonomy' => 'pptypes',
'field' => 'slug',
'terms' => $_POST['ptype'],
),
);
}
if ( !empty($_POST['taxonomy']) && !empty($_POST['term_id']) ){
$args['tax_query'] = array (
array(
'taxonomy' => $_POST['taxonomy'],
'terms' => $_POST['term_id'],
),
);
}
// start buffer
ob_start();
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
while($query->have_posts()){ $query->the_post();
get_template_part("template-parts/projects");
}
endif; wp_reset_postdata();
// start buffered data in data variable
$data = ob_get_clean();
wp_send_json_success( $data );
wp_die();
}
lazy-load.js
$('.unit-terms li a').each( function() {
if ( this.href == window.location.href ) {
$(this).parent().addClass('current');
}
});
main.js
(function($){
$('.isotope a').on('click', function(){
$('.isotope .active').removeClass('active');
$(this).addClass('active');
var filter = $(this).data('filter');
if(filter=='*'){
$('.property').show();
}else{
$('.property').not(filter).hide();
$('.property'+filter).show();
}
return false;
});
})(jQuery);
so how can i make it work? i don't know what im doing wrong here
Here is the repo link for the full project
https://github.com/Ov3rControl/hoomerz
ok, now I understand what you meant ;) During lazy load you send to backend only page number without current state of filters and / or search string. So it sends all posttype items based on page number only. You should send also current state of filters
main.js: add this to your after-page-load function:
var currentUrl = new URL(window.location.href);
var searchQuery = urlObj.searchParams.get("k");
lazy-load.js: add search param to data posted to backend
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'search: searchQuery // new field
};
lazy-load.php: add search param to WP_Query
if ( isset($_POST['search']) && !empty($_POST['search']) ){ // new section
$args['s'] = sanitize_text_field($_POST['search']);
}
That's example for text search filter. For all filters you must
1. match every filter from front (URL get param) (main.js)
2. than put it in data object sent to backend (lazy-load.js)
3. address this variable in lazy-load.php in if(isset($_POST['param-name'])) section ( new or existing one as there are some )
I suggest to try without ob_start() / ob_get_clean(). Also if you generate html instead of raw data structure, I would simply print it to output without wp_send_json_success().
Other solution would be sending raw data (1. array in php, 2. json_encode(), 3. wp_send_json() ) and than processing in javascript (dynamic dom element creation after request to backend made).
I have a multisite setup were the custom post type article has a relation to other posts at the network by the custom field alphanumeric_id This key is unique on each blog and the related posts are generated programmatically on add_action('wp_insert_post', 'bZive_create_TranslatedContent', 15, 3);
function bZive_trash_TranslatedContent($post_id){
// Get the current blog id
$original_site_id = get_current_blog_id();
$postTypes = array('profile', 'article');
$postType = get_post_type( get_the_ID() );
$randomString = get_post_meta( get_the_ID(), 'alphanumeric_id', true );
$args = array(
'public' => true,
'limit' => 500
);
$sites = wp_get_sites($args);
$tests = array();
foreach ($sites as $site) {
switch_to_blog($site['blog_id']);
if( get_current_blog_id() != $original_site_id and get_current_blog_id() != 1 ){
$args = array(
'post_type' => 'article',
'post_status' => array(
'publish', 'draft', 'pending','auto-draft', 'future', 'private'
),
'meta_query' => array(
array(
'key' => 'alphanumeric_id',
'value' => $randomString ,
'compare' => '=',
),
),
);
$posts = new WP_Query($args);
if( $posts->have_posts() ) {
while( $posts->have_posts() ) {
$posts->the_post();
// Move the post to trash
wp_trash_post(get_the_ID());
}
}
wp_reset_postdata();
}
restore_current_blog();
}
}
add_action('trash_post','bZive_trash_TranslatedContent',10,3);
What I want to archive: If I move one post to the trash - all related post should be moved to the trash too. But somehow the posts aren't getting deleted - I tested the WP_Query it's getting the right posts but still, they don't get deleted.
Finally working!
function bZive_trash_TranslatedContent($post_id){
// Get the current blog id
$original_site_id = get_current_blog_id();
$postTypes = array('profile', 'article');
$postType = get_post_type( get_the_ID() );
$randomString = get_post_meta( get_the_ID(), 'alphanumeric_id', true );
if (in_array( $postType, $postTypes ) and empty( get_post_meta( $post_id, 'del_translatedContent', true ) ) ) {
add_post_meta($post_id, 'del_translatedContent', 'true');
$args = array(
'public' => true,
'limit' => 500
);
$sites = wp_get_sites($args);
$tests = array();
foreach ($sites as $site) {
switch_to_blog($site['blog_id']);
if( get_current_blog_id() != $original_site_id and get_current_blog_id() != 1 ){
$args = array(
'post_type' => 'article',
'post_status' => array(
'publish', 'draft', 'pending','auto-draft', 'future', 'private'
),
'meta_query' => array(
array(
'key' => 'alphanumeric_id',
'value' => $randomString ,
'compare' => '=',
),
),
);
$posts = new WP_Query($args);
if( $posts->have_posts() ) {
while( $posts->have_posts() ) {
$posts->the_post();
// Move the post to trash
wp_trash_post(get_the_ID());
add_post_meta(get_the_ID(), 'del_translatedContent', 'true');
}
}
wp_reset_postdata();
}
restore_current_blog();
}
}
}
add_action('wp_trash_post','bZive_trash_TranslatedContent',1,3);
I have created a custom html form that is having 2 dropdowns State and City. When selects a State i want to populate the city dropdown. But the feature is not working. I already followed many urls but unable to solve the issue.
See the code below i have tried. Can anybody help me.
function zenuineform($form, &$form_state) {
$value_dropdown_first = isset($form_state['values']['comp_state']) ? $form_state['values']['comp_state'] : 1;
$form = array();
$form['comp_state']=array(
'#type'=>'select',
'#title'=>t('State : '),
'#options'=> $state_arr,
'#default_value' => $state,
'#ajax' => array(
// When 'event' occurs, Drupal will perform an ajax request in the
// background. Usually the default value is sufficient (eg. change for
// select elements), but valid values include any jQuery event,
// most notably 'mousedown', 'blur', and 'submit'.
'event' => 'change',
'callback' => 'zenuineform_ajax_callback',
'wrapper' => 'filtered_city',
),
);
$form['comp_city']=array(
'#type'=>'select',
'#title'=>t('City : '),
'#default_value' => $city,
'#prefix' => '<div id="filtered_city">',
'#suffix' => '</div>',
'#options' => zenuineform_second_dropdown_options($value_dropdown_first),
);
return $form;
}
function zenuineform_ajax_callback($form, $form_state) {
return $form['comp_city'];
}
function zenuineform_second_dropdown_options($state_id = '') {
if($state_id !='' ) {
$result = db_query('SELECT * FROM zen_city WHERE state_id = '.$state_id);
if ($result) {
$options = '<option value="">--Select--</option>';
while ($row = $result->fetchAssoc()) {
$rows[$row['id']] = $row['city_name'];
}
return $rows;
}
}
else {
return array('--Select--');
}
}
I need to make two chained select inputs (country, city) in WP.
(all is in locations taxonomy, country is a main category and city is a subcategory)
in first select i listed all countries:
$locations = get_terms( ‘locations’, array(
‘hide_empty’ => false,
‘parent’ => 0 ) );
In second select i need only the cities depend on selected country
(without page refresh/submit, so with AJAX)
I need passing selected value from first select to php variable:
$whichCountry = AJAX RESPONSE HERE
Listing second select:
$locations = get_terms( ‘locations’, array(
‘hide_empty’ => false,
‘parent’ => $whichCounty) );
Please help me how to achieve this
i make same code but its not enough:
JS:
(function ($) {
$(document).ready(function () {
$(‘#first_select’).on(‘change’, function(){
$.post(
PT_Ajax.ajaxurl,
{
// wp ajax action
action: ‘ajax-inputtitleSubmit’,
// vars
data: $(‘#first-select’).val(),
// send the nonce along with the request
nextNonce: PT_Ajax.nextNonce
},
function (response) {
console.log(response.data);
}
);
return false;
});
});
})(jQuery);
PHP:
add_action( ‘wp_enqueue_scripts’, ‘inputtitle_submit_scripts’ );
add_action( ‘wp_ajax_ajax-inputtitleSubmit’, ‘myajax_inputtitleSubmit_func’ );
add_action( ‘wp_ajax_nopriv_ajax-inputtitleSubmit’, ‘myajax_inputtitleSubmit_func’ );
function inputtitle_submit_scripts() {
wp_enqueue_script( ‘inputtitle_submit’, get_template_directory_uri() . ‘/assets/js/inputtitle_submit.js’, array( ‘jquery’ ) );
wp_localize_script( ‘inputtitle_submit’, ‘PT_Ajax’, array(
‘ajaxurl’ => admin_url( ‘admin-ajax.php’ ),
‘nextNonce’ => wp_create_nonce( ‘myajax-next-nonce’ )
)
);
}
function myajax_inputtitleSubmit_func() {
// check nonce
$nonce = $_POST[‘nextNonce’];
if ( ! wp_verify_nonce( $nonce, ‘myajax-next-nonce’ ) ) {
die ( ‘Busted!’ );
}
// generate the response
$response = json_encode( $_POST );
// response output
header( “Content-Type: application/json” );
$whichCountry = $response;
// IMPORTANT: don’t forget to “exit”
exit;
}
Functions.php
include_once(‘inputtitle_submit_inc.php’)
I have a CListView which I want to filter using Ajax. I have 2 textfields. Now they both filter the same column: titel. I'm searching quite some time now, but I can't seem to figger out why they both filter the titel and not the locatie too..
It's my first time to use Ajax so, i'm afraid I don't know exactly how to pass the right parameters at the moment and am kind of lost. Someone who can help me?
So here's my view:
<?php echo CHtml::beginForm(CHtml::normalizeUrl(array('kunstwerk/index')), 'get', array('id'=>'filter-form'))?>
<?php echo CHtml::textField('string', (isset($_GET['string'])) ? $_GET['string'] : '', array('id'=>'locatie'));?>
<?php echo CHtml::textField('string', (isset($_GET['string'])) ? $_GET['string'] : '', array('id'=>'titel'));?>
and..
Yii::app()->clientScript->registerScript('search',
"var ajaxUpdateTimeout;
var ajaxRequest;
$('input#titel').keyup(function(){
titel = $(this).serialize();
clearTimeout(ajaxUpdateTimeout);
ajaxUpdateTimeout = setTimeout(function () {
$.fn.yiiListView.update(
// this is the id of the CListView
'ajaxListView',
{data: titel}
)
},
// this is the delay
300);
});
$('input#locatie').keyup(function(){
locatie = $(this).serialize();
clearTimeout(ajaxUpdateTimeout);
ajaxUpdateTimeout = setTimeout(function () {
$.fn.yiiListView.update(
// this is the id of the CListView
'ajaxListView',
{data: locatie}
)
},
// this is the delay
300);
});"
);
and..
<?php $this->widget('zii.widgets.CListView', array(
'dataProvider'=>$dataProvider,
'itemView'=>'_view',
'sortableAttributes'=>array(
'titel'
),
'id'=>'ajaxListView',
));
?>
Here's my controller:
public function actionIndex($string = '')
{
$criteria = new CDbCriteria();
if( strlen( $string ) > 0 )
$criteria->addSearchCondition( 'titel', $string, true, 'OR' );
$criteria->addSearchCondition( 'locatie', $string, true, 'OR' );
$dataProvider = new CActiveDataProvider( 'Kunstwerk', array( 'criteria' => $criteria, ) );
//$dataProvider=new CActiveDataProvider('Kunstwerk');
$this->render('index',array(
'dataProvider'=>$dataProvider,
'bedrijven' => Bedrijf::model()->findAll(),
));
}