Need to fire an alert after "page load" on same page - javascript

This is a WordPress site and I have a template that renders all posts in a list at this URL http://www.example.com/articles. When the user clicks on a post title, it loads the content of the post using the same template but with a different URL http://www.example.com/articles/?article_id=298. What I cannot figure out is how to show an alert after the page loads the post content. I've tried setTimeout, $(document).ready, $(window).load, window.onload=funtion(), and now $(document).on("pagecontainerload",function().
JQuery/JavaScript
$('a.open-alert').click(function() {
$(document).on("pagecontainerload",function(){
window.alert('hey');
});
});
HTML
<?php
$tearsheet = get_query_var('article_id');
if($tearsheet != '') {
echo 'there is something here';
} else {
$args = array(
'post_type' => 'post',
'posts_per_page' => -1,
);
$query = new WP_Query( $args );
if($query->have_posts()) :
while($query->have_posts()) :
$query->the_post();
?>
<div>
<?php $id = get_the_ID(); ?>
<?php $title = get_the_title(); ?>
<a class="open-alert" href="<?php bloginfo('url'); echo '/find-articles/?article_id='.$id; ?>"><?php echo $title; ?></a>
</div>
<?php
endwhile;
endif;
}
?>

The click handler will never be executed, since the page unloads and a new page is loaded - the one in the link <a class="open-alert" href="<?php bloginfo.... You may have a return false in the onclick handler, but that would mean, the link will not be executed.
In order to do this dynamically, consider reloading only the container within that page, containing the post text by some Ajax functionality.

Related

Speed up admin-ajax.php request in CPT filters

I have custom post types with JS filtering (based on category). There are simple html boxes + php code with ACF fields what display after select category.
Problem is it take 1 second or more to load all this html boxes so its not so smooth.
This is my JS (file filters.js):
(function($){
$(document).ready(function(){
$(document).on('click', '.js-filter-item > a', function(e){
e.preventDefault();
var category = $(this).data('category');
$.ajax({
url:wp_ajax.ajax_url,
data: { action: 'filter', category: category },
type: 'post',
success: function(result) {
$('.js-filter').html(result);
},
error: function(result) {
console.warn(result);
}
});
});
});
})(jQuery);
This is html of box what is loaded (file content_pozice_box.php)
<a href="<?php echo get_permalink();?>"><div class="vypis_pozice">
<div class="projekt-wrapper">
<?php
$projekt = get_field('projekt');
if( get_field('projekt') == 'XXX' ) {
?>
<div class="logo-wrapper">
<img src="https://YYY.png" class="logo-wrapper-img">
</div><?php
}
if( get_field('projekt') == 'YYY' ) {
?>
<div class="logo-wrapper">
<img src="https://XXX.png" class="logo-wrapper-img">
</div>
<?php
}
?>
<div class="field_projekt"><h3><?php the_field('projekt');?></h3><div class="field_AAA">AAA:
<?php if ( get_field( 'AAA' ) ): ?>
<?php the_field('AAA');?>
<?php else: // field_name returned false ?>
dohodou
<?php endif; // end of if field_name logic ?>
</div></div>
</div>
<?php the_title('<h3>', '</h3>'); ?>
<div class="location-wrapper">
<div class="BBB"><img src="https://BBB.png"><?php the_field('BBB');?></div>
<div class="CCC"><img src="https://CCC.png"><?php the_field('CCC');?></div>
</div>
<div class="DDD"><?php $cat = get_the_category(); echo $cat[0]->cat_name; ?></div><div class="job-button">Otevřít</div>
</div></a>
PHP (loading JS, Ajax, function)
function load_scripts() {
wp_enqueue_script('ajax', get_stylesheet_directory_uri() . '/' . 'template-parts/' .'filters.js', array('jquery'), NULL, true);
wp_localize_script('ajax' , 'wp_ajax',
array('ajax_url' => admin_url('admin-ajax.php'))
);
}
add_action( 'wp_enqueue_scripts', 'load_scripts');
add_action( 'wp_ajax_nopriv_filter', 'filter_ajax' );
add_action( 'wp_ajax_filter', 'filter_ajax' );
function filter_ajax() {
$category = $_POST['category'];
$args = array(
'post_type' => 'pozice',
'posts_per_page' => -1
);
if(isset($category)) {
$args['category__in'] = array($category);
}
$query = new WP_Query($args);
if($query->have_posts()) :
while($query->have_posts()) : $query->the_post();
include("content_pozice_box.php");
endwhile;
endif;
wp_reset_postdata();
die();
}
This won't solve all your problems but the first thing you should do is reduce your database calls. get_field('projekt') is called 4 times, which runs for every iteration of your loop. Oddly, you've already set it to a variable:
$projekt = get_field('projekt');
But you're not using the variable anywhere. So try replacing that first, so that it only runs once per iteration:
if ( $projekt ) {...}
While you're at it you should always escape output for security's sake. I.E. Instead of <h3><?php the_field('projekt');?></h3> replace with <h3><?php echo esc_html( $projekt ); ?></h3>.
To find other sources of inefficiencies you might try the Query Monitor plugin, as well as your browser's dev tools. I'm not sure about your JS. It looks fine to me but perhaps someone else here will notice something.

AJAX Load More on Custom Post Grid

I cant get this to work. I am trying to create a custom post type grid with ajax load more button to show 6 mosts per page in the grid. I can get the posts to show but the Load More button just scrolls to the top of the page like a normal anchor link.
My theme code:
<div class="tabgrid">
<?php
$postsPerPage = 6;
$args = array(
'post_type' => 'dslc_projects',
'posts_per_page' => $postsPerPage,
'offset' => $offset
);
$loop = new WP_Query($args);
while ($loop->have_posts()) : $loop->the_post();
?><div class="project-grid-item">
<a href="<?php the_permalink() ?>">
<h3><?php the_title() ?></h3>
<p>View project...</p> </a>
</div><?php
endwhile; ?>
<?php echo '<div id="more_posts">Load More</div>';
wp_reset_postdata();
?>
</div>
</div>
My PHP:
function more_post_ajax(){
$offset = $_POST["offset"];
$ppp = $_POST["ppp"];
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'offset' => $offset
);
$loop = new WP_Query($args);
while ($loop->have_posts()) { $loop->the_post();
the_content();
}
exit;
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
My JS:
var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>";
var page = 1; // What page we are on.
var ppp = 6; // Post per page
$("#more_posts").on("click",function(){ // When btn is pressed.
$("#more_posts").attr("disabled",true); // Disable the button, temp.
$.post(ajaxUrl, {
action:"more_post_ajax",
offset: (page * ppp) + 1,
ppp: ppp
}).success(function(posts){
page++;
$(".tabgrid").append(posts); // CHANGE THIS!
$("#more_posts").attr("disabled",false);
});
});
can anyone see what could be wrong here?
Your anchor is just a normal anchor and href="#" means scroll to top. Your JS code is trying to add a handler to and element with the id "#more_posts" but your anchor doesn't have an id.
Try replacing your anchor with <div id="more_posts">Load More</div>

Updating and passing a value in PHP

I want to make a bundle creator in Wordpress using Woocommerce, where you select 1 of 4 T-shirts + 1 of 4 pairs of socks and they get added to the cart. Currently I am stuck on figuring out how to approach this. What I currently need to achieve is this:
There is a top image which corresponds to the currently selected product and three smaller images below that. Once you click the small image, it needs to change the top image. There is also a title on the bottom, which corresponds to the currently selected product, that changes together with the top image. You can see the intended result here.
I need to somehow get the ID of the product the user clicks on and pass it to other php functions. This is where I got stuck. Can anybody help me out?
The code should look something like this:
<div id="selected-product-image">
<?php get_the_post_thumbnail(/* ID of the currently selected product*/); ?>
</div>
<ul class="products">
<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 4, 'product_cat' => 't-shirts', 'orderby' => 'name' );
$loop = new WP_Query( $args );
?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); global $product; ?>
<li class="product">
<div class="select-product"><!--This should have a function to capture the product ID on click. -->
<?php echo get_the_post_thumbnail($loop->post->ID, 'shop_catalog'); ?>
</div>
</li>
<?php endwhile; ?>
<div id="selected-product-name">
<?php get_the_title(/* ID of the currently selected product*/) ?>;
</div>
<?php wp_reset_query(); ?>
</ul>
I understand that I can do something like this using AJAX, but I am not sure how to use the returned ID back in get_the_post_thumbnail() or get_the_title(). This is what I got:
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery("#select-product").click(function() {
var id = 29; /* Any value for testing */
jQuery.ajax({
method: "post",
url: "/test.php",
data: {
productID: id
}
})
.done(function(data) {
alert(data);
/* How do I use this data to update the picture/title? */
});
});
});
</script>
<!-- THE test.php FILE -->
<?php
$productID = $_POST['productID'];
echo $productID;
?>
UPDATE:
I have tried editing the test.php to echo a function, but I am getting a 500 error every time I try using a Wordpress function inside the test.php file. I tried including the wp-blog-header.php file so the functions can run, but it still doesn't help. What am I doing wrong?
<!-- THE test.php FILE -->
<?php
include_once('wp-blog-header.php');
$productID = $_POST['productID'];
echo get_the_post_thumbnail($productID);
?>

when button clicked send post-id inside variable

I have a query that displays events and there is a buy now button.
How do I make that when I press this button I send in a php session the post-id of the post that this button is inside of.
With what I have done so far the problem is that when I press the button I get the variable of the post-id of the last post in the loop instead of the post-id of the button I am pressing.
This is my code:
function calendario_posts( ) {
ob_start();
// WP_Query arguments
$paged = (get_query_var(‘paged’)) ? get_query_var(‘paged’) : 1;
$args = array (
'category_name' => 'calendario',
'posts_per_page' => '6',
'paged' => $paged
);
// The Query
$featured_post_query = new WP_Query( $args );
// The Loop
if ( $featured_post_query->have_posts() ) {
while ( $featured_post_query->have_posts() ) {
$featured_post_query->the_post();
?>
<div class="teatro-all">
<?php the_post_thumbnail(gallery); ?>
<h2 class="teatro-group teatro-title"><?php the_title(); ?></h2>
<h5 class="teatro-group teatro-fecha"> <?php the_field('fecha'); ?></h5>
<h5 class="teatro-group teatro-precio" >Precio desde: <?php the_field('precio'); ?></h5>
<?php $eventTitle = get_the_title(); ?>
<center><a class="teatro-buy teatro-button" href="http://localhost/newiga/tickets/">COMPRAR</a><br>
<center><a class="teatro-read-more teatro-button" href="<?php the_permalink(); ?>">LEER MAS</a></center>
<script> var buybutton = document.getElementById("teatro-buy");
buybutton.onclick = function(){
<?php $_SESSION['eventId'] = get_the_ID();?>
}
</script>
<?php
}
} else {
// no posts found
}
// Restore original Post Data
wp_reset_postdata();
}
function calendario_shortcode() {
$output = calendario_posts();
$output = ob_get_clean();
return $output;
}
add_shortcode( 'calendario', 'calendario_shortcode' );

Adding a "more" Button

I'm trying to add a "load more" button and limit the results below, so that there aren't 1000 things loading all at once in the portfolio page, here: http://typesetdesign.com/portfolio/
My knowledge of PHP isn't very good, so I'm not sure what I'm supposed to do. I know I could limit the projects here:
<?php query_posts( 'post_type=project&posts_per_page=200' );
But how would I then load more if I limited that result?
Here is the page coding for that entire page:
<div id="projects" class="clearfix">
<?php $page_skills = get_post_meta($post->ID, "_ttrust_page_skills", true); ?>
<?php if ($page_skills) : // if there are a limited number of skills set ?>
<?php $skill_slugs = ""; $skills = explode(",", $page_skills); ?>
<?php if (sizeof($skills) > 1) : // if there is more than one skill, show the filter nav?>
<ul id="filterNav" class="clearfix">
<li class="allBtn"><?php _e('All', 'themetrust'); ?></li>
<?php
$j=1;
foreach ($skills as $skill) {
$skill = get_term_by( 'slug', trim(htmlentities($skill)), 'skill');
if($skill) {
$skill_slug = $skill->slug;
$skill_slugs .= $skill_slug . ",";
$a = '<li><a href="#" data-filter=".'.$skill_slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}
}?>
</ul>
<?php $skill_slugs = substr($skill_slugs, 0, strlen($skill_slugs)-1); ?>
<?php else: ?>
<?php $skill = $skills[0]; ?>
<?php $s = get_term_by( 'name', trim(htmlentities($skill)), 'skill'); ?>
<?php if($s) { $skill_slugs = $s->slug; } ?>
<?php endif;
$temp_post = $post;
$args = array(
'ignore_sticky_posts' => 1,
'posts_per_page' => 200,
'post_type' => 'project',
'skill' => $skill_slugs
);
$projects = new WP_Query( $args );
else : // if not, use all the skills ?>
<ul id="filterNav" class="clearfix">
<li class="allBtn"><?php _e('All', 'themetrust'); ?></li>
<?php $j=1;
$skills = get_terms('skill');
foreach ($skills as $skill) {
$a = '<li><a href="#" data-filter=".'.$skill->slug.'">';
$a .= $skill->name;
$a .= '</a></li>';
echo $a;
echo "\n";
$j++;
}?>
</ul>
<?php
$temp_post = $post;
$args = array(
'ignore_sticky_posts' => 1,
'posts_per_page' => 200,
'post_type' => 'project'
);
$projects = new WP_Query( $args );
endif; ?>
<div class="thumbs masonry">
<?php while ($projects->have_posts()) : $projects->the_post(); ?>
<?php
global $p;
$p = "";
$skills = get_the_terms( $post->ID, 'skill');
if ($skills) {
foreach ($skills as $skill) {
$p .= $skill->slug . " ";
}
}
?>
<?php get_template_part( 'part-project-thumb'); ?>
<?php endwhile; ?>
<?php $post = $temp_post; ?>
</div>
Thanks so much, any input is a help!
Edit
Using Tables with pagination bootstrap style http://datatables.net/examples/basic_init/multiple_tables.html
Massive data base with pagination take a look here: https://stackoverflow.com/a/3707457/2293454
I didn't see your site, now I have, what you might need is something like this:
https://stackoverflow.com/a/21408418/2293454
as you can see that example has a limiter iMyLoadLimit = 5, so, wen the user scroll down the page, it will load more based on the total number of fetched data, if you load 100 articles or 1000, they will be divided by the limiter in the java, the result will be that every time the user scroll down it will display the next 5 or whatever number you want to display...
I hope that helps...
You need pagination (server side) and might want infinite scrolling (client side)
You may want to look at:
Simple PHP Pagination script
http://jscroll.com/
How to paginate query results for Infinite Scroll?

Categories

Resources