How to pull information in Wordpress without a loop? - php

I'm using a custom post type, and pulling that information throughout the site via a loop. It seems unnecessary to create a loop every time I want to call information from the custom post type. Is there another way?
Here's an example of what the loop looks like, and how I call it.
<?php
$args = 'post_type=post-custom&order=ASC';
query_posts($args);
if ( have_posts($args) ) : while ( have_posts() ) : the_post();
$my_meta = get_post_meta($post->ID,'_my_meta',TRUE);
?>
<img src="<?php echo $my_meta['img'];?>">
<?php
endwhile;
endif;
?>
Any help is appreciated!

You need to use some kind of loop...If you don't want to use The Loop, you can use a standard foreach loop and get_posts(). Because you're only interested in getting post meta, you can use the fields argument to return an array of post IDs, instead of full post objects:
$args = array(
'post_type' => 'post-custom',
'order' => 'ASC',
'posts_per_page' => -1,
'fields' => 'ids'
);
$post_ids = get_posts( $args );
foreach ( $post_ids as $id ) {
$meta = get_post_meta( $id, '_my_meta', true );
echo '<img src="' . $meta['img'] . '">';
}
As a final note, you should basically never use query_posts().

Related

In wordpress how to get post loop inside another loop

I want to get latest post based on author loop.
this is my code:
function display_artist_func() {
$out_args = array(
'post_type' => 'product',
'author' => 1,
'showposts' => 3
);
$out_loop = new WP_Query($out_args);
while ($out_loop->have_posts()) :
?>
<div><?php echo get_avatar( get_the_author_email(), '80' ); ?> </div>
<?php
//$product = wc_get_product( $product->id );
$args = array(
'post_type' => 'product',
'showposts' => 10,
'orderby' => 'date',
'order' => 'DESC'
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); global $product;$author = get_user_by( 'id', $product->post->post_author ); ?>
<li>
<?php
if ( has_post_thumbnail( $loop->post->ID ) )
echo get_the_post_thumbnail( $loop->post->ID, 'shop_catalog' );
else
echo '<img src="' . woocommerce_placeholder_img_src() . '" alt="Placeholder" width="65px" height="115px" />';
?>
<h3><?php the_title(); ?></h3>
<h4><?php echo $author->display_name;?></h4>
<div><?php echo get_avatar( get_the_author_email(), '80' ); ?> </div>
<?php
//echo $product->get_price_html();
//woocommerce_template_loop_add_to_cart( $loop->post, $product );
?>
</li>
<?php
endwhile;
endwhile;
wp_reset_query();
}
add_shortcode( 'display_artist', 'display_artist_func' );
there is 2 loop:
outside loop get the 3 author.
inside loop get the 3 post based on author from outside loop.
in outside loop a want to display author avatar.
but this code not work.
Your problem is that you're never setting up the post data in your outer loop. It looks to me like this code creates an endless loop? The function get_the_author_email() is actually deprecated, but what its doing is using global $authordata.
In your inner loop, you call:
$loop->the_post();
which is going to take your current query, setup postdata for the active post and then remove it so it no longer returns in your call to have_posts(). You're missing a call to:
$out_loop->the_post();
And so your postdata isn't setup, and you're going to create an endless loop.
NOW with all that said
To be perfectly honest your code doesn't look like it makes a lot of sense. Your 'outer loop' is querying products with one specific hard-coded author ID, but the only thing that outer post is used for IS to get the author email. The way its written - the author is going to be the same for every run of $out_loop.
So I think you still may be missing some logic here - I don't know from your description exactly how its supposed to work, but as is - if you're just looping through products, there's no need for two loops here.

Can I compare a category slug in wordpress to a page title?

I have a structured my blog posts to have categories, and the slugs of these categories are identical to some custom-post post titles.
I want to run a link from the post to the custom-post page using these matching slugs.
In single.php I am trying to run this code... but instead of returning the information of the custom-post it returns the information of the current post
<?php
$categories = get_the_category();
if ( ! empty( $categories ) ) {
foreach( $categories as $category ) {
$current_slug = $category->slug;
$args = array(
'post_type' => 'community',
'name' => $current_slug
);
$cat_query = new WP_Query($args);
if ( $cat_query->have_posts() ) {
the_title( sprintf( '<h3 class="post-title">', esc_url( get_permalink() ) ), '</h3>');
wp_reset_postdata();
}
}
}
?>
My hope for this code was -> if a post is given a category with the slug: 'cat-one' then at the top of the post would be a link to the CAT ONE page (which is a custom post type page with a url ..../communities/cat-one.
This should absolutely be possible. There's a few issues with your code however, and I've cleaned up a few other things.
You've got the code set up to loop through the categories, but you're using name in your WP_Query() args, and don't have a loop set up for the results. According to the WP_Query() docs, name will return a single post - if you want more than one, (since WP 4.4) you can use post_name__in instead. Also, and namely the larger issue with your code, is that you're never set up the internal variables inside your $cat_query. I've also added a while loop so it will spit out multiple category links.
Without defining the internal variables with the $query->the_post() method (or passing a $post_id argument to them), the post variable functions like the_title() and get_permalink() will use the current post, which is what your'e seeing now.
This should get you started:
if( $categories = get_the_category() ){
foreach( $categories as $category ){
$args = array(
'post_type' => 'community',
'post_name__in' => $category->slug
);
$cat_query = new WP_Query( $args );
if( $cat_query->have_posts() ){
while( $cat_query->have_posts() ){
$cat_query->the_post();
the_title( sprintf( '<h3 class="post-title">', esc_url( get_permalink() ) ), '</h3>');
}
wp_reset_postdata();
}
}
}

html h tag with text value in to php

This not working out for me. Any tips or example to make it work? post args = array($tags) didnt get value correctly.
<h6>seal</h6>
<h6>mark</h6>
<?php
$tags = "<script>document.write(h6);</script>";
$args = array(
'post_type' => 'Rune',
'posts_per_page' => -1,
'tag' => $tags,
);
$lastposts = get_posts( $args );
foreach ( $lastposts as $post ) :
setup_postdata( $post ); ?>
<?php the_content(); ?>
<?php endforeach;
wp_reset_postdata();
?>
$tags is going to equal the string <script>document.write(h6);</script>. PHP isn't going to evaluate your JS.
The result you're seeing is correct under the circumstances. You need to change the way you're getting tags in order to pass them in to your $args array.
Without knowing more about the problem I can't suggest a better approach to take.

Wordpress combine query and output different styling dependant on post type

I have two WordPress post types the normal 'post' and a custom post type called 'notes'. I want to combine both and sort them by date. I managed to find the combine query and that's working fine. The problem is I'd like to have different styling for notes. I thought I could do a wordpress if_singlular('notes') to try and target it.. but I'm guessing it's getting lost when the merge happens.
Does anyone know how I could achieve this functionality?
Many thanks!
My php:
<?php
// An example of creating two separate WP queries, combining the results,
// sorting by date and formatting the results for us in a loop like a regular query.
// order the posts by date in descending order (should go in functions.php to keep things tidy)
function order_by_date( $a, $b )
{
return strcmp( $b->post_date, $a->post_date );
}
// get the posts for the first query
$q1_args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$q1_posts = get_posts( $q1_args );
// get the posts for the second query
$q2_args = array(
'post_type' => 'notes',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$q2_posts= get_posts( $q2_args );
// Merge the post arrays together, and sort by date using the order_by_date function
$final_posts = array_merge( $q1_posts, $q2_posts );
usort( $final_posts, 'order_by_date' );
// Loop over the posts and use setup_postdata to format for template tag usage
foreach ( $final_posts as $key => $post ) {
setup_postdata( $post );
// Now we can use template tags as if this was in a normal WP loop
foreach ( $final_posts as $key => $post ) {
setup_postdata( $post );
// Now we can use template tags as if this was in a normal WP loop
echo '
<article class="item shortNote">
<div class="snMeta clearfix">
<img src="'.get_bloginfo('template_url').'/assets/images/sn-icon.png" alt="Short Note" />
<span class="metaDate">'. get_the_date('M / d / Y').'</span>
<strong>Short Note</strong>
</div>
<h2>'.get_the_title().'</h2>
</article>';
}
}
?>
Ok so this should do it:
<?php
// An example of creating two separate WP queries, combining the results,
// sorting by date and formatting the results for us in a loop like a regular query.
// order the posts by date in descending order (should go in functions.php to keep things tidy)
function order_by_date( $a, $b ) {
return strcmp( $b->post_date, $a->post_date );
}
// get the posts for the first query
$q1_args = array(
'post_type' => 'post',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$q1_posts = get_posts( $q1_args );
// get the posts for the second query
$q2_args = array(
'post_type' => 'notes',
'posts_per_page' => -1,
'post_status' => 'publish'
);
$q2_posts= get_posts( $q2_args );
// Merge the post arrays together, and sort by date using the order_by_date function
$final_posts = array_merge( $q1_posts, $q2_posts );
usort( $final_posts, 'order_by_date' );
// Loop over the posts and use setup_postdata to format for template tag usage
foreach ( $final_posts as $key => $post ) {
$post_type = $post->post_type;
setup_postdata( $post );
// Now we can use template tags as if this was in a normal WP loop
<article class="item shortNote ' . $post_type . '">
<div class="snMeta clearfix">
<img src="'.get_bloginfo('template_url').'/assets/images/sn-icon.png" alt="Short Note" />
<span class="metaDate">'. get_the_date('M / d / Y').'</span>
<strong>Short Note</strong>
</div>
<h2>'.get_the_title().'</h2>
</article>';
}
?>
I just had to test it on my server to see if it works. So I added the $post_type variable that should return the post type, and then I just put that in your class in the <article> tag, so you can differentiate :)
Tip:
When in doubt what your loop outputs, always do print_r(). This will show you what you are dealing with (arrays, strings, objects) so you easily know what to target :)
Hope this helps.

Make Custom Post Archive in Ascending Order

I'm trying to make my custom post type archive page reverse the display order, and want to make it ASCENDING. This is my code:
<?php
while ( have_posts() )
{
the_post();
?>
--MY CODE--
<?php } ?>
I tried putting query_posts('order=asc'); before the while loop, but this caused my loop to draw from the regular posts, not my custom post type.
Any help would be appreciated! Thanks
Use a simple query here. Don't use query_posts, never ever. Use WP_Query. You should do
<?php
$args= array(
'order' => 'ASC',
'post_type' => 'NAME OF YOUR CPT'
);
$the_query = new WP_Query( $args );
?>
<?php while ( $the_query->have_posts() ) :$the_querythe_post(); ?>
You need to add your ordering to the existing query. The way you did it overwrote the query. Try this:
global $query_string;
query_posts( $query_string.'&order=ASC' );
while( have_posts() ): the_post();
// rest of your code
endwhile;

Categories