WordPress storing all post titles of CPT in array - php

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);
?>

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>';
}

loop, push data into array

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);
...
}

Order numbers of foreach result

I got a function where i collect the data and then explode, this function is inside of a while, of wordpress
global $woocommerce;
global $wpdb;
$args = array( 'post_type' => 'product', 'stock' => 1, 'posts_per_page' => -1);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$order_id = $loop->post->ID;
foreach($product as $sku){
$sku = $product->get_sku();
$sku_s = explode('-', $sku);
$camp = $sku_s[0];
$itm_n = $sku_s[1];
}
<h6><span class="a1"><?php echo $camp;?></span>-<span class="a2"><?php echo $itm_n;?></span></h6>
MY output
is like this
<h6><span class="a1">581</span>-<span class="a2">20</span></h6>
<h6><span class="a1">581</span>-<span class="a2">50</span></h6>
<h6><span class="a1">581</span>-<span class="a2">1</span></h6>
<h6><span class="a1">581</span>-<span class="a2">6</span></h6>
<h6><span class="a1">581</span>-<span class="a2">9</span></h6>
581-20
581-1
581-9 .... so on..
But i need to sort the numbers for oder, for example
581-1
581-6
581-9....and so on...
Thanks for you help.
Create a comparison function for your skus i.e.
function myComparison(a,b) {
a.id<b.id;
}
then use that in a standard array sort
$skus.sort(myComparison);
Cannot see exactly how your objects are laid out but I hope this helps lead you top the right answer.
First off, this foreach loop doesn't make much sense. Why would you be iterating over $sku to immediately overwrite it with $product->get_sku()?
//what you wrote
foreach($product as $sku){
$sku = $product->get_sku();
$sku_s = explode('-', $sku);
$camp = $sku_s[0];
$itm_n = $sku_s[1];
}
//did you mean this?
foreach($products as $product){
$sku = $product->get_sku();
$sku_s = explode('-', $sku);
$camp = $sku_s[0];
$itm_n = $sku_s[1];
}
Assuming that you can identify which variable is extracted in each iteration (and that it resembles the corrected loop above) you can try one of two things.
(1) Have you tried passing the orderby to the WP_Query that you are running?
http://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
(2) You need to re-index your results so that your order is based on natural sort order of your SKUs.
while ( $loop->have_posts() ) : $loop->the_post();
$order_id = $loop->post->ID;
//create a new array to hold by SKU
$sortProducts = array();
foreach($products as $product){
$sortProducts[$product->get_sku()] = $product;
}
endwhile;
//sort natural order
ksort($sortProducts, SORT_NATURAL);
//notice that this is a different foreach loop here
foreach($sortProducts as $sku => $product){
$sku = $product->get_sku();
$sku_s = explode('-', $sku);
$camp = $sku_s[0];
$itm_n = $sku_s[1];
echo "<h6><span class=\"a1\">$camp</span>-<span class=\"a2\">$itm_n</span></h6>";
}
EXAMPLE OUTPUT IMAGE

PHP while loop

I have this very simple Wordpress while loop:
$loop = new WP_Query( args ) );
while ( $loop->have_posts() ) : $loop->the_post();
$data = grab_something( args );
echo $data;
echo "<br/";
endwhile;
This gives me something like:
datastring1
datastring2
anotherdata
somethingelse
and else
and so forth
(...)
I want to save these values from while loop as an array or variables, eg.
$data1 = "datastring1";
$data2 = "datastring2";
$data3 = "anotherdata";
(...)
How to? :)
Thanks!
You can save in array easily
$array=array();
while ( $loop->have_posts() ) : $loop->the_post();
$data = grab_something( args );
$array[]=$data;
endwhile;
print_r($data);
$array will store data from index 0 to the number of elements while loop iterate
Use a counter $i to keep track of the number, and then you can save the results either as an array or as a set of variables.
$loop = new WP_Query( args ) );
$i = 0;
while ( $loop->have_posts() ) : $loop->the_post();
$data = grab_something( args );
$i++;
$array[] = $data; // Saves into an array.
${"data".$i} = $data; // Saves into variables.
endwhile;
You only need to use the $i counter if you use the second method. If you save into an array with the above syntax, the indexes will be generated automatically.

Categories