Dynamically loading custom posts by category with AJAX - ajax

I'm working on this site:
http://www.bajo.co.uk/2012/
...which shows a toy portfolio on the home page. The toys have different categories: Infant, Vehicles, educational etc. When the user clicks the sidebar menu 'Infant', thumbnails for all toys with the category 'Infant' will be listed on the right.
I currently have this set up by using a different page-template for each category with the following custom loop:
<!-- loop to show products list -->
<?php
$args = array(
'post_type' => 'products',
'orderby' => 'title',
'order' => 'DES',
'posts_per_page' => 8,
'paged' => get_query_var ('page'),
'post_parent' => $parent,
'category_name' => 'educational'
);
?>
<?php query_posts($args); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<li>
<a href="<?php the_permalink() ?>" class="product_image">
<?php echo get_post_meta($post->ID, 'ProductImage', true);?>
<span class="overlay"></span>
</a>
<h3 class="product_tit"><?php the_title();?></h3>
</li>
<?php endwhile; ?>
<?php else :?>
<p>There are no products to display</p>
<?php endif; ?>
Although this works correctly, every time the user selects a category from the menu, the page is refreshed.
I would like to implement this with AJAX so that the page does not refresh and the products (which are a custom post type) are loaded in dynamically whilst maintaining the pagination.
Any pointers on where to start greatly appreciated.
I'm using:
Wordpress 3.5.1
Custom Post Type UI plugin

I still don't have the right to comment, so I put my comment here as an answer maybe it will be helpful.
My approach for such situation is to create a php file file.php which I will address via a parametrer like this file.php?p=infant (fo example)
<?php
$p=$_GET['p'];
require('../../../wp-load.php');
?>
<?php
$my_query = new WP_Query();
$my_query->query(array( 'post__in' => array($p)));
if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post();
?>
<li>
<a href="<?php the_permalink() ?>" class="product_image">
<?php echo get_post_meta($post->ID, 'ProductImage', true);?>
<span class="overlay"></span>
</a>
<h3 class="product_tit"><?php the_title();?></h3>
</li>
<?php
endwhile;
endif;
?>
I will create in addition a javascript function which will manage the ajax call like this:
function f(str)
{
$.ajax({
cache: true,
type: "GET",
timeout: 5000,
url: 'url/to/file.php?p='+str,
success: function(msg)
{
$('#the_div_containing_li').html(msg);
},
error: function(msg)
{
alert("Your browser broke!");
return false;
}
});
}
Note that you should put your li (and the dynamically loaded content in a div , which I called the_div_containing_li). and onClick on your anchor, call the javascript function f(id of this anchor). you can of course assign to each anchor an id via the wordpress loop.

Related

How to create an Ajax Filter to display custom post types in WordPress

I asked a question to this topic before but since it seems like this requires just custom coding, I need help from the experts. I am not a coder, I design and build website in Webflow but want to learnt to convert them to a WordPress theme.
I have a Custom Post Type and want to display all of these posts on a page, however, above the displayed posts I want a filter, so that the user can click on a category and only see custom posts for that category (without page reload).
I registered a custom taxonomy and added categories for this. I see this on so many website, this seems to be a super common thing, and that's why I am so surprised that there is no plugin to achieve that. But anyway, here is an example of what I want to achieve: https://www.hauserlacour.de/en/work
I know that it has something to do with custom queries and AJAX. But I couldn't find a beginner friendly tutorial to achieve what I need.
Can anyone help me with the code below and what is needed to turn my custom taxonomy into a filter?
And here is the code I have as of now:
<?php get_header( 'page-posttest' ); ?>
<div class="projekte-wrapper-1">
<?php $terms = get_terms( array(
'taxonomy' => 'art',
'orderby' => 'name',
'order' => 'ASC',
'hide_empty' => false
) ) ?>
<?php if( !empty( $terms ) ) : ?>
<div class="taxonomy-wrapper">
<?php foreach( $terms as $term ) : ?>
<?php echo $term->name; ?>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php
$projekte_query_args = array(
'post_type' => 'projekte',
'nopaging' => true,
'order' => 'ASC',
'orderby' => 'date'
)
?>
<?php $projekte_query = new WP_Query( $projekte_query_args ); ?>
<?php if ( $projekte_query->have_posts() ) : ?>
<div class="posts-wrapper">
<?php while ( $projekte_query->have_posts() ) : $projekte_query->the_post(); ?>
<?php PG_Helper::rememberShownPost(); ?>
<?php $image_attributes = !empty( get_the_ID() ) ? wp_get_attachment_image_src( PG_Image::isPostImage() ? get_the_ID() : get_post_thumbnail_id( get_the_ID() ), 'full' ) : null; ?>
<h1 class="heading-14"><?php the_title(); ?></h1>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
</div>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.', 'test' ); ?></p>
<?php endif; ?>
</div>
<?php get_footer( 'page-posttest' ); ?>

Filter AJAX search results in WordPress by page template

I am making a WordPress website, which is made up of a Woocommerce Store + Blog section. Both in the Store and on the Blog there is a search engine that shows instant results with AJAX. What I want to do is that, depending on the page where the user is (Blog page or Store page), the search engine will only show results of articles or products, respectively.
After googling and testing, I understood that the conditional tags of Wordpress (is_home (), is_shop (), etc) don't work if they are called from the functions.php file, and the AJAX php function I'm using is effectively inside the functions.php.
The AJAX php function is as follows:
<?php
/**
* Adding ajax search functionality to the theme
*/
add_action('wp_ajax_nopriv_ajax_search','ajax_search');
add_action('wp_ajax_ajax_search','ajax_search');
function ajax_search(){
global $post;
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
's' =>$_POST['term'],
'posts_per_page' =>10
);
$query = new WP_Query( $args );
// display results
if( $query->have_posts() ) : ?>
<?php while( $query->have_posts() ) : $query->the_post(); ?>
<li>
<?php
$terms = get_the_terms( $post->ID, 'category' );
foreach ($terms as $term) {
break;
} ?>
<a title="<?php the_title(); ?>" href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a>
<div class="clear"></div>
</li>
<?php endwhile;
wp_reset_postdata(); ?>
<?php else: ?>
<li class="no-results-ajax">No results.</li>
<?php endif; ?>
<?php exit;
}
?>
The JQuery function linked with the previous function is as follows:
function buscar_ajax(input1, input2) {
input1.keyup(function(e) {
// prevent browser autocomplete
jQuery(this).attr('autocomplete','off');
// get search term
var searchTerm = jQuery(this).val();
var urlFull = window.location.href; // URL completa
var ruta = window.location.pathname; // URL sin "http://dominio.com"
var dominio = urlFull.replace(ruta,''); // URL solo "http://dominio.com"
if(searchTerm.length > 2) {
jQuery.ajax({
url: dominio + "/wp-admin/admin-ajax.php",
type:"POST",
data:{
'action':'ajax_search',
'term' :searchTerm
},
success:function(result){
input2.fadeIn(200).html(result);
}
});
} else {
input2.fadeOut(200);
}
if(searchTerm.length == 0){
input2.hide();
}
if(e.keyCode == 27){
jQuery(this).val('');
input2.hide();
}
jQuery('body').click(function(e){
if ( !jQuery(e.target).hasClass("busqueda") ) {
input2.fadeOut(200);
jQuery(this).val('');
}
});
});
input1.keypress(function(e) {
if(e.keyCode == 27){
jQuery(this).val('');
input2.fadeOut(200);
}
});
}
var buscaHead1 = jQuery('input#s');
var buscaHead2 = jQuery('ul#dhemy-ajax-search');
buscar_ajax( buscaHead1, buscaHead2 );
And the HTML code of the search form:
<form role="search" method="get" id="buscador-blog" class="searchform" action="<?php echo esc_url( home_url( '/' ) ); ?>">
<input class="busqueda" type="text" value="" name="s" id="s" placeholder="Busca en el blog..."/>
<ul id="dhemy-ajax-search"></ul> <!-- AJAX search -->
<input type="submit" id="searchsubmit" value="" />
<input type="hidden" name="search-type" value="post" />
</form>
So far, the result is that AJAX shows blog articles or products or articles and products. (changing 'post' to 'product' in the 'post_type' parameter of the $ args array). I need that, if the person is on the Store page, they only show products and if they are on the Blog page, they only show posts.
This could be done if only I had some conditional to evaluate what type of page the user is viewing, and that is where I am trapped.
I very much appreciate any help or guidance you can give me.

How to add load more button ajax button to this wordpress loop?

<main class="main aktualitasu_saraksta_konteineris" role="main">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'group_by' => 'date',
'order' => 'DESC',
'ignore_sticky_posts' => 1
);
$query = new WP_Query($args);
?>
<?php if ($query->have_posts()) : while ($query->have_posts()) : $query->the_post(); ?>
<?php get_template_part( 'parts/loop', 'news' ); ?>
<?php endwhile; endif; wp_reset_postdata();?>
</main>
How to add load more button that load posts with ajax?
You will need to do this in javascript rather than in php look at this https://www.w3schools.com/jquery/jquery_ajax_get_post.asp. You will need to add button in html say
<button id="load_more" type="button">Load More</button>
And then in javascript (this is an example using jQuery)
$("#load_more").click(function(){
$.get("your/route", function(data, status){
//here you can add the data to the page depending on what the data is
});
});
your/route is whatever route you have set in php for fetching more posts

Show 'Advanced Custom Field' Image

I'm having problems getting the image field from Advanced Custom Field plugin. I'm using it to set an image for custom taxonomy category named "aktuelni_ponudi_category". I have displayed the name of the category and its link, but can't fix the problem with the image. I also want to create a shortcode, so here is my code:
function my_vc_shortcode( $atts ) {
$categories = get_categories( array(
'taxonomy' => 'aktuelni_ponudi_category',
'hide_empty' => '0',
'order' => 'DESC'
)); ?>
<div class="row">
<?php
foreach($categories as $category) { ?>
<div class="col-md-4">
<a href="<?php echo get_category_link($category->cat_ID); ?>">
<?php echo $category->name; ?>
</a>
<?php echo '<img src="' . the_field('acf_image') . '">'; ?>
</div>
<?php }
?>
</div>
<?php }
add_shortcode( 'my_vc_php_output', 'my_vc_shortcode');
I'm hoping for an answer...
If you use custom fields on a taxonomy term there is a special syntax to get that data: you should call the field function with a parameter composed of the taxonomy name and the term id, like here:
the_field('acf_field','aktuelni_ponudi_category_' . $category->cat_ID);
You can read more about it here: https://www.advancedcustomfields.com/resources/get-values-from-a-taxonomy-term/

Query vars in url (wordpress) work fine when page loaded directly, but fail on ajax

I've a little issue, and I couldn't find anything about it... I'm in deadlock.
So I've wp page that contains normal loop, if I call this file directly in browser all works fine, and I can even use query-vars such as: http://domain.com/blog/wp-content/themes/wovies-bones/getmovies.php?actor=x And it works fine, I get single post that has custom taxonomy actor = x.
But when I try to load same using ajax, it behaves differently and ignoring my get request returns all posts...
Any ideas what is happening?
ajax-jquery part:
$.ajax({
url: templatePath + "getmovies.php",
type: "GET",
data: filters_get,
cache: false,
success: function (data){
console.dir(data);
}
});
And php part:
/* Define these, So that WP functions work inside this file */
define('WP_USE_THEMES', false);
require('../../../wp-blog-header.php');
?>
<div id="container">
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="movie">
<a href="<?php the_permalink() ?>">
<?php
if (has_post_thumbnail()) {the_post_thumbnail('homepage-preview');}
else {echo '<img src="' . get_bloginfo( 'stylesheet_directory' ) . '/images/default-poster.jpg" />';}
?>
<p class="comments"><?php comments_number('0 review','1 review','% reviews'); ?></p>
<div class="description">
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
</div>
</a>
</div>
<?php endwhile; else: ?>
<!-- No movies found -->
<?php endif; ?>
</div><!-- End #container -->
filters_get looks like this: ?actor=x&
This way, you just load WordPress and run your own PHP file. Basicaly, I think you should redefine your WP_Query like this :
/*Define these, So that WP functions work inside this file */
define('WP_USE_THEMES', false);
require('../../../wp-blog-header.php');
global $wp_query;
$args = array(
'post_type' => 'my-post-type',
'my_tax' => $_GET['my_tax']
);
$wp_query = new WP_Query($args);
// Your template stuff
And if you're using AJAX to get your posts, you'd better use a hooked function as it is described in WordPress Codex :
add_action('wp_ajax_get_my_cpt', 'get_my_cpt');
add_action('wp_ajax_nopriv_get_my_cptn', 'get_my_cpt');
function get_my_cpt() {
$args = array(
'post_type' => 'my-post-type',
'my_tax' => $_GET['my_tax']
);
$cpts = get_posts($args);
if(empty($cpts)) {
_e('No custom post to show');
exit;
}
foreach($cpts as $cpt) {
// Do you stuff to display your custom posts
}
}
Then you will have to use this kind of url in your AJAX call : http://www.domain.tld/wp-admin/admin-ajax.php?action=get_my_cpt&my_tax=keyword

Resources