I'm building a shopping page that list all the stores. I've created a sidebar with all the categories and a list with pagination. This list is generated by a wordpress function in my theme-functions.php, but when I click in any category, I'm redirected to another page (to http://<domain>/store from http://<domain>/category). So I created a JavaScript function to prevent the link action using preventDefault and get his href value and set it as variable to pass it to the function via Ajax.
My question is: there is a way to pass this variable and refresh the wordpress function on the same page to show this list?
Code below:
Wordpress theme-function.php
function storeSingle() {
$catUrl = $_POST['catUrl'];
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'lojas' ,
'posts_per_page' => 5,
'orderby' => 'title',
'order' => 'ASC',
'paged' => $paged,
'category_name' => $catUrl
);
/* Added $paged variable */
$exec = new WP_Query($args);
if($exec->have_posts()):
echo '<ul class="single-store">';
while($exec->have_posts()):
$exec->the_post();
$categories = get_the_category($post->ID);
echo "<li class='store-box'>";
echo '<a href=" '. get_the_permalink() .' ">';
echo '<h1>';
echo the_title();
echo '</h1>';
echo "</a>";
echo '<div class="store-info-box">';
echo '<span>';
echo '<i class="fa fa-map-marker" aria-hidden="true"></i>';
echo the_field('localizacao');
echo '</span>';
echo '<span>';
echo $categories[0]->name;
echo '</span>';
echo '</div>';
echo "</li>";
endwhile;
echo '</ul>';
if (function_exists(custom_pagination)) {
custom_pagination($exec->max_num_pages,"",$paged);
}
endif;
}
add_action('wp_ajax_catUrl', 'catUrl');
add_action('wp_ajax_nopriv_catUrl', 'catUrl');
JavaScript function
$('.cat-item').on('click', 'a', function(e){
e.preventDefault();
var catUrl = this.href;
catUrl = catUrl.split('/');
$.ajax({
type: "POST",
url: 'http://localhost/asv/shopping/wp-admin/admin-ajax.php',
dataType: 'json',
data: {
action: catUrl,
catUrl: catUrl[5]
},
success: function(data){
response(data),
console.log('test' + data);
}
});
});
I've searched this a lot but I didn't find out how to use ajax in wordpress properly.
if you are getting results in you console.log('test' + data); seems like you just need to display this results back in your HTML container by replacing the current content with your ajax response.
Related
I am currently working on my own personal portfolio website. I've made a custom post type using Pods to create portfolio items and i want to use the wordpress tags as the filter.
I've successfully received the portfolio items and the filters. But how can i make them clickable/filterable ? Everything I've found includes portfolio plugins etc. But I don't want to use that, is just want to create my own simple filterable portfolio.
Can someone help me out ?
Here is the code:
Filters:
$tags = get_tags();
$html = '<div class="post_tags centered-content"> Alles';
foreach ( $tags as $tag ) {
$tag_link = get_tag_link( $tag->term_id );
$html .= "<a href='#{$tag->slug}' title='{$tag->name} filter' class='button outline {$tag->slug}'>";
$html .= "{$tag->name}</a>";
}
$html .= '</div>';
echo $html;
Portfolio items:
function getPortfolio(){
global $post;
$portfolioargs = array(
'posts_per_page' => 999,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'portfolio',
'post_status' => 'publish',
'suppress_filters' => false
);
$portfolioitems = get_posts($portfolioargs);
foreach ($portfolioitems as $portfolioitem) {
$feat_image = wp_get_attachment_image_src( get_post_thumbnail_id($portfolioitem->ID), 'full' );
$tags = wp_get_post_tags($portfolioitem->ID);
echo '<div class="card portfolio">';
echo '<a href="'. get_the_permalink($portfolioitem->ID) .'">';
echo '<figure>';
echo '<img src="'. pods_image_url($feat_image, 'card') .'"/>';
echo '</figure>';
echo '</a>';
echo '<div class="card-title-wrapper">';
echo '<h3>'. $portfolioitem->post_title .'</h3>';
echo '<span class="card-subtitle mdi mdi-tag-outline mdi-15px">';
foreach ( $tags as $tag ) {
echo $tag->name . ', ';
}
echo '</span>';
echo '</div>';
echo '<div class="card-content">';
echo '<p>'. $portfolioitem->post_content .'</p>';
echo '</div>';
echo '<div class="card-actions">';
echo 'Lees meer';
echo 'Bekijk website';
echo '</div>';
echo '</div>';
}
}
Check the screenshot here
In my opinion the best way to make these tags work as a filter is "AJAX".
here i have written your "tags" code to work as a javascript filter . hope it helps.
at first let rewrite your code to show tags , i add a line (created an input to send it with AJAX):
$tags = get_tags();
$html = '<div class="post_tags centered-content">
<input type='hidden' name='tag_filter' value=''>
Alles';
foreach ( $tags as $tag ) {
$tag_link = get_tag_link( $tag->term_id );
$html .= "<a title='{$tag->name} filter' class='button outline filterBtn {$tag->slug}'>";
$html .= "{$tag->name}</a>";
}
$html .= '</div>';
echo $html;
then we will have our javascript (jquery) to send the selected tag values:
$('.filterBtn').click(function(){
var selected_tag = $(this).text();
$('input[name="tag_filter"]').val(selected_tag);
$.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_fetch', filter: $('input[name="tag_filter"]').val()},
success: function (data) {
$('#yourResultDIV').html(data);
}
});
})
the next part is our PHP code to produce result base on our selected filter: (in functions.php)
add_action('wp_ajax_data_fetch' , 'resultsLoad');
add_action('wp_ajax_nopriv_data_fetch','resultsLoad');
function resultsLoad(){
$filter = $_POST['filter'];
global $post;
$portfolioargs = array(
'posts_per_page' => 999,
'orderby' => 'date',
'order' => 'DESC',
'post_type' => 'portfolio',
'post_status' => 'publish',
'tag' => $filter
);
$portfolioitems = get_posts($portfolioargs);
foreach ($portfolioitems as $portfolioitem) {
$feat_image = wp_get_attachment_image_src( get_post_thumbnail_id($portfolioitem->ID), 'full' );
$tags = wp_get_post_tags($portfolioitem->ID);
echo '<div class="card portfolio">';
echo '<a href="'. get_the_permalink($portfolioitem->ID) .'">';
echo '<figure>';
echo '<img src="'. pods_image_url($feat_image, 'card') .'"/>';
echo '</figure>';
echo '</a>';
echo '<div class="card-title-wrapper">';
echo '<h3>'. $portfolioitem->post_title .'</h3>';
echo '<span class="card-subtitle mdi mdi-tag-outline mdi-15px">';
foreach ( $tags as $tag ) {
echo $tag->name . ', ';
}
echo '</span>';
echo '</div>';
echo '<div class="card-content">';
echo '<p>'. $portfolioitem->post_content .'</p>';
echo '</div>';
echo '<div class="card-actions">';
echo 'Lees meer';
echo 'Bekijk website';
echo '</div>';
echo '</div>';
}
die();
}
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've attempted to setup a 'load more' button in WordPress. Simple idea, you press the button and it loads more posts using AJAX without reloading the page or needing to use pagination.
I followed a previous article on SO and have managed to get it to mostly work.
So far, I've been able to get additional posts loading fine, but for some reason, they are being duplicated. I had a look in the Networks tab and it seems each time I press the button, admin-ajax.php runs twice which I suspect is what's causing the duplication. Unfortunately, I'm not too sure what I need to change to resolve this.
It would also be really helpful to know how to get this working for custom post types as well as normal posts. On my website, I've got two post types, Standard blog posts and a custom 'Projects' post type. Each has its own page and own loop, how would I modify the above to get it to work for both? Would I need to write out the whole thing twice or maybe It's something simpler?
Any ideas guys?
Here is the HTML:
<section id="ajax-posts" class="layout">
<?php get_template_part( 'content', 'blog' ); ?>
</section>
<div class="load-more layout">
<a id="more_posts" class="button"><span class="icon-plus"></span></a>
</div>
Here is the main loop:
<?php
$postsPerPage = 1;
$args = array(
'post_type' => 'post',
'posts_per_page' => $postsPerPage
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php the_post_thumbnail();?>
<div class="inner-text">
<h4 class="post-title"><?php the_title(); ?></h4>
<h5><span class="icon-calendar"></span> <?php the_date(); ?></h5>
<?php the_excerpt(); ?>
Read More<span class="icon-arrow-right2"></span>
</div>
</article>
<?php endwhile; wp_reset_postdata(); ?>
Here is my functions.php:
function wpt_theme_js() {
wp_enqueue_script( 'bigredpod-script', get_template_directory_uri() . '/js/main.js', array( 'jquery' ), '', true );
wp_localize_script( 'bigredpod-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'bigredpod'),
));
}
wp_localize_script( 'bigredpod-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'bigredpod'),
));
function more_post_ajax(){
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 1;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
header("Content-Type: text/html");
$args = array(
'suppress_filters' => true,
'posts_per_page' => $ppp,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop -> have_posts()) : while ($loop -> have_posts()) : $loop -> the_post();
$out .=
'<article id="post-'. get_the_ID().'" class="'. implode(' ', get_post_class()) .'">
'.get_the_post_thumbnail().'
<div class="inner-text">
<h4 class="post-title">'.get_the_title().'</h4>
<h5><span class="icon-calendar"></span> '.get_the_date().'</h5>
<p>'.get_the_excerpt().'</p>
Read More<span class="icon-arrow-right2"></span>
</div>
</article>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax'); ?>
Here is my JS:
jQuery(document).ready(function($) {
var ppp = 1; // Post per page
var pageNumber = 1;
function load_posts(){
pageNumber++;
var str = '&pageNumber=' + pageNumber + '&ppp=' + ppp + '&action=more_post_ajax';
$.ajax({
type: "POST",
dataType: "html",
url: ajax_posts.ajaxurl,
data: str,
success: function(data){
var $data = $(data);
if($data.length){
$("#ajax-posts").append($data);
$("#more_posts").addClass('posts_loading');
} else{
$("#more_posts").removeClass('posts_loading').addClass('no_more_posts');
}
},
error : function(jqXHR, textStatus, errorThrown) {
$loader.html(jqXHR + " :: " + textStatus + " :: " + errorThrown);
}
});
return false;
}
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
load_posts();
});
});
You have put twice
wp_localize_script( 'bigredpod-script', 'ajax_posts', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'noposts' => __('No older posts found', 'bigredpod'),
));
In your wpt_theme_js() function. This is probably what causes the ajax to load twice.
I am trying to load the individual post information on click into the page when clicking the post title. I have managed to get my script to loop through the titles in the post array and on click load the post titles once more into a div. I want this to load the individual post information instead on click.
PHP Post Array Functions -
add_action( "wp_ajax_success_stories", "sa_get_paginated_posts" );
add_action( "wp_ajax_nopriv_success_stories", "sa_get_paginated_posts" );
function sa_get_paginated_posts(){
$args = array(
'posts_per_page' => -1,
'post_type' => 'success-stories',
'orderby' => 'post_date',
'order' => 'DESC'
);
$the_query = new WP_Query( $args );
$queryitems = $the_query->get_posts();
$alldata = array();
if ($queryitems){
foreach ($queryitems as $query_item){
$success_story = array();
$success_story["ID"] = $query_item->ID;
$success_story["title"] = $query_item->post_title;
$alldata[] = $success_story;
}
}
$encoded_data = json_encode($alldata);
echo $encoded_data;
die();
}
function sa_get_posts($post_amount, $post_type){
$args = array(
'posts_per_page' => $post_amount,
'post_type' => $post_type,
'offset' => 0,
'orderby' => 'post_date',
'order' => 'ASC'
);
Using this function to loop through -
<? if ($success_stories): //success story posts ?>
<ul class="small-block-grid-3">
<? foreach ($success_stories as $success_story):
$title = $success_story->post_title; ?>
<li><a data-id="<? echo $success_story->ID; ?>" class="success-extra" href="#" title=""><? echo $title; ?></a></li>
<? endforeach; ?>
</ul>
<div id="success-list"></div>
<a class="success-close" href="#" title="">CLOSE</a>
<? endif; ?>
Javascript/ AJAX Call
var $json_response_box = $("#success-list");
function get_ajax_success_posts() {
//this line gets the id attribute from the link
var current_story = $(this).attr("data-id");
console.log(current_story);
jQuery.ajax({
type: "GET",
url: "WORDPRESSDIRECTORY/admin-ajax.php",
cache: true,
data: {
action: "success_stories"
},
dataType: "JSON",
success: function(data) {
var arrayLength = data.length;
for (var i = 0; i < arrayLength; i++) {
var success_id = data[i].ID;
var success_title = data[i].title;
console.log(success_id);
story = '<ul>';
story += '<li>';
story += success_title;
story += '</li>';
story += '</ul>';
$json_response_box.append(story).fadeIn(1000);
}
},
error: function(errorThrown) {
console.log("fail-posts");
}
});
}
Appreciate your suggestions,
D
If I understand your question correctly, you should just add another php function and AJAX call, to get the post on click, something like this (I also added nonce to add some secutiry, it's always a good idea to add that to your ajax calls)
HTML:
<li><a data-id="<? echo $success_story->ID; ?>" data-nonce="<?php wp_create_nonce('get_post'.$success_story->ID); ?>" class="success-extra" href="#" title=""><? echo $title; ?></a></li>
PHP:
add_action( "wp_ajax_sa_get_post", "sa_get_post" );
add_action( "wp_ajax_nopriv_sa_get_post", "sa_get_post" );
function sa_get_post(){
if ( ! wp_verify_nonce( $nonce, 'get_post_'.$POST['id'] ) ) {
// This nonce is not valid.
$response['status'] = 'fail';
} else {
// The nonce was valid.
$post = get_post($POST['id']);
$response['status'] = 'success';
$response['post'] = $post;
}
echo json_encode($response);
exit(); // this is needed, as otherwise the AJAX returns an extra 0
}
JS:
$('.success-extra').on('click', function () {
jQuery.ajax({
type: "POST",
url: "WORDPRESSDIRECTORY/admin-ajax.php",
cache: false,
data: {
action: "sa_get_post",
id: $(this).attr('data-id'),
nonce: $(this).attr('data-nonce')
},
success: function(data) {
var result = $.parseJSON(data);
if (result.status != 'success') {
// display error messago or something
} else {
// do whatever you want with your result.post
}
}
})
Hope this helps.
Hi I am working with advanced custom fields with wordpress and im trying to fix the date to show : 24/01/201 instead of 01/24/2013
I have been looking at the ACF site but I can't seem to find why it is doing this.
please find attached my code :)
<?php
// start query
$query_args = array(
// number of featured items to show
'posts_per_page' => '-1',
'post_type' => 'product',
);
$args = array(
'meta_key' => 'time_&_date',
'orderby' => 'meta_value_num',
'order' => 'DESC'
);
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
$date = DateTime::createFromFormat('Ymd', get_field('time_&_date'));
echo $date->format('M d, Y');
endwhile;
// start loop
$wp_query = new WP_Query($query_args);
if ($wp_query->have_posts()) {
echo '<ul class="eventslist">';
echo '</br>';
echo '</br>';
// start while
while($wp_query->have_posts()) : $wp_query->the_post();
$_product = new jigoshop_product(get_the_ID());
echo '<li>';
// Event container
echo '<a href="'.get_permalink().'">';
// Event title
echo '<div class="loop_title lightlinksnounderline"> <span>•</span>' . the_title('','',false);
echo '</a>';
echo '</div>';
echo '<h3 class="field_title_loop">Date & Time: '; the_field('time_&_date');
echo '</h3>';
echo '<div class="cart_button">' ; do_action('jigoshop_after_shop_loop_item', $post, $_product );
echo '</div>';
echo '</li>';
echo '<div class="price_cart">' ; do_action('jigoshop_after_shop_loop_item_title', $post, $_product);
echo '</div>';
echo '</br>';
echo '<div class="cart_line">';
echo '</div>';
// end while
endwhile;
echo '</ul>';
// end loop
// reset query
wp_reset_query();
}
?>
shouldn't your $date->format be (d M Y) for this?