I have this simple counter php code and use it in Wordpress. Here is the code:
$counter = 0;
while ($query->have_posts())
{query->the_post();$counter++;
Which works fine. But when I go to page 2, then the counter resets and starts back at 1. Is there a way that it continues counting on page 2, page 3 and so on?
the url in the browser address is: /?sf_paged=2 for page 2 and /?sf_paged=3 for page 3 etc...
Is there some if code I can do, like:
if $url = /?sf_paged=2 {
$counter2++; }
else if $url = /?sf_paged=3 {
$counter3++; }
something like that?
Init your counter like this
$counter = $_GET['sf_paged'] ? intval($_GET['sf_paged']) * $posts_per_page : 0;
Then $counter++ will be what you want.
If you want to get the number of all the posts in the query, use:
$query->found_posts
If you want to see how many posts are there from page 1 to n (where 'n' is the current page) I suggest use a simple multiplication:
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;
$postnum = $paged*$query->posts_per_page;
Or you could try to store it in a $_GET parameter, a cookie or a sessionStorage / localStorage. :)
try this one should works fine
<?php
$i = 0; //counter
$post_in_page = 4; //number of posts in loop
$paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; //pagi
$guide = "post_type=post&posts_per_page=$post_in_page"; //loop option
?>
<?php query_posts($guide.'&paged=' . $paged); while(have_posts()) : the_post(); ?>
<?php
$i++; //here counter
if(get_query_var('paged') != 1){ // here if current page not first page
echo get_query_var('paged')*$post_in_page+$i-$post_in_page; // that's it :D
}else{
echo $i;
}
?>
<li>
<?php echo get_the_title(); ?>
<br />
</li><!--End Loop-->
<?php endwhile; ?>
<ul class="pagnum">
<li><?php next_posts_link();?></li>
<li><?php previous_posts_link(); ?></li>
</ul><!--End pagnum-->
<?php wp_reset_query();?>
Related
I have this php code with a sql query and I want the page(more like a part of the page) to update without page reload. I also have a button that when I click it updates the variable(?date=) on the link. What I want now is to also execute this block of code without page reload.
Here are pictures what I want to achieve:
[So when I click the date, it updates the ?date variable on the link][1]
[and I want this to also update based on the sql query I have without reloading the page][2]
<?php
if (isset($_GET["date"])) {
foreach ($db->query("SELECT DayName, StartTime, EndTime FROM event_availability
INNER JOIN days ON days.DayID = event_availability.DayID
WHERE EventID = ? AND DayName = ?", $_GET["eventid"], date('l', strtotime($_GET["date"]))) as $availtime) {
?>
<?php
$i = 1;
$start = date('h:i A', strtotime($availtime["StartTime"]));
$end = $availtime["EndTime"];
while (strtotime($start) <= strtotime($end)) {
?>
<input type="radio" class="btn-check shadow-none" name="timeradio" id="btnradio<?php echo $i ?>" autocomplete="off">
<label class="btn btn-outline-primary" for="btnradio<?php echo $i ?>"><?php echo $start ?></label>
<?php
$start = date("h:i A", strtotime("$start + 30 mins"));
$i++;
}
?>
<?php
}
}
?>
[1]: https://i.stack.imgur.com/lHxCq.png
[2]: https://i.stack.imgur.com/aQP5k.png
I am trying to build a simple interface in Woocommerce where a product gets added straight to the mini cart next to it with AJAX, rather than having the page refresh every time you add an item to the cart. Unfortunately I cannot get the AJAX to work and the page just keeps refreshing.
woocommerce.php - the default woocommerce page:
<?php
//LOOP THROUGH ALL PRODUCTS
$args = array( 'post_type' => 'product');
$loop = new WP_Query( $args );
echo "<ul class='mylisting'>";
while ( $loop->have_posts() ) : $loop->the_post();
global $product;
$id = $product->get_id();
$item_name = $product->get_name();
if( $product->is_type( 'variable' ) ){
$class = "variable-product";
} else {
$class = NULL;
}
//OUTPUT PRODUCTS
?>
<li>
<a class="menu-link <?php echo $class; ?>" data-product_id="<?php echo $id; ?>" href="/wpdev/shop/?add-to-cart=<?php echo $id; ?>"><?php echo $item_name." - ".$id; ?></a>
</li>
<?php if( $product->is_type( 'variable' ) ) : ?>
<div id="product-popup-<?php echo $id; ?>" class="product-popup">
<div class="popup-inner">
<?php woocommerce_variable_add_to_cart(); ?>
</div>
</div>
<?php endif; ?>
<?php
endwhile;
echo "</ul>";
wp_reset_query();
?>
<!-- DISPLAY MINI CART -->
<div id="mini-cart-container">
<?php woocommerce_mini_cart(); ?>
</div>
main.js - Main javascript file:
$('.menu-link').click(function(){
jQuery.ajax({
url : woocommerce_params.ajax_url,
type : 'post',
data : {
'action': 'ajax_update_mini_cart'
},
success : function( response ) {
$('#mini-cart-container').html(response);
}
});
});
functions.php
function ajax_update_mini_cart() {
echo wc_get_template( 'cart/mini-cart.php' );
die();
}
add_filter( 'wp_ajax_nopriv_ajax_update_mini_cart', 'ajax_update_mini_cart' );
add_filter( 'wp_ajax_ajax_update_mini_cart', 'ajax_update_mini_cart' );
The goal is to get the woocommerce_mini_cart() function to update with ajax. Is this possible?
I suspect the problem lies with the way I have coded the javascript ajax function, but I'm not sure. Any help would be greatly appreciated.
UPDATE: Moe's solution below has now been added, which has stopped the page reloading but the cart still doesn't update. Echoing some text inside the ajax_update_mini_cart() function does ajax that text inside the mini-cart-container div where the mini-cart should be, which proves (I think) that the javascript function and the php function is working. I think for some reason the problem comes when the echo wc_get_template( 'cart/mini-cart.php' ); is placed inside the function. Does anyone know why this is?
its following the href. try the following
$('.menu-link').click(function(e){
e.preventDefault();
jQuery.ajax({
url : woocommerce_params.ajax_url,
type : 'post',
data : {
'action': 'ajax_update_mini_cart'
},
success : function( response ) {
$('#mini-cart-container').html(response);
}
});
});
I'm using WordPress and ACF Gallery. In each post I have a gallery with images.
I need to get all images from all galleries and shuffle they.
How I can achieve this?
Now I have this:
<?php if ( $query->have_posts() ) : ?>
<?php while ( $query->have_posts() ) : $query->the_post();
$images = get_field( 'gallery' );
$size = 'full';
if ( $images ) : ?>
<?php foreach( $images as $image ): ?>
<img class="post-gallery" src="<?php echo $image['url']; ?>">
<?php endforeach; ?>
<?php endif; ?>
<?php if (has_post_thumbnail()) : ?>
<div class="post" style="background-image: url(<?php the_post_thumbnail_url(); ?>);"></div>
<?php endif; ?>
I think we need to put somehow all posts and posts's galleries to one array and shuffle it?
Update: js part(Infinite+masonry+imagesLoaded+randomize blocks
var images = $('.container-post .col-50');
for (var i = 0; i < images.length; i++) {
var imageFirst = Math.floor(Math.random() * images.length -1) + 1;
var imageSecond = Math.floor(Math.random() * images.length -1) +1;
images.eq(imageFirst).before(images.eq(imageSecond));
}
var $container = $('.container-post').masonry({
itemSelector: '.container-post .col-50',
});
$container.imagesLoaded().progress( function() {
$container.masonry('layout');
});
var masonry = $container.data('masonry');
$container.infiniteScroll({
outlayer: masonry,
path: '.wp-pagenavi .page',
append: '.container-post .col-50',
scrollThread: 1,
history: false,
hideNav: '.wp-pagenavi',
status: '.page-load-status',
});
Have a nice day!
I would personally have PHP do the heavy lifting and, as you said, create a shuffled array that JS can loop over. For example:
<?php
$collectedImages = [];
if ($query->have_posts()) {
while($query->have_posts()) {
$query->the_post();
$images = get_field('gallery');
$size = 'full';
if ($images === false) {
continue;
}
foreach ($images as $image) {
$collectedImages[] = $image['url'];
}
}
}
shuffle($collectedImages);
foreach ($collectedImages as $image) {
// Render it!
}
?>
More info:
shuffle() - PHP docs
I have been looking at this code for far too long and am getting nowhere so hopefully someone can help me!
I am building a wordpress site, and for the main blog page, I want to display the content as tiles, but every 3 or 7, I want to display a promo content post-type. I can do this fine, but when I add a Load More Posts button, it resets the counter that I have keeping track of my extra promo content back to 0, therefore only showing the first 2 promo pieces over and over with each new load.
I would appreciate any help. I'm going in circles now.
the important parts of the home.php file :
<div class="blog-post-tiles">
<?php
//variables
$counter = 0;
$promo_counter = 0;
$args = array(
'post_type' => 'promo',
);
//$postlist = new WP_Query( $args );
$postlist = get_posts($args);
$posts = array();
foreach ( $postlist as $post ) {
$promo_posts_array[] += $post->ID;
}
?>
<?php if ( have_posts() ) : ?>
<?php $query = new wp_query( $query_string.'&cat=-16' );
while ( $query->have_posts() ) : $query->the_post() ?>
<?php
// print post loop
get_template_part( 'template-parts/content', get_post_format() );
$counter++;
//display promo content ever 3rd or 10th spot
if (($counter == 3) || ($counter % 10 == 0) || ($counter % 10 == 3)) {
if ($promo_counter < count($promo_posts_array)){
$print_post = $promo_posts_array[$promo_counter];
$promo_thumbnail_src = wp_get_attachment_image_src( get_post_thumbnail_id($print_post), array( 200,200 ), false, '');
?>
<div class="posts_page_tile promo-tile" id="id-<?php echo $print_post; ?>">
<div class="entry-content">
<div class="promo-image" style="background-image:url('<?php echo $promo_thumbnail_src[0]; ?>'); background-color:<?php echo get_post_meta($print_post, 'bgcolor', true) ?>">
<h3><?php echo get_the_title($print_post); ?></h3>
<div class="promo_button_white_border"><?php echo get_post_meta($print_post, 'cta', true); ?>
</div>
</div>
</div>
</div>
<?php
}
$promo_counter++;
wp_reset_postdata();
}
?>
<?php endwhile; ?>
I'm using this load more posts plugin.
Below is my textbox values....i am unable to put my screen shots here..
i used multiple input tag jquery from this site..
http://loopj.com/jquery-tokeninput/demo.html
and second option of this demo. plz visit demo link ...
but i used multiple input textbox..in which we select multiple tags in one textbox okay.
like 700X 701X 702X
I need to get this textbox value and store in 3 rows..
FOR EX - in above screenshot there are 3 values 700,701,702 ok...now i need to ask you...when i click save i need to store this values in 3 different rows...
Rows No - used_receipt
1 700
2 701
3 702
i try like below but wont work...
textbox code
<input id="demo-input-local" type="text" value="<?php echo $data['used_receipt'];?>" name="used_receipt" />
javascript
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input-local").tokenInput([
<?php
$receipt = $database->getRows("SELECT DISTINCT SM.receipt_no FROM scheme_master SM Inner join book_issue BI ON BI.book_no = SM.Book_no2 where SM.receipt_no not in (select used_receipt from book_return)");
foreach($receipt as $row){ ?>
{name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
]);
});
</script>
php code to insert multiple values in database
$used_receipt = $_POST['used_receipt'];
$arr = explode(",", $used_receipt);
$max = count($arr);
for ($i = 0; $i < $max; $i++)
{
$insertrow = $database->insertRow("INSERT INTO book_return (book,surveyor,used_receipt,city,return_date,created)
VALUES (:book,:surveyor,:used_receipt,:city,:return_date,:created)",
array(':used_receipt'=>$arr[$i]);
}
Instead of
foreach($receipt as $row){ ?>
{name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
Try this
$r = array();$i=1;
foreach($receipt as $row){
$r[]['name'] = $row['receipt_no'];$r[]['id'] = $i++;
}
echo "JSON.parse(\"".json_encode($t)."\")";
below is script which i used
<script type="text/javascript">
$(document).ready(function() {
$("#demo-input-local").tokenInput([<?php
$receipt = $database->getRows("SELECT DISTINCT SM.receipt_no FROM scheme_master SM Inner join book_issue BI ON BI.book_no = SM.Book_no2");
foreach($receipt as $row){ ?>
{id:<?php echo $row['receipt_no']; ?>,name: "<?php echo $row['receipt_no']; ?>"},
<?php } ?>
]);
});
</script>
and get this input in like
$used_receipt = $_POST['used_receipt'];
$arr = explode(",", rtrim($used_receipt));