if statement in a for each function - php

$args = array( 'numberposts' => '3' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<a style="color:white;text-decoration:none;" href="'. get_permalink($recent["ID"]) .'">
<article class="post post_home" style="background-image: url('.
function(){
if( has_post_thumbnail() ) {
echo get_the_post_thumbnail_url( $recent["ID"], 'cover' );
} elseif ( has_category( 'positive-morning' ) ) {
echo get_bloginfo('template_directory') . '/img/BG/2-Morning.jpg';
} elseif ( has_category( 'positive-talks' ) ) {
echo get_bloginfo('template_directory') . '/img/BG/2-Talks.jpg'; }
}
.');
background-position : center; background-size :cover;">
<h2>'. $recent["post_title"] .'</h2></article>';
....
}
Hi all,
I'm having trouble to put an if statement because when I add the if statement supposed to declare if the post has no thumbnails, it should get the relative path to display the thumbnails defined for the category.
I've tried different ways to make it work but I can't find what's the problem. The only error I get is
Object of class Closure could not be converted to string
Thanks for any help

function(){ is a function definition, you can't concatenate that. Additionally, has_post_thumbnail is actually the WP function you want to use and that takes as its first parameter the post ID. So you should rewrite your code as follows.
$args = array( 'numberposts' => '3' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
$output = '<a style="color:white;text-decoration:none;" href="'. get_permalink($recent["ID"]) . '">
<article class="post post_home" style="background-image: url(';
if( has_post_thumbnail($recent["ID"]) ) {
$output .= get_the_post_thumbnail_url( $recent["ID"], 'cover' );
} elseif ( has_category( 'positive-morning' ) ) {
$output .= get_bloginfo('template_directory') . '/img/BG/2-Morning.jpg';
} elseif ( has_category( 'positive-talks' ) ) {
$output .= get_bloginfo('template_directory') . '/img/BG/2-Talks.jpg';
}
$output .= ' background-position : center; background-size :cover;">
<h2>'. $recent["post_title"] .'</h2></article>';
echo $output;
}

Theres a few things missing here. You're not setting up postdata inside your loop and you don't need a function inside it either, also personally I don't like concatinating strings together inside PHP tags to make HTML so I used ob_start() and ob_get_clean() to build the HTML. try something like this...
<?php
$args = array( 'numberposts' => '3' );
$recent_posts = wp_get_recent_posts( $args );
ob_start();
foreach( $recent_posts as $recent ){
setup_postdata($recent); ?>
<a style="color:white;text-decoration:none;" href="<?php get_permalink($recent["ID"])?>">
<article class="post post_home" style="background-image: url(<?php
if( has_post_thumbnail() ) {
echo get_the_post_thumbnail_url( $recent["ID"], 'cover' );
} elseif ( has_category( 'positive-morning' ) ) {
echo get_bloginfo('template_directory') . '/img/BG/2-Morning.jpg';
} elseif ( has_category( 'positive-talks' ) ) {
echo get_bloginfo('template_directory') . '/img/BG/2-Talks.jpg';
}; ?>
); background-position : center; background-size :cover;">
<h2><?php echo $recent["post_title"] ?></h2></article>
<?php
wp_reset_postdata();
}
echo ob_get_clean(); ?>
Fair warning I haven't tested any of that code

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.

How to list posts and wrap them alphabetically?

I have a list of posts on my website, what I'm trying to do is to wrap them alphabetically from A-Z by title to get a glossary like this:
A.
Apple
B.
Banana
C.
Carotts
D.
E.
F.
G.
Grenada
and so on untill letter z.
I want the letter to be displayed even if there's no post.
and i want to wrap results inside this structure :
<div class="group_letter">
<div class="letter">A</div>
<div class="post">Apple</div>
</div>
<div class="group_letter">
<div class="letter">B</div>
<div class="post">Banana</div>
</div>
here is what I've got so far :
<?php
$letter=' ';
query_posts( array ( 'post_type' => 'auteurs', 'orderby' => 'title', 'order' => 'ASC' ) );
if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php
$title=get_the_title();
$initial=strtoupper(substr($title,0,1));
if($initial!=$letter) {
echo "<div>$initial</div>";
$letter=$initial;
}
echo "<div class='post'>" . $title. "</div>";
?>
<?php endwhile; endif; wp_reset_query(); ?>
here is the result :
<div class='letter'>A</div>
<div class='post'>Apple</div>
<div class='letter'>B</div>
<div class='post'>Banana</div>
<div class='letter'>C</div>
<div class='post'>carotts</div>
<div class='letter'>G</div>
<div class='post'>Grenanda</div>
I have 2 problems :
Empty letters are not displayed.
I can't find a way to wrap my groups inside group_letter div.
I would solve this with a filter on WP_Query. One that detects an extra query variable.
Add this into your functions.php
add_filter( 'posts_where', 'title_filter', 10, 2 );
function title_filter( $where, &$wp_query )
{
global $wpdb;
if ( $search_term = $wp_query->get( 'search_prod_title' ) ) {
$where .= ' AND ' . $wpdb->posts . '.post_title LIKE \'%' . esc_sql( $wpdb->esc_like( $search_term ) ) . '%\'';
}
return $where;
}
Once you have filter in place you can use wp_query and array range of alphabet
foreach (range('A', 'Z') as $char) {
echo '<div class="group_letter">';
echo '<div class="letter">'.$char.'</div>';
$args = array(
'post_type' => 'auteurs',
'posts_per_page' => -1,
'search_prod_title' => $char,
'post_status' => 'publish',
'orderby' => 'title',
'order' => 'ASC'
);
$the_query = new WP_Query($args);
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$title=get_the_title();
$initial=strtoupper(substr($title,0,1));
if($initial==$char) {
echo "<div class='post'>" . $title. "</div>";
}
endwhile;
wp_reset_postdata();
endif;
echo '</div>';
}
remove_filter( 'posts_where', 'title_filter', 10, 2 );
I have not tested this code, I hope it should work.
You can get more information about Wp_query https://codex.wordpress.org/Class_Reference/WP_Query
Sorry, postin TV from phone, so may be not displaying properly
Firstly, you have to create an array of all alphabets.
$alph = array('A', 'B', 'C',.... 'Z');
<
?php
$title=get_the_title();
foreach($alph as $key) {
// add while loop here
initial=strtoupper(substr($title,0,1));
if($initial!=$key) {
echo '<div class="group_letter">';
echo "<div>$key</div>";
}else{
echo "<div class='post'>" . $title. "</div>";
}
echo "</div>";
// end while loop here
}
?>

WP_Query + Infinite Scroll

I've stucked while working on my brand new blog template (on wordpress). I've got following query/php code:
echo '<div id="posts-container" class="fusion-blog-layout-medium fusion-blog-infinite fusion-posts-container-infinite fusion-blog-archive fusion-clearfix">';
$args = array( 'post_type' => 'era', 'post_status' => array('publish', 'future'), 'paged' => $paged );
$custom_query = new WP_Query($args);
while($custom_query->have_posts()) : $custom_query->the_post();
$post_classes = $post_class . ' ' . $alignment_class . ' ' . $thumb_class . ' post fusion-clearfix';
ob_start();
post_class( $post_classes );
$post_classes = ob_get_clean();
echo '<article id="post-' . get_the_ID() . '" ' . $post_classes . '>';
get_template_part( 'new-slideshow' );
echo '<div class="fusion-post-content koncert post-content">';
echo ( '<h2 class="entry-title fusion-post-title" data-fontsize="18" data-lineheight="27">' .get_the_title() . '</h2>' );
if ( get_field( "data_i_miejsce_koncertu", get_the_ID() ) ) {
echo ( '<div class="lista-koncert-podtytul">' . get_field( "data_i_miejsce_koncertu", get_the_ID() ) . '</div>' );
}
echo '<div class="fusion-post-content-container">';
do_action( 'avada_blog_post_content' );
if ( get_field( "opis", get_the_ID() ) ) {
echo '<div class="lista-koncert-opis">' . wp_trim_words(get_field( "opis", get_the_ID() ), 60, ' [...]') . '<br><br>Zobacz więcej ></div>';
}
echo '</div>';
echo '</div>'; // End post-content.
echo '</article>';
endwhile;
wp_reset_postdata(); // reset the query
echo '</div>';
What I would like to achieve is to not have regular pagination (I've already removed the controls from my template), but I would like to use jquery infinite scroll script. But being honest - i have no clue how to even start ;/ mainly because there are no that many live examples/tutorials in the internet.. thanks for any tips
You need to invovle javascript to make infinte scrolling work.
Basically what you need to have:
Page that displays first few posts and loads the infinite scrolling javascript function
Hook on wp_ajax to provide next posts data as you call it
After scroll/"click on load more" you call this with javascript and append the loaded posts at the bottom
Repeat this until all posts are loaded
This should give you a good starting point: https://www.billerickson.net/infinite-scroll-in-wordpress/
Also please don't write your HTML in Wordpress themes/plugins with echo. This is far more readable and helps you to keep your indentation right:
?>
<div id="posts-container" class="fusion-blog-layout-medium fusion-blog-infinite fusion-posts-container-infinite fusion-blog-archive fusion-clearfix">
<?php
$args = array( 'post_type' => 'era', 'post_status' => array('publish', 'future'), 'paged' => $paged );
$custom_query = new WP_Query($args);
while($custom_query->have_posts()) : $custom_query->the_post();
$post_classes = $post_class . ' ' . $alignment_class . ' ' . $thumb_class . ' post fusion-clearfix';
ob_start();
post_class( $post_classes );
$post_classes = ob_get_clean();
?>
<article id="post-<?php echo get_the_ID() ?>" <?php echo $post_classes ?>>
...

Second WordPress loop failing

I have two loops running on my page one for getting one set of posts from a specific category and then further down getting posts from a custom post type but for some reason If I output both of them the second loop does not show and if I comment out the first the second one does show?
Im a bit confused as to why?
FIRST LOOP UPDATED
<?php
$post_query = new WP_Query(array( 'category_name' => 'email-content'));
if ( $post_query->have_posts() ) {
echo '<div class="tabs tabs_default">';
echo '<ul class="horizontal">';
while ( $post_query->have_posts() ) {
$post_query->the_post();
$title = strtolower(get_the_title());
$title = str_replace(' ', '-', $title);
echo'<li>'.get_the_title().'</li>';
}
echo '</ul>';
while ( $post_query->have_posts() ) {
$post_query->the_post();
$title = strtolower(get_the_title());
$title = str_replace(' ', '-', $title);
echo '<div id="'.$title.'">';
echo '<div><button class="copy" id="'.$title.'" data-clipboard-text="'.get_the_content().'" title="Copy">Copy</button></div>';
echo '<div>'.get_the_content().'</div>';
echo '</div>';
}
$post_query->reset_postdata();
}
?>
SECOND LOOP UPDATED
I didn't need one of the loops so I refined the code a bit further but still I am not having any luck with the second loop outputting.
<?php
$featureThumb = new WP_Query( array(
'post_type' => 'resources',
'meta_key' => 'file_upload',
'posts_per_page' => -1
));
while ($featureThumb->have_posts()) : $featureThumb->the_post();
echo '<div>';
if (has_post_thumbnail($post->ID)) {
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'homepage-thumb-thumb' );
echo '<img src="' . $thumb[0] . '" width="200" height="200" />' ;
};
echo '<p><a href="'. get_field('file_upload') .'" target="_blank" download>Click here to download as PDF</a></p>';
endwhile;
unset($featureThumb);
}
?>
It seems that you have three queries and 4 loops, not two.
Also, you have an extra } after the unset($featureThumb); that you should remove.
The three queries you posted in your question are:
$post_query, $loop and $featureThumb. At the last one your loop is incorect. It uses the object of the second one. Change at the third query in the loop, $loop with $featureThumb.
You need to use wp_reset_postdata() after the first two queries instead of wp_reset_query() as someone suggested and it should both work.
wp_reset_query() ensures that the main query has been reset to the original main query, while on the other hand wp_reset_postdata() makes sure that the global $post has been restored to the current post in the main query.
UPDATE:
If that does not work, if global $post object is not defined, try:
$post_query->reset_postdata();
$loop->reset_postdata();
UPDATE 2:
Your first query and loop should look like this:
<?php
$post_query = new WP_Query(array( 'category_name' => 'email-content'));
if ( $post_query->have_posts() ) {
echo '<div class="tabs tabs_default">';
echo '<ul class="horizontal">';
while ( $post_query->have_posts() ) {
$post_query->the_post();
$title = strtolower(get_the_title());
$title = str_replace(' ', '-', $title);
echo'<li>'.get_the_title().'</li>';
}
echo '</ul>';
while ( $post_query->have_posts() ) {
$post_query->the_post();
$title = strtolower(get_the_title());
$title = str_replace(' ', '-', $title);
echo '<div id="'.$title.'">';
echo '<div><button class="copy" id="'.$title.'" data-clipboard-text="'.get_the_content().'" title="Copy">Copy</button></div>';
echo '<div>'.get_the_content().'</div>';
echo '</div>';
}
$post_query->reset_postdata();
}
?>
You have to use wp_reset_query(); at the end of the first loop as well. So the first loop should be:
<?php
$post_query = new WP_Query(array( 'category_name' => 'email-content'));
if ( $post_query->have_posts() ) {
echo '<div class="tabs tabs_default">';
echo '<ul class="horizontal">';
while ( $post_query->have_posts() ) {
$post_query->the_post();
$title = strtolower(get_the_title());
$title = str_replace(' ', '-', $title);
echo'<li>'.get_the_title().'</li>';
}
echo '</ul>';
while ( $post_query->have_posts() ) {
$post_query->the_post();
$title = strtolower(get_the_title());
$title = str_replace(' ', '-', $title);
echo '<div id="'.$title.'">';
echo '<div><button class="copy" id="'.$title.'" data-clipboard-text="'.get_the_content().'" title="Copy">Copy</button></div>';
echo '<div>'.get_the_content().'</div>';
echo '</div>';
}
wp_reset_query();
}
?>

Trying to call post title, excerpt, and permalink from id for shorcode

I was able to get the title and excerpt to display correctly, but I can't figure out which permalink call to use.
function display_excerpt_shortcode( $atts ) {
extract(shortcode_atts(array(
'excerptid' => ''
), $atts));
if ($excerptid) {
$args=array(
'p' => $excerptid,
'post_type' => 'post',
'post_status' => 'publish'
);
$my_query = new WP_Query($args);
if ($my_query) {
$title = apply_filters( 'the_title', $my_query->posts[0]->post_title );
$excerpt = apply_filters( 'the_excerpt', $my_query->posts[0]->post_excerpt );
$link = apply_filters( 'the_permalink', $my_query->posts[0]->post_permalink );
return '<h3>' . $title . '</h3> <p>' . $excerpt . '</p> <a class="button small primary" href="' . $link . '" title="' . $title . '" >Read More </a>';
}
}
return;
}
add_shortcode('display_excerpt', 'display_excerpt_shortcode');
I've tried all kinds of combinations. the_permalink, get_permalink, post_permalink... I just can't figure out if it's the wrong combination or if I'm just completely off the mark. Thanks in advance.
Have you tried:
$link = get_permalink( $my_query->posts[0]->post_ID )
I think your problem is that the query object has no 'permalink' property.
Following the guide in the codex's class reference page, you'll find the pattern of setting a new post object during each iteration of the loop with $the_query->the_post();:
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
//Now reference WP post functions:
the_title();
the_permalink();
}
}
Sorry it's a totally different design, but this has never failed me.

Categories