loop, push data into array - php

I try to push each data from the Wordpress loop into array:
<?php
$array = array();
$args = -1;
$posts = get_posts($args);
foreach ($posts as $post){
array_push( $array, array(
"title" => get_the_title(),
//capire perchè non stampa il contenuto
"cont" => get_the_content()
));
}
print_r($array);
?>
The problem was that I want to have final data into the multidimensional array but I have only the title value but NOT the content.

Your loop is fine. To access the content get_the_content() you need to use setup_postdata. It sets up the global post data for template tags.
foreach ($posts as $post){
setup_postdata($post);
...
}

Related

Foreach loop not looping through

I have a foreach loop which is only returning the title of the latest post. For example, I have the post test as the latest post in products and in the loop defined below, when doing var_dump, it only dumps the title for the latest post called "test".
Why is this?
Approach:
<?php
$args = array(
'post_type' => 'products',
'post_parent' => 0,
'posts_per_page' => 15,
);
$products = get_posts( $args );
if ($products){
foreach ($products as $product) : setup_postdata( $product );
var_dump(get_the_title());
endforeach;
wp_reset_postdata();
}
?>
foreach ($products as &$product) : setup_postdata( $product );
Please try this in your foreach loop.
Use this one
if ($products){
foreach ($products as $product) : setup_postdata( $product );
echo get_the_title($product->ID));
// or echo $product->post_title;
endforeach;
wp_reset_postdata();
}
It's strange but when you're wanting to use template tags along with setup_postdata() you need to use the global $post variable. setup_postdata() doesn't actually set that variable it sets some related global variables and runs the the_post action. You can see what happens here
To do what you want to do with out passing ids etc for every template function call you would need to setup your loop like this.
global $post;
foreach ( $products as $post ) {
setup_postdata( $post );
// Your code here.
}
wp_reset_postdata();// Reset the global $post variable and re-setup postdata.

Get list of values, then all post titles with that value

I have a working wordpress loop which displays all posts of a certain meta_query value. The only issue is that the values are repeated. For example, if I have two posts with the value "Blue" then both posts appear in the loop, which makes "Blue" appear twice.
What I would like is for "Blue" to appear once, and underneath it, a list of all post titles with that value.
Here's my current query:
<?php
$the_query = new WP_Query(array(
'post_type' => 'post',
'post_status' => 'publish',
'meta_key' => 'colors',
));
while ( $the_query->have_posts() ) : $the_query->the_post();
$colors = get_field('colors');
if( $colors ): foreach( $colors as $color ):
endforeach;
endif;
echo' <div><h2>'.$color.'</h2><div>'.get_the_title( $post_id ).'</div></div>';
endwhile; wp_reset_postdata();?>
I tried using an array for the titles, but it just returned "Array"
$titles = get_the_title();
$title_names = array();
foreach ($titles as $title){
$title_names[] = get_the_title($id);}
echo $title_names
I'm thinking I need another if statement somewhere with an array? Or maybe I'm approaching this from the wrong direction.
You would want to try something like this:
$results = [];
while ( $the_query->have_posts() ) {
$the_query->the_post();
$colors = get_field('colors');
if( !empty($colors) ) {
foreach( $colors as $color ) {
$results [$color][]['title'] = get_the_title();
$results [$color][]['link'] = get_attachment_link();
}
}
}
foreach ($results as $color => $posts) {
echo "<div><h2>{$color}<h2>";
foreach($posts as $post) {
echo "<div>{$post['title']}</div>";
}
echo '</div>';
}

WordPress storing all post titles of CPT in array

I have a CPT 'jobs' and would like to store all post titles in an array.
This is what I've tried but for some reason I get Trying to get property of non-object error.
Here's what I've tried:
$myarray = array();
$jobs = new WP_Query( array( 'post_type' => 'jobs') );
foreach ($jobs as $job):
$myarray = $job->post_title;
endforeach;
echo $myarray;
I've dumped the $jobs wp_query and I can see the post_titles there.
Make use of get_posts. It only returns the $posts property from the query object. Also, you are missing the array syntax ([]) after $myarray. As it stands, $myarray will only hold the current post title of the post being looped through. As a final note, you cannot echo an array, you can only echo strings
$myarray = array();
$jobs = get_posts( array( 'post_type' => 'jobs') );
foreach ($jobs as $job):
$myarray[] = $job->post_title;
endforeach;
var_dump( $myarray );
try this way..
<?php
$myarray = array();
$jobs = new WP_Query( array( 'post_type' => 'post','orderby=title&order=DESC') );
global $post;
if($jobs->have_posts()){
while ($jobs->have_posts()):$jobs->the_post();
$myarray[] = $post->post_title;
endwhile;
}
echo "<pre>";
print_r($myarray);
?>

Can't get most recent post from categories

I'm trying to get a category and loop through its sub categories getting one post from each of those sub-categories. Below is my code:
<?
$homepage_cat = get_category_by_slug( 'home-page-slider' );
$id = $homepage_cat->cat_ID;
print($id);
$sub_cat = get_categories('hide_empty=0&child_of=' . $id);
print_r($sub_cat);
foreach ($sub_cat as $key => $cat)
{
echo $cat->term_id;
query_posts('cat=' . $cat->term_id);
if ( have_posts() )
{ echo '<h1> HELL YEAH </h1>';
while ( have_posts() )
{
echo '<h1>' get_the_title(); '</h1>';
} // end while
} // end if
} //end foreach
?>
The code is not returing any posts as HELL YEAH is not being echoed. Can anyone suggest a solution?
Use get_posts() not query_posts, it is better for these kinds of situations.
$args = array('posts_per_page' => 1, 'category' => $cat->term_id);
$posts = get_posts($args);
foreach($posts as $post) : setup_postdata( $post ) ?>
<h1><?php get_the_title(); ?></h1>
<?php endforeach; ?>
There are quite a few problems here
First of all, never use query_posts to construct custom queries. It breaks the main query, is unreliable and outright fails in most cases in pagination
Secondly, you have to reset your postdata after every custom query
Thirdly, never use short tags. Always use full tag ie <?php and not just <?
Lastly, you are missing the_post() which should return post objects
Your query should look something like this
<?php
$homepage_cat = get_category_by_slug( 'home-page-slider' );
$id = $homepage_cat->cat_ID;
print($id);
$sub_cat = get_categories('posts_per_page=1&hide_empty=0&child_of=' . $id);
print_r($sub_cat);
foreach ($sub_cat as $key => $cat)
{
echo $cat->cat_ID;
$q = new WP_Query('cat=' . $cat->cat_ID);
if ( $q->have_posts() )
{ echo '<h1> HELL YEAH </h1>';
while ( $q->have_posts() )
{
$q->the_post();
echo '<h1>' get_the_title(); '</h1>';
} // end while
} // end if
wp_reset_postdata();
} //end foreach
?>
Replace this
$post_args = array(
'showposts' => 1,
'cat' => $cat->term_id
);
with this.
$post_args = array(
'posts_per_page' => 1,
'category' => $cat->term_id
);
I hope it'll work.

Why Wordpress query_post is not showing correct posts?

I'm trying to query wordpress post by using query_posts and trying to save them in an array so that I get retrieve the post from array. This is what I'm doing,
$posts= array();
$args = array('posts_per_page' =>3,'cat' => 3 );
$posts[] = query_posts( $args );
global $post;
if ( ! empty($posts) ) :
foreach ($posts as $post) {
setup_postdata($post);
echo get_the_title();
}
wp_reset_postdata();
endif;
wp_reset_query();
When I run this script it shows a post which is not in cat 3. but if I do print_r($post) it shows the correct three posts. Any idea of where I'm getting wrong?
No need to declare it as an array:
global $post;
$args = array('posts_per_page' => 3,'cat' => 3);
$query = query_posts($args);
foreach ($query as $post) {
setup_postdata($post);
the_title();
}
wp_reset_query();
This one should work also WP_Query or get_posts() is preferred method for secondary queries.
global $post;
$posts_args = array('cat' => 3, 'posts_per_page' => 3);
$posts_query = new WP_Query($posts_args);
$posts_arr = $posts_query->get_posts();
if ( ! empty($posts_arr) ) :
foreach ($posts_arr as $post) {
setup_postdata($post);
echo get_the_title();
}
wp_reset_postdata();
endif;
wp_reset_query();
Remember that query_posts modifies the main loop, so probably the post that is not from cat = 3 is from the main loop. Try to create a new query with get_posts.
$posts = get_posts('posts_per_page=3&cat=3');
global $post;
if (!empty($posts)):
foreach ($posts as $post):
setup_postdata($post);
echo get_the_title();
endforeach;
wp_reset_postdata();
endif;

Categories