Filter posts by their post-type with dropdown menu - ajax

I want to filter posts by their post-type.
therefore I have created a dropdown menu where I can select one or multiple post-types.
My question now is: How do I get functionality for my dropdown, because I dont't know how to corespond with the database when the element is in the frontend.
This is my Dropdown-Menu

Using ajax you can filter post.
This is my code for filter post by category (filter post by multiple category selection)
ajax code
<script type="text/javascript">
$('.categorytag').click(function(){
var cokeValue = //you need to pass array of post category id
var data = {
action: 'get_partiblog',
foo: cokeValue
};
$.post('/wp-admin/admin-ajax.php',data,function(response){
$('#filteredblog').html(response);
});
})
</script>
php code
<?php
add_action('wp_ajax_get_partiblog','Getblogcatwise');
add_action('wp_ajax_nopriv_get_partiblog','Getblogcatwise');
function Getblogcatwise(){
$catids = $_POST['foo'];
foreach($catids as $catid){
$args = array(
'post_type'=> 'post',
'orderby' => 'ID',
'category_name' => $catid,
'post_status' => 'publish',
'order' => 'DESC',
'posts_per_page' =>-1 // this will retrive all the post that is published
);
$result = new WP_Query( $args );
if ( $result-> have_posts() ) :
while ( $result->have_posts() ) : $result->the_post();
$link = get_permalink();
echo '<a href="'.$link.'" target="_blank">';
echo '<div class="service-wrapper" style="border:1px solid #367bae;">';
/* if ( has_post_thumbnail() ){
echo '<div><img src="'.the_post_thumbnail("thumbnail").'" alt="Image Missing" rel="lightbox"></div>';
}else{
echo '<div><img src="https://uae.microless.com/cdn/no_image.jpg" alt="" rel="lightbox"></div>';
}*/
$title= get_the_title();
echo '<center><div style="color:#367bae;font-size:22px;font-weight:700;position: relative;margin-top: 25%;padding:5%;">'.$title.'</div></center>';
echo '<div class="service-wrapper-inner">';
//$title= get_the_title();
//echo '<h3>'.$title.'</h3>';
echo '<center><i style="font-size:18px;color:#fff;-webkit-transition: 1s;-moz-transition: 1s;-ms-transition: 1s;-o-transition: 1s; transition: 1s;" class="fa fa-bars"></i></center>';
$excerpt= the_excerpt();
echo '<div class="description"><p>'.$excerpt.'</p></div></div></div></a>';
endwhile;
endif; wp_reset_postdata();
}
}
?>

Related

AJAX Search returns "You do not have sufficient permissions to access this page" on non-admin user

I have this demo website that I'm making:
https://theme.artware.gr/
The problem I am facing is on the search functionality. You can click on the right/top side search to see the issue. When I am logged-in as admin, the search works fine, but when I view the page as a guest I get the error: "You do not have sufficient permissions to access this page".
This is my code so far:
// AJAX Search (no WooCommerce)
if ( !class_exists( 'WooCommerce' ) ) {
function simple_search_scripts(){
wp_enqueue_script( 'simple_search', get_stylesheet_directory_uri() . '/js/search.js', array(), '1.0.0', true);
wp_localize_script('simple_search', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ), 'nonce' => wp_create_nonce('ajax-nonce') ));
}
// Create shortcode
function simple_search(){
simple_search_scripts(); ?>
<input type="text" name="keyword" id="keyword" onkeyup="fetch()" placeholder="<?php _e('Αναζήτηση...'); ?>" />
<div id="datafetch"></div>
<?php
}
add_shortcode('simple_search', 'simple_search');
// Fetch data
function simple_search_callback(){
$the_query = new WP_Query( array( 'posts_per_page' => 10, 's' => esc_attr( $_GET['keyword'] ), 'post_type' => 'post' ) );
if( $the_query->have_posts() ) : while( $the_query->have_posts() ) : $the_query->the_post();
$myquery = esc_attr( $_GET['keyword'] );
$a = $myquery;
$search = get_the_title();
if( stripos("/{$search}/", $a) !== false) { ?>
<div class="result-sin">
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'medium' ); ?>
<div class="result-sin-img">
<?php if ($image) { ?>
<img src="<?php echo $image[0]; ?>" width="<?php echo $image[1]; ?>" height="<?php echo $image[2]; ?>" />
<?php } ?>
</div>
<div class="result-sin-tit"><?php the_title();?></div>
<div class="result-sin-txt"><?php the_excerpt();?></div>
</div>
<?php }
endwhile;
wp_reset_postdata();
endif;
die();
}
add_action('wp_ajax_simple_search', 'simple_search_callback' );
add_action('wp_ajax_nopriv_simple_search', 'simple_search_callback' );
}
And the search.js:
function fetch(){
jQuery.ajax({
async: true,
url: myAjax.ajaxurl,
type: 'GET',
data: {
action: 'simple_search',
keyword: jQuery('#keyword').val(),
nonce: myAjax.nonce
},
success: function(data) {
jQuery('#datafetch').html( data );
}
});
}
And on the header, I simply call a shortcode [simple_search] . Everything post I read on SO said that the wp_ajax_nopriv_ACTION was missing. But I already have that.
UPDATE
I tried using method GET, that didn't work. I also used: wp_localize_script('simple_search', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php', 'relative' ), 'nonce' => wp_create_nonce('ajax-nonce') )); to better enqueue the admin-ajax.php, that didn't work either.
Somewhere In my theme I had require_once('file.php') that had the line below:
if ( !current_user_can( 'manage_options' ) ) { wp_die( __( 'You do not have sufficient permissions to access this page.' ) ); }
When I removed this, the problem was fixed.

woocommerce product sort order change by our own weight value or menu order

I need to add a specified value or weight for a product so that product will display as per order on the woocommerce shop page. I think this can be done by product bulk edit. But not sure is it right or any conflict may arise in the future. can anyone suggest how I a custom sort function as per a given value for the bulk products? Currently, the drag and drop method is difficult in the case of thousand of products.
add_action( 'woocommerce_product_bulk_edit_start', 'custom_field_product_bulk_edit', 10, 0 );
function custom_field_product_bulk_edit() {
?>
<div class="inline-edit-group">
<label class="alignleft">
<span class="title"><?php _e('Custom Sort Weight', 'woocommerce'); ?></span>
<span class="input-text-wrap">
<select class="change_t_dostawy change_to" name="change_t_dostawy">
<?php
$options = array(
'' => __( '— No change —', 'woocommerce' ),
'1' => __( 'Change to:', 'woocommerce' ),
);
foreach ( $options as $key => $value ) {
echo '<option value="' . esc_attr( $key ) . '">' . $value . '</option>';
}
?>
</select>
</span>
</label>
<label class="change-input">
<input type="text" name="_t_dostawy" class="text t_dostawy" placeholder="<?php _e( 'Enter Weight Here ', 'woocommerce' ); ?>" value="" />
</label>
</div>
<?php
}
// Save the custom fields data when submitted for product bulk edit
add_action('woocommerce_product_bulk_edit_save', 'save_custom_field_product_bulk_edit', 10, 1);
function save_custom_field_product_bulk_edit( $product ){
if ( $product->is_type('simple') || $product->is_type('external') ){
$product_id = method_exists( $product, 'get_id' ) ? $product->get_id() : $product->id;
if ( isset( $_REQUEST['_t_dostawy'] ) ){
// update_post_meta( $product_id, 'menu_order', sanitize_text_field( $_REQUEST['_t_dostawy'] ) );
$arg=array('ID' => $product_id,'menu_order' => $_REQUEST['_t_dostawy']);
$result = wp_update_post($arg);
}
}
}
I have added an option on quick edit and then update the menu order value by ajax. so that all the product having same menu order will be displayed on same row.But this is not a correct way.
So I have do other stuff that added text box in the product listing and where we can add a menu order for product.
//
Add product new column in administration
add_filter( 'manage_edit-product_columns', 'woo_product_weight_column', 20 );
function woo_product_weight_column( $columns ) {
$columns['sort_weight'] = esc_html__( 'Weight', 'woocommerce' );
return $columns;
}
// Populate weight column
add_action( 'manage_product_posts_custom_column', 'woo_product_weight_column_data', 2 );
function woo_product_weight_column_data( $column ) {
global $post;
if ( $column == 'sort_weight' ) {
$postval = get_post( $post->ID);
$menu_order_new = $postval->menu_order;
?>
<input type="text" name="menuorder" id="id_<?php echo $post->ID;?>" data-productid="<?php echo $post->ID;?>" value="<?php echo $menu_order_new; ?>" class="menuorder"/>
<?php
}
}
add_action('admin_head', 'my_column_width');
function my_column_width() {
echo '<style type="text/css">';
echo 'table.wp-list-table .column-sort_weight { width: 101px; text-align: left!important;padding: 5px;}';
echo 'table.wp-list-table .column-wpseo-score { width: 101px; text-align: left!important;padding: 5px;}';
echo'.menuorder{ width: 101px; }';
echo '</style>';
}
// this code adds jQuery script to website footer that allows to send AJAX request
add_action( 'admin_footer', 'misha_jquery_event' );
function misha_jquery_event(){
echo "<script>jQuery(function($){
var weight_val;
var pr_id;
jQuery('.menuorder').on('input', function(){
weight_val = $(this).val();
pr_id=$(this).attr('data-productid');
var dataVariable = {
'action': 'productmetasave',
'product_id': pr_id,
'value':weight_val
};
jQuery.ajax({
url: ajaxurl,
type: 'POST',
data: dataVariable,
success: function (response) {
if(response==1){
location.reload(true);
}else{
console.log('Failed To update menu-order ');
}
}
});
});
});</script>";
}
// this small piece of code can process our AJAX request
add_action( 'wp_ajax_productmetasave', 'misha_process_ajax' );
function misha_process_ajax(){
if($_POST['product_id'] && $_POST['value'] ){
$arg=array('ID' => $_POST['product_id'],'menu_order' => $_POST['value']);
$rs = wp_update_post($arg);
if($rs){
echo "1";
}else{
echo "0";
}
}
die();
}

How to get Advanced Custom Fields values with Ajax in Wordpress

I'm trying to do a WP_query on a custom-post-type but for some reason I cannot get the values from the custom-field-types of these posts.
Here is what I got so far (functions.php)
function fetch_cases(){
$args = array(
'post_type' => array('case'),
'post_status' => array('publish'),
'posts_per_page' => 5
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
</div>
</a>
<?php }
}
die();
add_action('wp_ajax_nopriv_fetch_cases', 'fetch_cases');
add_action('wp_ajax_fetch_cases','fetch_cases');
}
And in my JS file have the following:
$.ajax({
url: "/wp-admin/admin-ajax.php",
data: {
action: "fetch_cases"
},
success: function(data) {
$(".fetch_cases").append(data);
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
Can someone tell me what I'm doing wrong?
I also tried to do:
<?php the_field('case_picture'); ?>
but with no luck? what am I missing?
add_action() should be outside your custom function. Try this instead.
function fetch_cases(){
$args = array(
'post_type' => array('case'),
'post_status' => array('publish'),
'posts_per_page' => 5
);
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
</div>
</a>
<?php }
}
die();
}
add_action('wp_ajax_nopriv_fetch_cases', 'fetch_cases');
add_action('wp_ajax_fetch_cases','fetch_cases');
you can use this logic by storing the field as a hidden value and pass in ajax through js
$query = new WP_Query($args);
if($query->have_posts()) {
while($query->have_posts() ){
$query->the_post();
?>
<a href="<?php the_permalink(); ?>">
<div style="background-image:url('<?= get_field('case_picture'); ?>')">
<p><?= get_field('case_title') ?></p>
<input type="hidden" id="hidden" name="hidden_field" value="<?= get_field('case_picture'); ?>"> // store the value
</div>
</a>
<?php }
}
die();
Now get the data in jquery and pass through ajax
<script>
var hidden=//Grab data here.
$.ajax({
url: "/wp-admin/admin-ajax.php",
data: {
action: "fetch_cases",
image:hidden, // Pass the data
},
success: function(data) {
$(".fetch_cases").append(data);
},
error: function(errorThrown) {
console.log(errorThrown);
}
});
</script>
and use the data in ajax called
function fetch_cases()
{
$image=$_POST['image'];
}
get_field method has 2nd parameter which is post ID, pass this and check. It should work.
$post_id = $post->ID;
$value = get_field( 'case_picture', $post_id );

WP_Query on function not showing pagination

I have this code and its working fine, the only problem is that its not showing pagination. This code is on my functions.php file.
add_action( 'wp_ajax_nopriv_load-filter', 'prefix_load_cat_posts' );
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () {
global $post;
$cat_id = $_POST[ 'cat' ];
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
$args = array (
'cat' => $cat_id,
'posts_per_page' => 6,
'order' => 'DESC',
'paged' => $paged
);
$cat_query = new WP_Query($args);
if($cat_query->have_posts()) :
while($cat_query->have_posts()) : $cat_query->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
wp_reset_query();
?>
<div class="page-nation">
<ul class="pagination pagination-large">
<?php
$pagination = get_the_posts_pagination(array(
'mid_size' => 2,
'prev_text' =>esc_html__('Previous', 'travel-tour'),
'next_text' => esc_html__('Next', 'travel-tour'),
'screen_reader_text' => ' ',
) );
echo $pagination;
?>
</ul>
</div>
<?php
endif;
die();
}
and this is my jquery ajax script
<script>
jQuery(document).ready(function () {
jQuery('.js-category-button').on('click', function(e){
e.preventDefault();
jQuery('.preloadswitch').addClass('addpreloader');
var catID = jQuery(this).data('slug');
var catName = jQuery(this).attr('href');
var ajaxurl = '<?php echo esc_js( admin_url( 'admin-ajax.php' ) ) ?>';
jQuery.ajax({
type: 'POST',
url: ajaxurl,
crossDomain : true,
dataType: 'html',
data: {"action": "load-filter", cat: catID },
beforeSend: function () {
jQuery(".the-categories").html('<div></div>').fadeIn('slow');
jQuery(".page-nation").hide();
//window.location.hash = "#"+jQuery("#comehere").attr("id");
jQuery('html,body').animate({scrollTop:jQuery('#comehere').offset().top}, 1000);
window.history.pushState('obj', 'newtitle', catName);
},
success: function(response) {
jQuery(".the-categories").append(response);
jQuery('.preloadswitch').removeClass('addpreloader');
return false;
}
});
})
});
</script>
I don't what to do here anymore, I have been searching on the web for possible working function but with no luck.
I just need to show the pagination
Comment out or remove the wp_reset_query();, or move it to after the pagination; and use paginate_links() instead of get_the_posts_pagination().
Here's the altered 'if-else' block in your prefix_load_cat_posts() function:
if($cat_query->have_posts()) :
while($cat_query->have_posts()) : $cat_query->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile;
//wp_reset_query();
?>
<div class="page-nation">
<ul class="pagination pagination-large">
<?php
$pagination = paginate_links(array(
'mid_size' => 2,
'prev_text' =>esc_html__('Previous', 'travel-tour'),
'next_text' => esc_html__('Next', 'travel-tour'),
'current' => $paged,
'total' => $cat_query->max_num_pages,
'type' => 'array',
'base' => home_url( '/%_%' ),
) );
echo '<li>' . implode( '</li><li>', $pagination ) . '</li>';
?>
</ul>
</div>
<?php
endif;
[EDIT] Try setting the base parameter.

wordpress showing comments from a post retrieved with ajax

i'm loading a post with ajax.
The code is
$(document).ready(function(){
loadPostsFun = function(){
$.ajax({
url: "http://lab1.koalamedia.es/ajax/",
//url: "/random/",
success: function(response){
$("#randomPost").html( response );
}
});
};
$("#another").click(function(){
loadPostsFun();
return false;
});
});
The response is generated by a custom template with this code:
<?php
query_posts('showposts=1&orderby=rand');
the_post();
$args = array( 'numberposts' => 1, 'orderby' => 'date' );
$rand_posts = get_posts( $args );
?>
<?php
foreach( $rand_posts as $post ) : setup_postdata($post);
?>
<div id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if ( is_front_page() ) { ?>
<h2 class="entry-title"><?php the_title(); ?></h2>
<?php } else { ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<?php } ?>
<div class="entry-content">
<?php the_content(); ?>
<?php wp_link_pages( array( 'before' => '<div class="page-link">' . __( 'Pages:', 'twentyten' ), 'after' => '</div>' ) ); ?>
<?php comments_popup_link(__('Comments (0)'), __('Comments (1)'), __('Comments (%)')); ?>
</div><!-- .entry-content -->
</div><!-- #post-## -->
<?php
//comments_template( '', true ); //this doesn't work
comment_form();
//wp_list_comments(''); //this doesn't work
?>
<?php endforeach; ?>
The ajax request works but the comments doesn't show.All the post data is there.
How can i show the comments?
neither comments_template or wp_list_comments work.
You can view a demo or download the template sample i've done here
Without much tweaking wp_list_comments() works in a comments template (usually comments.php) only.
Use get_comments(), pass the post ID as parameter:
$comments = get_comments(array ( 'post_id' => $post->ID );
if ( $comments )
{
foreach ( $comments as $comment )
{
print "<li>$comment->comment_author<br>$comment->comment_content</li>";
}
}
i've found the problem, i forgot to set the global variable:
global $withcomments;
i was using
$withcomments = true;
comments_template();
but without the global it didn't work.
Now works like normal comments do.

Resources