I'm looking to store the results from a WP_query as a $variable and access it outside of the loop. I can only seem to get the first result.
It's is important the $book_data from the results can be accessed outside of the loop.
Code
$args = array(
'post_type' => 'books',
'paged' => $paged,
);
$wp_query = new WP_Query( $args);
$count = $wp_query->post_count;
while ($wp_query->have_posts()) : $wp_query->the_post();
$book_name = get_post_meta( get_the_ID(), 'book_name', true );
$book_author = get_post_meta( get_the_ID(), 'book_author', true );
$book_data = $book_name . ' - ' . $book_author . '<br />';
endwhile;
wp_reset_postdata();
// Access data outside of Loop
echo $book_data;
Current Result
The Stand - Steven King
Desired Result
The Stand - Steven King
War and Peace - Leo Tolstoy
Middlemarch - George Eliot
You're basically overwriting your variable on iteration. You could either a) display the books in the loop, or if as you mentioned you want to use that data in multiple places, you can b) add to an array and display at your discretion.
// Create empty array for book data
$book_data = [];
$args = array(
'post_type' => 'books',
'paged' => $paged,
);
$wp_query = new WP_Query( $args);
$count = $wp_query->post_count;
while ($wp_query->have_posts()) : $wp_query->the_post();
$book_name = get_post_meta( get_the_ID(), 'book_name', true );
$book_author = get_post_meta( get_the_ID(), 'book_author', true );
// Add each book to the array
$book_data[] = $book_name . ' - ' . $book_author;
// can also just echo the above out with:
// echo $book_name . ' - ' . $book_author . '<br />';
endwhile;
wp_reset_postdata();
// Access data outside of Loop
foreach ($book_data as $book) {
echo $book . '</br>;
}
Related
how to get the current category name of the page inside functions.php?
this is for adding a load more functionality based on a category per page.
this is what my current code looks like
add_filter('query_vars', 'registering_custom_query_var');
function registering_custom_query_var($query_vars)
{
$query_vars[] = 'id'; // Change it to your desired name
return $query_vars;
}
function more_post_ajax() {
global $wp_query;
$ppp = (isset($_POST["ppp"])) ? $_POST["ppp"] : 1;
$page = (isset($_POST['pageNumber'])) ? $_POST['pageNumber'] : 0;
$category = get_category(get_query_var('cat'));
header("Content-Type: text/html");
$args = array(
'post_type' => 'post',
'posts_per_page' => $ppp,
'category_name' => $category->name,
'paged' => $page,
);
$loop = new WP_Query($args);
$out = '';
if ($loop->have_posts()) : while ($loop->have_posts()) : $loop->the_post();
$out .= '<div class="article_card"><div class="article_card__thumbnail">' . get_the_post_thumbnail() . '</div><div class="article_card__content"><h3>' . get_the_title() . '</h3><p class="body-small">' . wp_trim_words( get_the_excerpt(), 60 ) . '</p><a a href="' . get_the_permalink() . '"> Learn more →</a></div></div>';
endwhile;
endif;
wp_reset_postdata();
die($out);
}
add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');
add_action('wp_ajax_more_post_ajax', 'more_post_ajax');
Are you looking for something like this?
<?php
$post = get_post();
if ( $post ) {
$categories = get_the_category( $post->ID );
var_dump( $categories );
}
I want to get all the product data in the WooCommerce (product sku, name, price, stock count, availability and etc.) Can I do that using wp-query?
This way you can get all products via wp_query :
global $wpdb;
$all_product_data = $wpdb->get_results("SELECT ID,post_title,post_content,post_author,post_date_gmt FROM `" . $wpdb->prefix . "posts` where post_type='product' and post_status = 'publish'");
And if you want further product data then it will be like this :
$product = wc_get_product($product_id);
$product->product_type;
get_post_meta($prodyct_id, '_regular_price');
$product->get_available_variations();
Thanks for all reply.I have resolve that like billows
$full_product_list = array();
$loop = new WP_Query(array('post_type' => array('product', 'product_variation'), 'posts_per_page' => -1));
while ($loop->have_posts()) : $loop->the_post();
$theid = get_the_ID();
$product = new WC_Product($theid);
if (get_post_type() == 'product_variation') {
// ****************** end error checking *****************
} else {
$sku = get_post_meta($theid, '_sku', true);
$selling_price = get_post_meta($theid, '_sale_price', true);
$regular_price = get_post_meta($theid, '_regular_price', true);
$description=get_the_content();
$thetitle = get_the_title();
}
// add product to array but don't add the parent of product variations
if (!empty($sku))
$full_product_list[] = array("PartyID" => (int) $party_id,"Description"=> $description,
"ExternalNumber" => $theid, "ProductName" => $thetitle, "sku" => $sku,
"RegularPrice" => $regular_price, "SellingPrice" => $selling_price,
"ExternalProductCategoryId" => $cat_id, "ExternalProductCategoryName" => $cat_name);
endwhile;
When your building out your query set the post type to be product
$query->set('post_type', 'product');
And that will only search through woocommerce products.
Also if you are creating a theme, you can take any file from the /wp-content/plugins/woocommerce/templates/ directory and put it inside of /wp-content/themes/<yourTheme>/woocommerce to override any woocommerce page.
you can write this code in page that you want to display all product information
<?php
$args = array(
'post_type' => 'product',
'posts_per_page' => 10
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<br />' . woocommerce_get_product_thumbnail().' '.get_the_title().'';
global $product;
//echo $product;
echo $product->get_id();
echo $product->get_name();
echo $product->get_sale_price();
echo $product->get_regular_price();
echo $product->get_sku();
echo $product->get_low_stock_amount();
echo $product->get_review_count();
echo $product->get_short_description();
$ratting = $product->get_rating_counts();
for($i = 0 ; $i < count($ratting); $i++) {
echo $ratting[i];
}
endwhile;
wp_reset_query();
?>
This is an old question; the answers using WP_Query() are obsolete since 2018.
See my answer here.
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.
Wordpress ninjas... I require some help regarding pagination.
I have the following code :
global $wp_query;
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array_merge( $wp_query->query_vars,
array(
'post_type' => 'attachment',
'posts_per_page' => 10,
'paged' => $paged
)
);
How come $query->max_num_pages returns 0 ?
And is there a way to alter the original archive query with the $query->max_num_pages ?
[EDIT]
In Addition to the above code I have the following
$output = '<div class="download-attachments left_content_container"><ul>';
//this does not retrieve anything
$query = new WP_Query( $args );
// this does retrieve posts
$attachments = get_posts( $args );
// this block is only used for testing purposes..
// ie. it is not being executed because the query does not return anything, Whilst get_posts() works
if( $query->have_posts() ){
while( $query->have_posts() ){
$query->the_post();
echo the_ID();
}
}
foreach ($attachments as $attachment) {
setup_postdata($attachment);
//get attachments metadata etc.
$url = wp_get_attachment_url( $attachment->ID );
$title = get_the_title( $attachment );
$caption = $attachment->post_excerpt;
$size = get_readable_size( filesize(get_attached_file( $attachment->ID )) );
$icon = get_icon_for_attachment( $attachment->ID );
$mime = get_post_mime_type( $attachment->ID );
$date_added = $attachment->post_date;
$filename = ( !$caption == '' ) ? $caption : $title ;
$description = ($attachment->post_content != '') ? '<span class="attachment-author"><span class="attachemnt-label">Added by: ' . $attachment->post_content . '</span></span>' : '';
$output .= '<li class="'.$mime.'">
<img class="attachment-icon" src="'.$icon.'" alt="pdf">
'. $filename .' '.$description.'
<span class="attachment-date"><span class="attachment-label">Date added: </span>'.$date_added.'</span>
<span class="attachment-size"><span class="attachment-label">Attachment size: </span>'.$size.'</span></li>' ;
}
$output .= '</ul></div>';
echo $output;
echo '<div class="paging pull-left">';
$paged = $wp_query->get( 'paged' );
if ( ! $paged) {/* do nothing */ ;}
else { bootstrap_pagination(); var_dump($wp_query->max_num_pages); // returns 0 }
echo '</div>';
You have a couple of problems here. You don't need to call the global $wp_query because you are not going to use it. Secondly, array_merge is totally out of place. This should not be used at all in this situation. Your code should look something like this
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'attachment',
'posts_per_page' => 10,
'paged' => $paged
)
);
$query = new WP_Query( $args );
For more info on custom queries with WP_Query have a look here
I' am learning how to make a WordPress Plugin. I did make few simple plugins but not as complicated as this one. It's a Events Calendar. The var_dump from the function "nc_get_start_date()" on the page it outputs wrong dates.
The output from the var_dump(nc_get_start_date());
string(32) "1970-01-01,1970-01-01,1970-01-01"
This is what the function should return in real
23-12-2013, 25-12-2013, 26-12-2013
In the function.php on the plugin folder. This is the codes
/* Query to get the events post from the database */
function get_nc_events(){
global $post;
$query = new WP_Query(
array(
'post_type' => 'events',
'post_status' => 'publish',
'posts_per_page' => -1,
'order' => 'ASC'
)
);
return $query;
}
/* Get the start date from the above function */
function nc_get_start_date(){
$query = get_nc_events();
while ( $query->have_posts() ) : $query->the_post();
$nc_event_id = $post->ID;
$wnc_start_date = get_post_meta( $nc_event_id, 'wnc_start_date');
$wnc_start_date = $wnc_start_date[0];
$wnc_start_date = date("Y-m-d", strtotime($wnc_start_date));
$wnc_start_date_array .= "$wnc_start_date,";
endwhile;
return rtrim($wnc_start_date_array, ",");
}
When I write the code in page-caledar.php without the function it renders everything prefectly.
$query = get_nc_events();
while ( $query->have_posts() ) : $query->the_post();
$nc_event_id = $post->ID;
$wnc_start_date = get_post_meta( $nc_event_id, 'wnc_start_date');
echo $wnc_start_date = $wnc_start_date[0] . "<br/>";
endwhile;
Problem Solved. Thanks everyone. The problem was in this function
/* Get the start date from the above function */
function nc_get_start_date(){
global $post;
$query = get_nc_events();
while ( $query->have_posts() ) : $query->the_post();
$nc_event_id = $post->ID;
$wnc_start_date = get_post_meta( $nc_event_id, 'wnc_start_date');
$wnc_start_date = $wnc_start_date[0];
$wnc_start_date = date("Y-m-d", strtotime($wnc_start_date));
$wnc_start_date_array .= "$wnc_start_date,";
endwhile;
return rtrim($wnc_start_date_array, ",");
}
I didn't make global $post;