wordpress get_posts() overlapping printed records - wordpress

This is my very firs time to play around with wordpress. The theme I selected have a nice static look but that look disappears in dynamic mode. I followed some web tutorials to add my own function that fetches posts in one category and print in the position. I thought it was working fine until i noticed it is messing up the data. Here is my function first:
$args = array( 'posts_per_page' => 6, 'offset'=> 0, 'category' => 6,'orderby'=>'id','order'=>'desc' );
$posts = get_posts($args);
if(!empty($posts)){//yes we have posts
//loop results now
foreach($posts as $story) {
setup_postdata( $story );
the_ID();
echo '<br/>'.the_title();
echo '<br/>'.the_excerpt();
}//end loop
}//
The problem is the_ID and the_title() alaways take after the first record while the exceprt shows correct value of both records.
I did print array on posts variable and it holds two distinct ids and titles for the two records I have. But when I print, only the firs one is showing.
Someone suggested in some blog the correct way is :
$title = apply_filters('the_title', $story->title);
$content = apply_filters('the_content', $story->content);
but then the title and content variables are null/blank.
Any idea what I am doing wrong please? I am newbie to wordpress so sorry.

It is solved...avoid using get_posts() function and use WP_query() instead.

Related

Wordpress get_posts() shows only partially correct data of custom post inside user profile

I have a wordpress-based website where I'm trying to move some custom functionality that used to be just plain mysql table and some code to insert/update/show stuff from it. I'm trying to merge it in WP as custom posts so I can use filters, tags, pagination and such.
It supposed to show a few custom items inside the user profile (Ultimate Member). Like, user info, then 10 of user's top items of this kind, then on next tab 10 items of some other kind, etc.
But seems like things aren't as simple in WP, and you can't just toss things on top of each other and expect it to not overlap. >_> So when I'm trying to add a block with custom post type data, it returns only some of the data mixed with profile data mixed with nothingness.
Yeah, I get it, there's probably a profile loop and some data already inside variables, as far as I could understand from manuals. What I can't understand is how to fix it. Here's how it looks:
$args = array(
'author' => $uid,
'numberposts' => 10,
'post_type' => 'ff',
);
$ff = get_posts($args);
if($ff){
foreach($ff as $f){
setup_postdata($f);
the_content(); //shows what's needed, as well as ID, the_time() and some more
the_title(); //shows author's name instead of post title
the_tags(); //shows nothing, as well as excerpt, etc
get_the_excerpt(); //still nothing
$f->post_excerpt; //but this shows the excerpt, as well as print_r($f)
}
wp_reset_postdata();
}
Maybe someone could give a hint what am I missing? Thanks in advance!
Try using the post ID to get your data and echo it. A little more code but may work better.
// Set the global post up here
global $post;
$args = array(
'author' => $uid,
'numberposts' => 10,
'post_type' => 'ff',
);
$ff = get_posts($args);
if($ff){
foreach($ff as $f){
setup_postdata($f);
$id = $f->ID; // get post ID
$content = get_the_content($id); // get the content to echo later
$tags = get_the_tags($id); // use to get tags, these are not part of the get_posts return object
echo $content; // show the content
echo $f->post_title; // show the returned post title. can use get_the_title($id) and echo it if this does not work
// Display the tags after getting them above
foreach ($tags as $tag) {
echo $tag->name . ', ';
}
// You can get the excerpt this way too but you said your other worked okay
$excerpt = get_the_excerpt($id);
echo $excerpt;
}
wp_reset_postdata();
}
(Original) To elaborate. This sets up the global post object. Which is generally a requirement for your functions to work in the loop. Not always the case as I've found over the years, but a good practice if you're not using the post ID in the loop to get your data.

Wordpress Posts Id from query_posts

I'm using WordPress with a template that generates a pretty nice thumbnail for each post depending on Ids, and type of post. (ref:https://blinkdemo.wordpress.com/)
Since I've been asked to create a custom page that could show certain post from a category, I decided to create a query for a template page that checks the page slug and then list the posts containing a certain category + a tag ('comparativas').
The problem that I'm facing is that the list of post presented on the page doesn't show up the corresponding thumbnail on each post.
Thumbnails are generated dynamically basically with these lines:
$post_id = $post->ID;
$thumbnail_id = get_post_thumbnail_id( $post_id );
$thumbnail_image = wp_get_attachment_image_src( $thumbnail_id,$thumbnail_size );
The problem is that I couldn't find the way to send to the specific post ids to the function above, since the main $wp_query->posts; retrieves the page id instead of the post requested by the query_posts method.
The loops present the correct posts but when I echo the post->ID it shows the page id.
My query is:
global $wp_query;
// concatenate the query
$args = 'cat='.$idCategory.'&tag=comparativas';
query_posts( $args );
$posts = $wp_query->posts;
$current_id = get_the_ID(); //-> this returns the page id
If you could please tell me how to overwrite the global $wp_query; so the template can handle the corresponding ids for the list of post It would be great.
Any clue?
Best,
Juan
You could use, setup_postdata($post)
Then get_the_ID() works again :)
It doesn't work just because you aren't looping through them. You can do it many ways.
The 2 more common are the following:
overwrite the query with query_posts
$args = array('cat' => $idCategory,'tag' => 'comparativas');
query_posts($args);
if(have_posts()){
while(have_posts()){
the_post();
$current_id = get_the_ID(); // this return what you want now
the_title(); // this works as expected
}
}
wp_reset_query(); // get previous query back
get an array of WP_Post objects and setup_postdata or simply loop through them
$args = array('cat' => $idCategory,'tag' => 'comparativas');
$posts_i_want = get_posts($args);
foreach( $posts_i_want as $post ){
setup_postdata($post);
$current_id = get_the_ID(); // this return what you want now
the_title(); // this works as expected
}
wp_reset_postdata(); // get previous postdata back
I personally prefer the first in most cases
Cheers

What's the correct way to work with WordPress posts from the API?

What's the trick to working with WordPress posts as pure data structures?
Traditionally, you use "The Loop" and output data via functions like this:
<?php the_title(); ?>
<?php the_content(); ?>
These functions dump text directly into the response.
Using $wpdb, I can get back an array of posts like this:
$posts = $wpdb->get_results("SOME SQL HERE", OBJECT);
I then get a array of stdClass objects which are...Post-ish, I guess. They have properties for "post_title" and such, but there's no Permalink, which makes me think this isn't the "correct" Post object to use. Also, the "post_content" isn't complete HTML -- it still has line-breaks, etc.
When iterating this array, I've found I have to do this:
foreach ($events as $post)
{
setup_postdata($post);
...
This puts that post in the global scope. Then I can use the aforementioned functions to write content out, and use functions like this to get metadata:
$display_date = get_custom_field('display_date');
Is there a better way? This just seems...odd. Is there a way to get a complete representation of a post as an object, with all metadata, and everything else I need to manipulate it from the data level, rather than just assuming I want to dump output to the response?
You can use WP_Query instead, just like
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ) : $the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
endwhile;
All you have to prepare the $args arguments array to make a customized query, for example, you can use
// Display posts that have "books" tag
$the_query = new WP_Query( 'tag=books' );
or
// Display posts that have these categories
$the_query = new WP_Query( 'category_name=event,news' );
or more complex one like
// Display posts tagged with bob, under people custom taxonomy
$args = array(
'post_type' => 'post',
'people' => 'bob'
);
$the_query = new WP_Query( $args );
You can also use query_posts but it's a bit different than WP_Query and you can also use get_post and use a custom select query only when there is no way to get the desired result using WordPress' way. There is a nice answer about WP_Query vs query_posts() vs get_posts(), read this for better understanding.

wordpress query (shortcode) returns always the first post

I have made a shortcode inside my plugin, which is working great .
The shortcode needs to take some parameters and create a custom loop with output.
One of the parameters is how many posts to output the loop for ($markers)
$args=array(
'meta_key'=>'_mykey',
'post_status'=>'publish',
'post_type'=>'post',
'orderby'=>'date',
'order'=>'DESC',
'posts_per_page'=>$markers,
);
$wp_query = new WP_Query();
$wp_query->query($args);
if ($wp_query->have_posts()) : while (($wp_query->have_posts()) ) : $wp_query->the_post();
// do the loop using get_the_id() and $post->id
endwhile;endif;
wp_reset_query();//END query
On occations I will need to have data from ALL posts ($markers = '-1' ) and sometimes only one ($markers = '1' ) or muliple ($markers = 'x').
All of those work great on single pages / posts - but My problem is that when this function is in a place where I have more than one post (!is_single) and ($ markers = '1' )it will always return the data for the LATEST post , and not for the correct one ..
(for example in the default wordpress theme, where it would display10 posts - they will all be the same data )
It is obviously a problem of the $post->ID - but how can I have the correct post ID when doing a custom loop OUTSIDE the wp loop ?
I tried to ovverride the problem by
global $post;
$thePostIDtmp = $post->ID; //get the ID before starting new query as temp id
$wp_query = new WP_Query();
$wp_query->query($args);
// Start Custom Loop
if (!is_single()){
$post_id_t = $thePostIDtmp;}
else {
$post_id_t = $post->ID;}
and then use $post_id_t - but it did not seems to work ,
Should I not use get_the_id() ? or should I not use query (and use get_posts) ??
Any ideas / solutions / thoughts ??
I would use query_posts(http://codex.wordpress.org/Function_Reference/query_posts)rather than override the $wp object. You should be able to include as many loops on the page as you want with this. If you have problems with this you can use: http://codex.wordpress.org/Function_Reference/wp_reset_query just before you call it.
I find this: http://blog.cloudfour.com/wordpress-taking-the-hack-out-of-multiple-custom-loops/
takes a bit of the pain away too.
There are basically two sorts of querying posts in WordPress: Those that alter the main loop and those that do not. If you want to change the main loop like the one used to display category archive pages then use query_posts. It let's you do exactly that. Delete, change and append parameters of the default query to change the outcome of a typical page.
query_posts has some drawbacks though.
Then there are queries that are just used to get stuff out of the database to play around with e.g. displaying the latest post titles in the sidebar or the attachments of the current post.
To do that create a new WP_Query object that will build your custom loop independently of the main loop like so:
// The Query
$the_query = new WP_Query( $args );
// The Loop
while ( $the_query->have_posts() ) : $the_query->the_post();
echo '<li>';
the_title();
echo '</li>';
endwhile;
// Reset Post Data
wp_reset_postdata();
Then there is get_posts() which is like the little brother of WP_Query. It has an easier interface in my opinion and returns an array with the results that is easier to work with.
It looks like this:
$myposts = get_posts( $args );
foreach($myposts as $post) : setup_postdata($post);
echo "<li>";
the_title();
echo "</li>";
endforeach;
Inside the foreach template tags like get_the_id() will work.

How do I list all Entries with a certain tag in Wordpress?

I may just be missing this functionality, but does anyone know if there is a widget available:
I need to list the subject for all the entries that are associated with a given tag.
For example: I have 5 articles tagged with "Tutorial", I'd like to see a list as follows:
Tutorial 1: Installing the app
Tutorial 2: Customizing
Tutorial 3: Advanced edits
Tutorial 4: User managment
Does functionality like this exists in wordpress allready?
If you are comfortable with hacking WP you can try adding to your sidebar with wp_list_pages, http://codex.wordpress.org/Template_Tags/wp_list_pages.
Or there are plug-ins like Simple-Tags(http://wordpress.org/extend/plugins/simple-tags/) that help you manage your tags.
The nice thing about WordPress is there are lots of plug-ins available that can add functionality that the base app does not ahve, a quick search for plug-ins for tabs(http://wordpress.org/extend/plugins/search.php?q=tag) returned quite a list, sure it's a lot to dig through but that also helps you see what is available.
So i found an article on using custom queries. I modified the script to pull a specific tag, in this case "Open Source".
<?php
$querystr = "SELECT wposts.*
FROM $wpdb->posts wposts, $wpdb->terms wterms, $wpdb->term_relationships wterm_relationships, $wpdb->term_taxonomy wterm_taxonomy
WHERE wterm_relationships.object_id = wposts.ID
AND wterm_relationships.term_taxonomy_id = wterm_taxonomy.term_taxonomy_id
AND wterms.term_id = wterm_taxonomy.term_id
AND wterm_taxonomy.taxonomy = 'post_tag'
AND wterms.name = 'Open Source'
AND wposts.post_status = 'publish'
AND wposts.post_type = 'post'
ORDER BY wposts.post_date DESC";
$pageposts = $wpdb->get_results($querystr, OBJECT);
?>
<?php if ($pageposts): ?>
<?php foreach ($pageposts as $post): ?>
<?php setup_postdata($post); ?>
<?php the_title('<li>', '</li>'); ?>
<?php endforeach; ?>
<?php else : ?>
<?php endif; ?>
If you only want to list pages for one specific tag then this would work. However, say you wanted to give a listing of pages for each tag based on the current articles listed on the page.
You might create an array of all the tags using the get_the_tags() function during The Loop and then use that array to dynamically generate the WHERE statement for the query.
You can easily use get_posts to create an array of posts based on a set of parameters. It retrieves a list of recent posts or posts matching these criteria.
In your case, I would like to show how to display your posts under a specific tag ( in your case, Tutorial ) by creating a short code, which can be easily used anywhere later on in your site.
In your functions.php
function shortcode_tag_t() {
$uu_id=get_current_user_id();
$args = array(
'posts_per_page' => 10,
'tag' => 'Tutorial',
'post_type' => 'post',
'post_status' => 'publish'
);
$posts_array = get_posts( $args );
foreach ( $posts_array as $post ) : setup_postdata( $post );
$url = $post->guid;
echo"<li><a href='".$url."'>" .$post->post_title."</a></li>";
endforeach;
wp_reset_postdata();
}
add_shortcode('your_shortcode_name', shortcode_tag_t );
Now you have a list of 10 posts tagged under Tutorial.
Echo the created short code where ever you want to display the list.

Resources