PHP Array Random Variable not switching out on page refresh - php

I am using Advanced Custom Fields plugin on a WordPress site. I have a repeater field with 25+ quotes that I am displaying on a per page basis. Each page has unique quotes.
The code I currently have to pull one random quote from that pool of 25 works just as it is suppose to when I am logged in. When I log out, it does pull one random quote but will not switch it out to a different one on page refresh like it does when I am logged in.
I am using this random row code from here:
https://gist.github.com/wesrice/1924934
<?php
if (is_singular('post')) {
$repeater2 = get_field( 'quote_info', 11 );
$random_rows2 = array_rand( $repeater2, 1 );
if( is_array( $random_rows2 ) ){
foreach( $random_rows2 as $random_row2 ){
echo '<div class="newquote">
<div class="newinnerwrapperquote">"' . $repeater2[$random_row2]['bottom_quote_text'] . '"</div>';
echo '<div class="newquoteby">' . $repeater2[$random_row2]['bottom_quote_author'] . '</div></div>';
}
} else {
echo '<div class="newquote">
<div class="newinnerwrapperquote">"' . $repeater2[$random_rows2]['bottom_quote_text'] . '"</div>';
echo '<div class="newquoteby">' . $repeater2[$random_rows2]['bottom_quote_author'] . '</div></div>';
} wp_reset_query();
} else {
$repeater = get_field( 'quote_info' );
$random_rows = array_rand( $repeater, 1 );
if( is_array( $random_rows ) ){
foreach( $random_rows as $random_row ){
echo '<div class="newquote">
<div class="newinnerwrapperquote">"' . $repeater[$random_row]['bottom_quote_text'] . '"</div>';
echo '<div class="newquoteby">' . $repeater[$random_row]['bottom_quote_author'] . '</div></div>';
}
} else {
echo '<div class="newquote">
<div class="newinnerwrapperquote">"' . $repeater[$random_rows]['bottom_quote_text'] . '"</div>';
echo '<div class="newquoteby">' . $repeater[$random_rows]['bottom_quote_author'] . '</div></div>';
}
}
?>
The first if statement is if it is on a WordPress post rather than a page. I hope I explained this well.

Internal caching plugin was activated. Turned it off and works now when not logged in.

Related

Wordpress ACF Get Block Field

I'm running into an issue with ACF, and I just can't figure out what's going on, and nothing on the internet is helping out.
I've added some fields to the Image Slider block:
But no matter what I try inside of our custom block code: image-slider.php I cannot get the values of any of the auto_play fields. get_field always returns null. I know the value is there, because if I dump out get_fields( $postID ), I can see the ['page_builder'][2] element has the value I want. I could get to it that way, but I can't seem to determine which index I'm on (the 2) programmatically.
So if you know either, how I can access the field directly, or figure out my current 'page_builder' index, that would be extremely helpful.
It's super confusing, because the have_rows( 'slide_setting' ) call obviously knows where to look, and works as expected.
The custom block php looks like:
<?php
if(have_rows( 'slide_setting' ) ) {
$digits = 3;
$randID = rand(pow(10, $digits-1), pow(10, $digits)-1);
echo '<div class="container"><div class="row"><div id="swiper_'.$randID.'" class="col-md-12 wiche-swiper-top-navigation-wrapper">';
echo '<div class="swiper-container wiche-swiper-top-navigation">';
// var_dump( get_fields( get_the_ID() )['page_builder'][2] );
// var_dump( get_post_field( 'auto_play' ) );
// var_dump(get_field('image_slider_settings_auto_play'));
// var_dump(get_row_index());
// var_dump(get_field_objects( $post->ID ));
// var_dump( get_row_index() );
// var_dump( acf_get_field_group( 'slide_setting' ) );
// die();
if ( get_field( 'auto_play' ) ) {
echo '<div class="swiper-wrapper" data-swiper-autoplay="' . get_field( 'auto_play_delay' ) . '" data-swiper-disable-on-interaction="' . get_field( 'auto_play_disable_on_interaction' ) . '">';
} else {
echo '<div class="swiper-wrapper">';
}
while( have_rows( 'slide_setting' ) ) {
the_row();
$title = get_sub_field( 'title' );
$image = get_sub_field( 'image' );
$content = get_sub_field( 'content' );
if ( $image || $content ) {
echo '<div class="swiper-slide swiper-banner-slide swiper-no-swiping">';
if ( $title ) {
echo '<div class="text-center slider-top-title">';
echo $title;
echo '</div>';
}
if ( $image ) {
echo '<div class="banner-image">';
echo wp_get_attachment_image( $image, 'full', '', array( 'loading' => false ) );
echo '</div>';
}
if ( $content ) {
echo '<div class="banner-content">';
echo $content;
echo '</div>';
}
echo '</div>';
}
}
echo '</div>';
echo '</div>';
echo '<div class="swiper-button-next swiper-button-next-outsite">Next</div><div class="swiper-button-prev swiper-button-prev-outsite">Prev</div>';
echo '</div></div></div>';
}
So I wasn't able to get a perfect answer to my question, looks like the API to get what I want doesn't exist (dumb).
What I ended up with - I set up a new function in my theme's functions.php file that looks like the following:
$post_slider_config_index = 0;
function get_the_slider_config( $post_id ) {
global $post_slider_config_index;
$page_builder = get_fields( $post_id )['page_builder'];
$slider_config = null;
foreach ($page_builder as $key => $value) {
if ( $value['acf_fc_layout'] === 'image_slider_settings' ) {
if ( $key > $post_slider_config_index ) {
$slider_config = $value;
$post_slider_config_index = $key;
break;
}
}
}
return $slider_config;
}
And then inside my image-slider.php file I call it like so:
$slider_config = get_the_slider_config( get_the_ID() );
if ( $slider_config[ 'auto_play' ] ) {
echo '<div class="swiper-wrapper" data-swiper-autoplay="' . $slider_config[ 'auto_play_delay' ] . '" data-swiper-disable-on-interaction="' . $slider_config[ 'auto_play_disable_on_interaction' ] . '">';
} else {
echo '<div class="swiper-wrapper">';
}
The $post_slider_config_index variable keeps track of the last index retrieved so that if there are multiple sliders on a page, it'll grab the right one as its rendered.
It's not perfect, it's not super efficient, but it does what I needed. Annoying WP doesn't just give you the information it obviously has already regarding where you are in the page.

WordPress Infinite Loop on Single Post

I've taken some code from https://gist.github.com/banago/5603826 so that I am able to do previous/next posts for a specific post on my WordPress site which is a custom post type of 'product'.
<?php
if( get_adjacent_post(false, '', true) ) {
previous_post_link('%link', '← Previous Post');
} else {
$first = new WP_Query('post_type=products&posts_per_page=1&order=DESC'); $first->the_post();
echo '← Previous Post';
wp_reset_query();
};
if( get_adjacent_post(false, '', false) ) {
next_post_link('%link', 'Next Post →');
} else {
$last = new WP_Query('post_type=products&posts_per_page=1&order=ASC'); $last->the_post();
echo 'Next Post →';
wp_reset_query();
};
?>
However it doesn't actually infinitely loop, if it's on the first or last post, the link outputs the page it's already on. An example can be found here - http://s860623395.websitehome.co.uk/products/bespoke-build/
Any solutions to this? Thanks!
Was just working on this myself the other day for a portfolio.
Here is what worked for me (adjusted for your product loop)
It should show a single next product indefinitely (infinite loop)
if( get_adjacent_post(false, '', true) ) {
$previous_link_url = get_permalink( get_previous_post() );
echo '← Next Product';
} else {
$first = new WP_Query('post_type=product&posts_per_page=1&order=DESC');
$first->the_post();
echo 'Next Product →';
wp_reset_query();
};
Just a note, next post is actually the previous post, It's a confusing thing, but when you view the latest post, be it portfolio, product or whatever, the next one is actually the one before, otherwise the next post after the most recent published post would then be the oldest one. This seems to be how most have done it within an infinite loop.
Like you, I tried many variations, none of which really worked, but this one did. Currently I'm using it in the Genesis framework for a portfolio CPT with a background image.
Here is the full working code below taken from a child theme:
add_action( 'genesis_after_content_sidebar_wrap', 'go_prev_next_post_nav_cpt', 999 );
/**
* Enable next link in portfolio.
*
* #since 1.0.0
*/
function go_prev_next_post_nav_cpt() {
echo '<div class="adjacent-entry-pagination">';
echo '<div class="wrap">';
if( get_adjacent_post(false, '', true) ) {
$prevThumb = get_the_post_thumbnail_url( get_previous_post(), 'full' );
$previous_link_url = get_permalink( get_previous_post() );
$prevTitle = get_the_title( get_previous_post() );
echo '<a class="post-link bg-image bg-overlay" href="' . $previous_link_url . '" style="background-image:url(' . $prevThumb . ')"><div class="next-description"><p class="mast">Next project</p><h3 class="display-2">' . $prevTitle . '</h3></div></a>';
} else {
$first = new WP_Query('post_type=portfolio&posts_per_page=1&order=DESC');
$first->the_post();
$bg_image = get_the_post_thumbnail_url();
echo '<a class="post-link bg-image bg-overlay" href="' . get_permalink() . '" style="background-image: url(' . $bg_image . ')"><div class="next-description"><p class="mast">Next project</p><h3 class="display-2">' . get_the_title() . '</h3></div></a>';
wp_reset_query();
};
echo '</div>';
echo '</div>';
}
From memory, I used this as a starting point (lot a trial and error!). https://gist.github.com/banago/5603826

Issue with PHP executing twice

I am displaying a list of filters using Isotope. The functionality works when the first part of the code works however, when the screen is resized the posts don't filter when it executes the last part... Any help is much appreciated!
<?php
$filterLinks = array();
$newarray = array();
$starter = array('name'=>'View All','slug'=>'*');
$filterLinks[] = $starter;
$taxterms = get_terms( $customTax );
if ( ! empty( $taxterms ) && ! is_wp_error( $taxterms ) ){
foreach ( $taxterms as $taxterm ) {
$datafilter = '.' . $taxterm->slug;
$newarray = array(
'name' => $taxterm->name,
'slug' => $datafilter,
);
$filterLinks[] = $newarray;
}
}
echo '<ul id="filters" class="desk-filters button-group">' ."\n";
foreach ($filterLinks as $links) {
echo '<li><button class="button" data-filter="' . $links['slug'] . '">' . $links['name'] . '</button></li>'."\n";
}
echo '</ul>';
// Drop down menu on mobile
echo '<div id="filters" class="resp-filters button-group">'."\n";
echo '<div class="resp-filter-btn">Select Filter</div>'."\n";
echo '<div class="resp-filter-content">'."\n";
foreach ($filterLinks as $links) {
echo '<a class="button" data-filter="' . $links['slug'] . '">' . $links['name'] . '</a>'."\n";
}
echo '</div>'."\n";
echo '</div>';
?>
Functionality Works:
echo '<ul id="filters" class="desk-filters button-group">' ."\n";
foreach ($filterLinks as $links) {
echo '<li><button class="button" data-filter="' . $links['slug'] . '">' . $links['name'] . '</button></li>'."\n";
}
echo '</ul>';
Functionality Doesn't Work:
// Drop down menu on mobile
echo '<div id="filters" class="resp-filters button-group">'."\n";
echo '<div class="resp-filter-btn">Select Filter</div>'."\n";
echo '<div class="resp-filter-content">'."\n";
foreach ($filterLinks as $links) {
echo '<a class="button" data-filter="' . $links['slug'] . '">' . $links['name'] . '</a>'."\n";
}
echo '</div>'."\n";
echo '</div>';
Is this because i'm executing it twice, just hiding one on desktop and showing the other on mobile?
Looking for some direction. Thanks in advance!
You're using id="filters" twice, which is improper use of the id attribute, since it should be unique. Not sure if that is of any concern?

How can i display only the first image from this JSON array?

OK, I'm trying to integrate an API that lists adoptable pets into a wordpress website. I've done lots of googling and read through tutorials, and so far have managed to put together a super basic plugin that seems to do what I'm trying to accomplish. Currently I'm trying to pull in an image, but just the first image. Each animal may have 5 images associated with it, but I only want to pull in the first (default). Currently my code brings them all. Now I realize the problem is that I'm using "foreach()". But, this is new to me and my googling is not going well, and any other way I've tried to do it is just not getting me ANY pictures. Any advice is appreciated....and if I'm doing anything else wrong, feel free to let me know :) I also need to figure out how to paginate it, but I'm thinking that's a separate question! Thanks!
<?php
add_shortcode('pets', 'petsshortcode');
function petsshortcode() {
$request = wp_remote_get( 'https://petstablished.com/api/v2/public/pets?public_key=UlEK4EWvDAoOjXeQXSCQZAyBywWfqfOg&search[status]=available,foster&pagination[limit]=20&pagination[page]=1' );
if( is_wp_error( $request ) ) {
return false; // Bail early
}
$body = wp_remote_retrieve_body( $request );
$data = json_decode( $body );
if( ! empty( $data ) ) {
foreach( $data->collection as $collection ) {
echo '<div id="pet-block"><ul class="pet-profile"><li class="pet-name">'. $collection->name; echo '</li>';
echo '<li class="pet-meta">'.'<span class="sex">' . $collection->sex; echo '</span>' . '<span class="breed">' . $collection->breed; echo '</span><span class="age">' . $collection->age; echo '</span></li>';
echo '<li><p>' . $collection->description; echo '</li></p>';
foreach( $collection->images as $images ) {
echo '<div class="pet-photo"><img src="' . $images->image->url; echo '" width="200"></div>';}
echo '</ul></div>';
}
}
}
You don't need nested foreach loops in this case, simply use just one foreach loop like this:
// your code
foreach( $data->collection as $collection ) {
echo '<div id="pet-block"><ul class="pet-profile"><li class="pet-name">'. $collection->name; echo '</li>';
echo '<li class="pet-meta">'.'<span class="sex">' . $collection->sex; echo '</span>' . '<span class="breed">' . $collection->breed; echo '</span><span class="age">' . $collection->age; echo '</span></li>';
echo '<li><p>' . $collection->description; echo '</li></p>';
echo '<div class="pet-photo"><img src="' . $collection->images[0]->image->url; echo '" width="200"></div>';
echo '</ul></div>';
}
// your code

Wordpress shortcode shows as plain text in one view, works in other

I have this complex loop:
<?php
$args = array(
'cat' => 54,
'order' => 'ASC',
'posts_per_page' => -1
);
$query = new WP_Query($args);
$q = array();
while ( $query->have_posts() ) {
$query->the_post();
$a = '<h2>' . get_the_title() .'</h2>'
. get_the_post_thumbnail() .
'<p>' . get_the_content("...plačiau") . '</p>';
$categories = get_the_category();
foreach ( $categories as $key=>$category ) {
$b = '<h1 class="thetitle">' . $category->name . '<span>Išskleisti <i class="fa fa-arrow-circle-down"></i></span></h1>';
}
$q[$b][] = $a; // Create an array with the category names and post titles
}
/* Restore original Post Data */
wp_reset_postdata();
foreach ($q as $key=>$values) {
echo $key;
echo '<div class="straipsniai">';
foreach ($values as $value){
if (count($values) == 1) {
echo '<div class="vienas">' . $value . '</div>';
} else if (count($values) == 2) {
echo '<div class="du">' . $value . '</div>';
} else if (count($values) == 3) {
echo '<div class="trys">' . $value . '</div>';
} else {
echo '<div>' . $value . '</div>';
}
}
echo '</div>';
}
?>
Which worked for me, gave me this nice list/accordion:
http://bruzienesklinika.lt/web/gydytojai/
Now, each person in the category has some articles as posts and I want a list of their articles under their description. (basic Title + exerpt + read more link)
I've tried to do this by using "List category posts" plugin which allows me to use [catlist id=24] shortcode, but the problem is that browser prints it as plain text, source shows [catlist id=24](You can open the most bottom "GYDYTOJA REUMATOLOGĖ" tab to see that). The shortcode does work inside page, which is rendered by single.php, but it does not show when rendered in the loop I gave you in the beginning of the question.
SO, the question is, how do I make the shortcode work in the initial list, where all the categories are listed with posts inside the accordion.
Now it is not the problem of this certain plugin because no shortcodes work in that accordion list.
Or maybe you have an idea how to do this the other way?

Categories