Wordpress Dynamic Posts with AJAX - javascript

I'm would like to make this code load using the post ID of the item clicked inside the internal UL. How can this be done?
Currently creates a side menu containing the specified categories.
After which it creates a ul sub menu within with each li being a post from the category. The post from the category is also inserted using ajax into the specified div.
I need for the posts that are shown in the div and side menu to also load into the div when they're clicked.
Currently I am using cat ids to create the menu and insert into the div. I need to have post ids working from the sub menu.
It's rather difficult to explain.
index.php
<?php
$args = array(
'include' => '4,5,7,8'
);
$categories = get_categories($args);
?>
<ul id="category-menu" class="nav nav-list">
<?php
foreach ( $categories as $cat ) { ?>
<?php $show = 'cat=' . $cat->term_id; ?>
<li id="cat-<?php echo $cat->term_id; ?>">
<a class="<?php echo $cat->slug; ?> ajax tree-toggle" onclick="cat_ajax_get('<?php echo $cat->term_id; ?>');" href="#">
<?php echo $cat->name; ?>
</a>
<ul class="nav nav-list tree" style="display: none">
<?php query_posts($show); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php $post_id = $wp_query->post->ID; echo $post_id; ?>
<li>
<a class="ajax" onclick="cat_ajax_get('<?php echo $post_id ?>');" href="#"><?php the_title(); ?></a>
</li>
<?php endwhile; endif; ?>
</ul>
</li>
header.php
<script>
function cat_ajax_get(catID) {
jQuery("a.ajax").removeClass("current");
jQuery("a.ajax").addClass("current"); //adds class current to the category menu item being displayed so you can style it with css
var ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ); //must echo it ?';
jQuery.ajax({
type: 'POST',
url: ajaxurl,
data: {"action": "load-filter", cat: catID },
success: function(response) {
jQuery("#category-post-content").html(response);
return false;
}
});
}
</script>
functions.php
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 () {
$cat_id = $_POST[ 'cat' ]; $args = array (
'cat' => $cat_id,
'posts_per_page' => 10,
'order' => 'DESC'
);
$posts = get_posts( $args );
ob_start ();
foreach ( $posts as $post ) {
setup_postdata( $post ); ?>
<div id="post-<?php echo $post->ID; ?> <?php post_class(); ?>">
<h1 class="post-title"><?php the_title(); ?></h1>
<div id="post-content">
<?php the_content(); ?>
</div>
</div>
<?php
}
wp_reset_postdata();
$response = ob_get_contents(); ob_end_clean();
echo $response;
die(1);
}

Related

Ajax category filter a WP Post Loop with button click

I have a simple post loop with buttons that list all possible categories. The categories are listed as following:
<div class="filter-nav">
<?php
global $post;
$cat_args=array(
'post_type' => 'post',
);
$categories=get_categories($cat_args);
foreach($categories as $category) {
echo '<button type="button" data-category="' . $category->slug . '">' . $category->name . '</button>';
}
?>
</div>
And a WP loop as following:
<?php
$args = array(
'post_type' => 'post',
'orderby' => 'date',
'order' => 'ASC',
'status' => 'publish',
'posts_per_page' => -1,
);
$post = new WP_Query($args);
?>
<?php if ( $post->have_posts() ) { ?>
<div class="feed-slider">
<?php
while ($post->have_posts()) {
$post->the_post(); ?>
<div class="feed-column">
<?php if ( has_post_thumbnail() ) { ?>
<div class="feed-thumb">
<div class="image-overlay transition"></div>
<?php the_post_thumbnail( 'medium_large' ); ?>
</div>
<?php } ?>
<div class="feed-meta">
<p class="feed-categories">
<?php foreach ( ( get_the_category() ) as $category ) {
echo $category->cat_name . ' ';
} ?>
</p>
<h3 class="quicksand font-bold transition"><?php the_title(); ?></h3>
</div>
</div>
<?php
wp_reset_postdata();
}; ?>
</div>
<?php } else { ?>
<p class="no-content">Nothing found!</p>
<?php } ?>
What would be the approach to be done so that when one of the categories buttons is clicked, the loop is run one more time, filtering it with only the selected category?

Wordpress AJAX Hide Load More Button

I've created a custom WP-Query with the possibility to load more posts on button click with AJAX. Everything works fine. Now I'd like to hide the button if there are less or exactly four posts. The button should also disappear if there are all posts loaded with AJAX.
I'd be very thankful if somebody could help me! Thank you in advance.
My PHP:
<div class="masonry category-single-magazin__inner entry-content">
<?php $args = array('category_name' => 'magazin', 'posts_per_page' => '4', 'paged' => 1, 'orderby'=> 'date', 'order' => 'DESC'); $custom_query = new WP_Query( $args ); while($custom_query->have_posts()) : $custom_query->the_post(); ?>
<article class="object <?php if ( get_field( 'beitragsfarbe' ) == 1 ) { echo 'object--blue'; } else { echo 'object--yellow'; } ?>" id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink(); ?>">
<div class="lazy object__inner" data-src="<?php echo get_the_post_thumbnail_url(); ?>">
<div class="overline">
<h6>
<?php $posttags = get_the_tags(); if ($posttags) { foreach($posttags as $tag) { echo $tag->name . ' '; }}?>
</h6>
</div>
<div class="object__inner__text content-no-margin">
<h4>
<?php the_title(); ?>
</h4>
<p class="textlink" href="<?php the_permalink(); ?>">Mehr erfahren</p>
</div>
</div>
</a>
</article>
<?php endwhile ?>
</div>
<button class="load-more reload-masonry button-full button-full--yellow">
<div class="button-full__inner">Mehr anzeigen</div>
</button>
<script type="text/javascript">
jQuery(document).ready(function() {
var ajaxurl = "<?php echo admin_url( 'admin-ajax.php' ); ?>";
var page = 2;
var pageNumber = <?php echo count_cat_post('magazin')/4; ?>;
$('.load-more').on('click', function() {
var data = {
'action': 'load_posts_by_ajax',
'page': page,
'security': '<?php echo wp_create_nonce("load_more_posts"); ?>',
};
$.post(ajaxurl, data, function(response) {
$('.masonry').append(response);
page++;
});
});
if (page == (parseInt(pageNumber) - 1)) {
$('.load-more').hide();
}
});
</script>
My functions.php:
function load_posts_by_ajax_callback() {
check_ajax_referer('load_more_posts', 'security');
$paged = $_POST['page'];
$args = array(
'category_name' => 'magazin',
'posts_per_page' => '4',
'paged' => $paged,
'orderby'=> 'date',
'order' => 'DESC'
);
$custom_query = new WP_Query( $args ); while ( $custom_query->have_posts() ) : $custom_query->the_post() ?>
<article class="object <?php if ( get_field( 'beitragsfarbe' ) == 1 ) { echo 'object--blue'; } else { echo 'object--yellow'; } ?>" id="post-<?php the_ID(); ?>">
<a href="<?php the_permalink(); ?>">
<div class="lazy-ajax object__inner" style="background-image:url('<?php echo get_the_post_thumbnail_url(); ?>')">
<div class="overline"><h6><?php $posttags = get_the_tags(); if ($posttags) { foreach($posttags as $tag) { echo $tag->name . ' '; }}?></h6></div>
<div class="object__inner__text content-no-margin">
<h4><?php the_title(); ?></h4>
<p class="textlink" href="<?php the_permalink(); ?>">Mehr erfahren</p>
</div>
</div>
</a>
</article>
<?php endwhile ?>
<?php wp_die();}
I will not write whole code but here is the possible solution. First you need to know how many pages of post are there, you can get total number of post by using following Wordpress function
<?php
$count_posts = wp_count_posts();
/*this function only works with post type is post .
if you using for categories first you need to find how many
post are there in that categories.*/
?>
If you divide total count_post by number of post per page you will get total number of page.
Now you can simply check it in your javascript like this.
var pageNumber = <?php echo (wp_count_posts()/4); ?>
//make sure pageNumber is number not string can use javascript parseInt function
jQuery(document).ready(function() {
if(page==(parseInt(pageNumber)-1)){
//send ajax request to get last page post but hide the button
}
});
I hope this will help you. Let me know if anything is not clear.
Solved it by myself. Although thank you for guiding me to the solution!
I've created a function for this with jQuery counting the visible posts:
function hideButton(){
var poststotal = <?php echo count_cat_post('magazin'); ?>;
var postsvisible = $('.masonry > article').length;
if (poststotal == postsvisible) {
$('.load-more').addClass('hidden');
}
};

.addClass on element in functions.php

I can't figure out how to solve this. In header.php I have this javascript
<script language="javascript">
$(document).ready(function() {
$(".catfilter").click(function(){
$("#category-post-content").addClass("shownewsajax");
$(".sasasa").addClass("rrrrrrrrrrrr");
});
});
</script>
It works perfectly for #category-post-content, but since the "sasasa" element is in functions.php (into add_action function), the class "rrrrrrrr" will not be added on .catfilter click.
Any ideas of how to make it work even if element that need the class is in functions.php?
This is the code in functions.php where .sasasa is
///Ajax post filtering by category
add_action( 'wp_ajax_load-filter', 'prefix_load_cat_posts' );
function prefix_load_cat_posts () { ?>
<div class="allposts row blogrow">
<?php ob_start ();
$query = new WP_Query(
$args = array (
'showposts' => 999,
'cat' => $cat_id = $_POST[ 'cat' ]
) );
$posts = get_posts( $args );
foreach ( $posts as $post ) {
setup_postdata( $post );
?>
<div class="sasasa news-wrap">
<div class="newsflex">
<div class="postfeat"> <?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID ), 'my-custom-thumb' ); ?>
<img src="<?php echo $image[0]; ?>">
<?php endif; ?>
</div>
<div class="postinfo">
<div class="postcat">
<?php foreach( (get_the_category($post)) as $category) { ?> <?php echo $category->cat_name; ?><?php } ?>
</div>
<h4 class="newstitle"><?php echo $post->post_title; ?></h4>
<div class="postexc"><?php $excerpt = get_the_excerpt($post); echo $excerpt;?></div>
READ MORE <span class="rightarrow"></span>
</div>
</div>
</div>
<?php
} wp_reset_postdata(); ?>
</div>
<div class="next-button">Load More Posts CAT</div>
<? $response = ob_get_contents();
ob_end_clean();
echo $response;
die(1);
}
$(document).ready(function() {
$(".catfilter").click(function(){
$("#category-post-content").addClass("shownewsajax");
$(".sasasa").addClass("rrrrrrrrrrrr");
});
});
try this. this will execute when everything in your page is loaded.
The .sasasa elements are added dynamically using Ajax. So when the jQuery function is parsed, those elements aren't present. If you start from the document and .find() those elements, it should work.
.catfilter seems to be static...
<script language="javascript">
$(document).ready(function() {
$(".catfilter").click(function(){
$("#category-post-content").addClass("shownewsajax");
$(document).find(".sasasa").addClass("rrrrrrrrrrrr");
});
});
</script>

500 internal server error jQuery and WordPress

I am attempting to use ajax in my WordPress project to dynamically load videos depending on their post ID. At the moment when I click on the video link I get the error 500 internal server error. I send the post ID via ajax to a PHP script, there I attempt to get the post meta of the post using the ID and then display the video url stored within that post meta. Can anyone see where I am going wrong?
Below is my shortcode function
/**
* Render the HTML code for the speaker interviews
*
* #return $output string The HTML code to be rendered, caught by ob_start();
*/
function test_view_shortcode_fn( $attributes ) {
ob_start();
$args = array( 'post_type' => 'test_video',
'post_status' => 'publish',
'posts_per_page' => 1
);
$main_video = new WP_Query( $args );
if( $main_video->have_posts() ) : while ( $main_video->have_posts() ) : $main_video->the_post();
$video = get_post_meta( get_the_ID(), '_video_url' );
$poster = get_post_meta( get_the_ID(), '_video_poster' );
?>
<div class="row">
<div class="columns small-12 medium-7 large-8 video-single">
<?php echo do_shortcode("[video src='" . $video[0] . "' poster='" . $poster[0] . "' width='800' height='640' preload='none' ]") ?>
<ul class="channel-share">
<li><a class="text-center" href="https://www.facebook.com/sharer/sharer.php?u=<?php the_permalink(); ?>" title="Share on Facebook" target="_blank"><i class="fa fa-facebook"></i></a></li>
<li><a class="text-center" href="https://twitter.com/home?status=<?php the_title(); ?>-<?php the_permalink(); ?>" title="Share on Twitter" target="_blank"><i class="fa fa-twitter"></i></a></li>
<li><a class="text-center" href="https://www.linkedin.com/shareArticle?mini=true&url=<?php the_permalink(); ?>&title=<?php the_title(); ?>" title="Share on Linked In" target="_blank"><i class="fa fa-linkedin"></i></a></li>
<li><a class="text-center" href="https://plus.google.com/share?url=<?php the_permalink(); ?>" title="Share on Google+" target="_blank"><i class="fa fa-google-plus"></i></a></li>
</ul>
<?php the_content(); ?>
</div>
<div class="columns small-12 medium-5 large-4 video-single">
<aside>
<ul class="iot-channel-sidebar">
<?php
$args = array(
'post_type' => 'test_video',
'posts_per_page' => 5,
'orderby' => 'rand'
);
$channel = new WP_Query( $args );
if( $channel->have_posts() ) : while( $channel->have_posts() ) : $channel->the_post();
$poster = get_post_meta( get_the_ID(), '_video_poster' );
$id = get_the_ID();
$video_ajax_url = VIDEO_URI . '/inc/video_ajax.php';
?>
<?php if( $poster ) { ?>
<li class="video-archive-item">
<div class="video-poster">
<a title="<?php the_title(); ?>" id="video_<?php echo $id; ?>">
<img src="<?php echo $poster[0]; ?>" alt="<?php the_title(); ?>" />
</a>
</div>
<div class="video-title">
<a title="<?php the_title(); ?>">
<h4><?php the_title(); ?></h4>
</a>
</div>
</li>
<script type="text/javascript">
jQuery("#video_<?php echo $id; ?>").click(function(){
jQuery.ajax({
url: '<?php echo $video_ajax_url; ?>',
type: 'POST',
data: {id: '<?php echo $id; ?>'},
success: function(data){
$('.wp-video').html(data); // Load data into a <div> as HTML
}
});
});
</script
<?php } ?>
<?php endwhile; endif; ?>
</ul>
</aside>
</div>
</div>
<?php endwhile; endif;
$output = ob_get_clean();
return $output;
}
My ajax:
<?php
global $post;
$postID = $_POST['id'];
setup_postdata( $postID );
echo $postID;
$video = get_post_meta( $postID, '_video_url' );
$poster = get_post_meta( $postID, '_video_poster' );
echo do_shortcode("[video src='" . $video[0] . "' poster='" . $poster[0] . "' width='800' height='640' preload='none' ]")
?>
I finally realised this was due to the fact that WordPress wasn't being loaded on the PHP file being called via Ajax.
To fix this I included wp-load.php at the top of my PHP script the Ajax was calling and it works perfectly. Here's what I added to my PHP file.
<?php
$filename = "../../../../wp-load.php";
include($filename);
?>

Show/Hide multiple WordPress entries

I have some code that pulls in wordpress posts, I want to just pull in the image. Then when the image is clicked, more info to appear in a div at the right side of the page. Been trying a few things myself but can't seem to get it to work correctly.
This is my wordpress code, i'm incrementing the posts to add showdiv-1, showdiv-2 etc... then incrementing the information div to be storeinfo-1, storeinfo-2 etc...
Clickable logos:
<ul class="store_list">
<?php $i = 1; ?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts('cat=3'.$cat.'&order=ASC&showposts=100&paged=' . $paged);
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li class="one-third nomargin">
<a id="showdiv-<?php echo $i; ?>" class="store-logo" title="View <?php echo $post->post_title; ?> shop info"><?php
$thumbnail_id = get_post_meta($post->ID, 'Store Logo', true);
echo wp_get_attachment_image($thumbnail_id, 'Store Logo');
?></a>
</li>
<?php $i++; ?>
<?php endwhile; else: ?>
<p><?php _e('No shops to view in this category.'); ?></p>
<?php endif; ?>
</ul>
Divs to show when logo is clicked:
<?php $m = 1; ?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts('cat=3'.$cat.'&order=ASC&showposts=100&paged=' . $paged);
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="storeinfo-<?php echo $m; ?>">
<h1 class="shop-name"><?php echo $post->post_title; ?></h1>
<p class="shop-telephone nop">Tel: <?php getCustomField('Telephone'); ?></p>
<div class="shop-openinghours">
<?php the_content(); ?>
</div>
<p class="shop-website nop"> <a target="_blank" href="http://<?php getCustomField('Website'); ?>">Visit Site</a></p>
</div>
<?php $m++; ?>
<?php endwhile; else: ?>
<p><?php _e('No shops to view in this category.'); ?></p>
<?php endif; ?>
Thanks in advance!
You can do that with following steps;
You have already give ids, ok. Those images are related to specific information divs.(I assume store-info-* divs are hidden first). Simply write a jquery function. I am giving your updated code, and my new implemented jquery code.
EDIT: In order to hide previous ones when you click show info, I have added a class to store-info-* divs and added jquery code to my implementation to hide all open stores and show clicked one.
<ul class="store_list">
<?php $i = 1; ?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts('cat=3'.$cat.'&order=ASC&showposts=100&paged=' . $paged);
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<li class="one-third nomargin">
<a id="showdiv-<?php echo $i; ?>" class="store-logo" title="View <?php echo $post->post_title; ?> shop info" class="images"><?php
$thumbnail_id = get_post_meta($post->ID, 'Store Logo', true);
echo wp_get_attachment_image($thumbnail_id, 'Store Logo');
?></a>
</li>
<?php $i++; ?>
<?php endwhile; else: ?>
<p><?php _e('No shops to view in this category.'); ?></p>
<?php endif; ?>
</ul>
<?php $m = 1; ?>
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts('cat=3'.$cat.'&order=ASC&showposts=100&paged=' . $paged);
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div id="storeinfo-<?php echo $m; ?>" style="display:none;" class="stores">
<h1 class="shop-name"><?php echo $post->post_title; ?></h1>
<p class="shop-telephone nop">Tel: <?php getCustomField('Telephone'); ?></p>
<div class="shop-openinghours">
<?php the_content(); ?>
</div>
<p class="shop-website nop"> <a target="_blank" href="http://<?php getCustomField('Website'); ?>">Visit Site</a></p>
</div>
<?php $m++; ?>
<?php endwhile; else: ?>
<p><?php _e('No shops to view in this category.'); ?></p>
<?php endif; ?>
jQuery(function ($) {
$(".images").on('click', function() {
$(".stores").hide();
var idObj = $(this).attr("id").split("-");
var id = idObj[1];
$("#storeinfo-" + id).show();
});
});

Categories

Resources