Store the output of foreach loop to array - php

I'm using a code to show specific filtered products and i'm trying to integrate this code with an exist function in my theme showing posts in slider . what i'm stuck in is that's i need the output of the foreach loop to be stored in array so i can use it in the function , sorry for my english , here's my code , any help will be highly appreciated
//the loop and it output posts with no problems//
<?php
foreach ( $products as $post ) : setup_postdata( $post ); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endforeach; // end of the loop. ?>
<?php wp_reset_postdata(); ?>
//the slider function and it works through the theme in same logic for example for related products the value is an array //
<?php
$slider_args = array(
'slides_per_view' => 4 ,
'img_size' => 'woocommerce_thumbnail',
'custom_sizes' => false
);
theme_set_loop_prop( 'products_view', 'carousel' );
echo theme_generate_posts_slider( $slider_args, false, //i need to put the array here// $relatedproducts );
?>

Related

Wordpress print latest posts

I have a static page with 10 containers located at different places in the index.php file, i want to show the 10 latest posts. I want to echo the data for a post (title,text,thumbnail,author,time) like this:
<div class="text">
<?php
echo '$textfrompost3';
?>
</div>
<div class="title">
<?php
echo '$titlefrompost3';
?>
</div>
...
...
My PHP file:
<?php
// the query
$the_query = new WP_Query( array(
'category_name' => 'Allgemein',
'posts_per_page' => 10,
"orderby" => "date",
"order" => "DESC"
));
?>
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
// insert values into variables
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
Thanks in advance, i appreciate any help you can provide.
I'd simply replace your call to WP_Query with get_posts() which will provide an array of post objects.
$latest_posts = get_posts( array(
'category_name' => 'Allgemein',
'posts_per_page' => 10,
) );
I've dropped order and orderby in the example above. While you may well have a different global setting for the number of posts to display, it's unlikely you're modifying the default ordering.
Documentation: https://codex.wordpress.org/Template_Tags/get_posts
So let's say I want to output the title of the third post, I could do the following:
// let's be sure we have a third post.
if ( isset( $latest_posts[2] ) ) {
echo $latest_posts[2]->post_title; // remember arrays have a zero-based index.
}

Randomize array content in PHP via Wordpress posts

Do you guys know how to limit posts per page and randomize posts in wordpress?
I have a relationship field in the back-end where I add and remove items that I created to display in a website. This content is printed through the WP_Query below:
<?php
$args = array (
'post_type' => 'home_banners'
$fullbanner = new WP_Query ( $args );
?>
And here is the PHP:
<?php if ( have_posts() ) : while ( $fullbanner->have_posts() ) : $fullbanner->the_post(); ?>
#####Get the relationship field
<?php $banners = get_field('home_banner_01_selection'); ?>
#####Check if the relationship field has contents
<?php if( $banners ): ?>
#####Start foreach
<?php foreach( $banners as $banner ): ?>
<?php the_field( 'home_headline', $banner->ID ); ?>
<?php endforeach; ?>
<?php endif; ?>
I have three contents added in this relationship field. I want just to display ONLY ONE content per page and randomize it when refreshing the page. At the moment it is currently display all the three contents in the page.
I notice that the var $banners behave as an array. If I add echo count($banners); it will display 3. Moreover, if I add shuffle($banners); it will shuffle the content among them.
Thanks for helping me.
You could shuffle the array $banners and then just echo out the post in array wit
<?php
$banners = get_field('home_banner_01_selection');
if($banners) {
shuffle($banners);
?>
<?php the_field( 'home_headline', $banners[0]->ID ); ?>
<?php
}
?>

PHP/WordPress: Custom Field Value in Loop returns Array instead of Single Result

For the search results page in WordPress Im making a custom template. And in that custom template I want to display custom meta field values.
However, when I do this:
<?php if ( have_posts() ) : ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
$pName = get_post_meta($post->ID, $productName, true);
echo $pName;
);
?>
<?php endwhile; ?>
<?php else : ?>
<?php get_template_part( 'content', 'none' ); ?>
<?php endif;
The result I get is not the value of the custom field but:
Array
When I var_dump the $pName it shows all the right custom field content.
Question: Why am I getting an array as the result (when Ive told it its a single result with 'true') and how do I fix it so it displays the proper content?
Thanks!

wordpress query_posts alternative

I am creating a website that integrates a portfolio which uses custom post types, this was done based off of this tutorial.
So far it is exactly what I am looking for and works great except for one small detail. In order to fetch the posts from the new custom post type the author of the tutorial used the query_posts() codex. So the top of my portfolio page looks like this:
<?php
/* Template Name: Portfolio */
get_header();
query_posts('post_type=portfolio&posts_per_page=10');
?>
What I gather is that this declares "get posts from "post type" portfolio and show 10 per page". My problem is that I can't go get content from my portfolio page. It seems that now my portfolio page only fetches the content from the custom post type, and I can't use:
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
to get content from the actual page.
This is what I am trying to do, I've replaced:
query_posts('post_type=portfolio&posts_per_page=10');
with:
add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
function add_my_post_types_to_query( $query ) {
if ( is_page( 8 ) && $query->is_main_query() )
$query->set( 'post_type', array( 'portfolio' ) );
return $query;
}
This seems like the right track, but it stills doesn't work. I'm not getting the posts from my custom post type.
Any ideas how I could modify this? I am also still learning so being clear with explanations would be greatly appreciated.
Thank you!
Editing the pre_get_posts will replace the original query and you will not have the content for your page at all. I would only recommend going this approach if you only wanted to display the content of your portfolio post type and not the content of your portfolio page.
For general post queries it is recommended to use WP_Query or get_posts.
http://codex.wordpress.org/Class_Reference/WP_Query
http://codex.wordpress.org/Template_Tags/get_posts
If you use the WP_Query function the wp_reset_postdata() will restore the post data back to the original so you can get the content of your original page.
$args = array(
'posts_per_page' => 10,
'post_type' => 'portfolio',
);
// The Query
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
Now you will be able to use the original loop to show the content of your page
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
Usually, I stick my query posts in a variable, like so:
$catid = get_cat_ID('My Category Name');
$args = array(
'posts_per_page' => 5,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'category' => $catid
);
$posts_array = get_posts($args);
Then you can loop it like so:
<?php foreach ($posts_array as $post) : setup_postdata($post);?>
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
<?php endforeach; ?>
Finally, to access your page content you can use the variable $post, it's automatically set by wordpress. No need to add any more code than this to access your page content.
<?php foreach( $posts as $post ) : setup_postdata($post); ?>
<h1><?php the_title(); ?></h1>
<p><?php the_content(); ?></p>
<?php endforeach; ?>
The foreach loop for your page content is a little overkill, and there is a better way to do it (most likely at least), but I haven't been bothered to look into it further yet! It works though!

Random Wordpress posts outside of the main loop without duplicate posts. How?

Well I can't figure this one out...
I have this Wordpress I use as a photo gallery blog.
I have a basic setup using the main default loop for posts.
Like this:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
//the post
<?php endwhile; ?>
<b>Not Found</b>
<?php endif; ?>
In the sidebar and where ever, I want to appear random posts.
I've managed to do that. With this:
<?php query_posts($query_string . 'showposts=1&orderby=rand'); ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
//the post
<?php endwhile; endif; ?>
It looks amazing! In theory.
There are duplicate posts all over the place. And that just looks stupid.
I have read lots of articles but I just can't seem to get it to work :(
Any help would be much appreciated.
Try this code for random post.
<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><?php the_title(); ?></li>
<?php endforeach; ?>
</ul>
Or You can get help from this url mention below
http://codex.wordpress.org/Template_Tags/get_posts
After a good night of sleep, here's what I have done:
Creating array with post ID:
<?php $already_posted = array(); ?>
The Main loop where at the end I record the post ID to array:
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
//the post
<?php $already_posted[]= $post->ID; endwhile; ?>
<?php else : ?>
<b>Not Found</b>
<?php endif; ?>
And the random post code using post__not_in to avoid duplicates and again recording post ID:
<?php $args = array( 'numberposts' => 1, 'orderby' => 'rand', 'post__not_in' => $already_posted );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
//the post
<?php $already_posted[]= $post->ID; endforeach; ?>
Works evertime!
You can do amazing stuff with this :)
Thanks to paislee and Arvind Pal for helping out.
Skip would-be duplicates by remembering displayed ID's from the first loop
$displayed = array(); // create an array that we'll use associatively
In your first loop, each time:
$displayed[get_the_ID()] = TRUE; // <-- save all post IDs in here
Change your random loop opening like this:
<?php if (have_posts()) : while (have_posts()) : the_post();
// skip post IDs you've already seen
if ($displayed[get_the_ID()]) continue;
?>
Due to randomness in the number of duplicates, you may want to alter your query so that it gets all posts, and change the second loop to break once the desired number of random posts is reached.
Notes
showposts is depracated. Replace showposts=1 with posts_per_page=-1

Categories