Display WP_Query results in a specific order - wordpress

I have this WP_Query:
<?php $query = new WP_Query(
array( "post_type" => "post",
"showposts" => "12"
) );
while ($query->have_posts()) : $query->the_post(); ?>
...
My goal is to use this function for displaying the posts in this order:
1 3 5 7 9 11 2 4 6 8 10 12
So that 6 rows with 2 columns each will be displayed like this:
1 2
3 4
5 6
7 8
9 10
11 12
The page logic that I have requires this specific order.
At the moment I'm achieving this using shortcodes, but that means 12 mySQL queries instead of just 1 and having the result displayed in this custom order.
I know that I could do this if I setup a custom field where to specify the order in which I want the result provided.
However, I don't want to complicate an editor's life, so I want this to be achieved by stating somewhere the order in which I want the WP_Query results displayed.
I had a look at post__in, but that would involve manually providing the posts IDs, so it is not an option since this is the home page and the post numbers will always be different.
Basically, no matter which are the latest posts (what ID they have), I want to display them like this:
1,3,5,7,9,11,2,4,6,8,10,12
Instead of the default order, which is:
1,2,3,4,5,6,7,8,9,10,11,12

There is a very simple and easy way to achieve this. You can take advantage of the built in loop counter, $wp_query->current_post. There is no need for custom queries etc. Inside your loop, do something like this
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php /* Start the Loop */ ?>
<div class="entry-content <?php if( $wp_query->current_post%2 == 1 ) echo ' left-post'; ?>">
<?php get_template_part( 'content', get_post_format() ); ?>
</div>
<?php endwhile; ?>
This will add a class of left-post to every second post. You can now style accordingly (float your entry-content left and set the width to about 48%). To avoid wacky styling problems, simply add .left-post { clear: left; } to your stylesheet

It's really simple, actually.
Install a plugin called Simple Page Ordering: https://wordpress.org/plugins/simple-page-ordering/
And add the 'oderby' => 'menu_order' argument in your query.
Also, instead of using "showposts", use posts_per_page.
thanks.

I'm sorry to say that it's unlikely you'll achieve this using WP_Query. I believe you're likely approaching this in the wrong way.
Your results will need to be returned in a structured and uniform way, and you'll have to handle them appropriately, regardless of the method to return them. Doing it the way you're proposing can easily cause issues with pagination, and MySQL doesn't have an ordering algorithm to achieve it, so any query written will be slow. You'll limit yourself moving forward too.
I'm guessing you are doing something with columns on the web page, which is why you want the results in this order. If this is the case there are lots of ways to achieve it without having to reorder your results in this manner.
Without trying to sound offensive, it sounds like a case of over-complicating the problem, and it can be solved earlier on in the process rather than tinkering with the data source itself.
If you can send over what you're doing with the results themselves (maybe better in a different question?) then you might get better results.

Related

What variables are in the Drupal $primary_nav variable

How would I pull an array of all the labels and links for every menu item in the $primary_nav variable?
You can just use php's print_r(). Or use a dedicated module like devel : it provides helpers which pretty print variables including arrays and objects. It also provides a clear cache button, can generate random nodes, etc.
I think devel's dprint_r() and dpm() are the most used functions and the most useful I guess for Drupal developers when it comes to print and debug variables.
In your case, $primary_nav is a processed variable : it is first prepared by functions from the registered theme, then it can be altered in process or preprocess hooks provided by themes and/or modules.
Knowing that, you can either print it right from the template you are working on, like page.tpl.php :
<?php if (!empty($primary_nav)): ?>
<!--<?php print render($primary_nav); ?>-->
<?php dpm($primary_nav); ?>
<?php endif; ?>
.. or debug it "earlier" in a process or preprocess function like :
function some_preprocess_page(&$variables) {
dpm($variables['primary_nav']);
}
Also, if you don't know what is going on or what variables are available in a template, combining php's get_defined_vars() with a pretty print function can be vey helpful : dpm(get_defined_vars());

How to change the excerpt depending on category - WordPress

I was wondering how to change the excerpt depending on category in WordPress. I have changed the default amount but I need this amount for some boxes on the home page and I need it to display more words on the blog page of the website.
Thanks,
Charlie
I would suggest a custom excerpt that you can use and change as you wish. I've recently done a complete answer on the_excerpt(). This comes from that answer. You can also check out the complete answer here
CUSTOM EXCERPT LENGTHS
Sometimes you need to display simple excerpts of different lengths and it is not viable to write an excerpt for every post/function/page. Here is a nice small little function using wp_trim_words
function wpse_custom_excerpts($limit) {
return wp_trim_words(get_the_excerpt(), $limit, '' . ' …' . __( 'Read more »', 'wpse' ) . '');
}
What this little function do is taking get_the_excerpt trimming that to $limit set by the user and returning the text with a read more link at the end.
You can call this excerpt as follow in your template
echo wpse_custom_excerpts($limit);
where $limit will be your word count, so an excerpt of 30 word will be
echo wpse_custom_excerpts(30);
Just one thing to remember here, if you set your limit to more that 55 words, only 55 words will be returned as the excerpt is only 55 words in length. If longer excerpts are needed, use get_the_content instead.

Does query_posts have an effect on get_the_category?

I am having trouble debugging a situation, and I think some better background information on how these systems work would be very helpful. I know that the use of the function query_posts() is strongly discouraged. But let's just assume that there is nothing I can do to remove it from the code. Specifically the query is changed to pull posts of a post_type (a post_type specific to the theme I am using). This is what the query looks like after it has been changed:
posts_per_page=10&paged=0&post_type=project
Then the loop begins and it can successfully grab the titles for each post. But when I call get_the_category() it returns an empty array, even though all of the posts have categories. I verified that it was an empty array with var_dump.
I am do not have a super strong understanding of how these systems work, so the emphasis on not using query_posts has me worried. Is there any possible interaction between query_posts and get_the_category() that could cause it to not work correctly?
Why not using WP_Query()? Im not sure it is cause by query_posts, but query_posts() alters Wordpress Main Loop (global $wp_query).
You can use the WP_Query method like this, by replacing with your query_posts loop
$newLoop = new WP_Query('posts_per_page=10&paged=0&post_type=project');
if ( $newLoop->has_posts() ) {
while ( $newLoop->has_posts() ) { $newLoop->the_post();
the_title(); // Your title
var_dump ( get_the_category() ); // this should not be empty if category assigned to current post
}
}
If you still want to go with query_posts try one of the methods below:
Try passing post id manually:
get_the_category( get_the_ID() ); // Must be in loop
Or try adding this:
// after endwhile of query_posts
wp_reset_query();

Wordpress Query Random Posts every X amount of hours

I'm fairly new to PHP so excuse me if this seems like a dumb question. I'm building a WP theme for a client, I've gotten the base-functionality down for a "random posts" section, but there's a factor that I'm unable to figure out for myself.
It is a custom post type, that also is utilizing custom fields. The function is, 4 posts from this post type display at random with the required information.
Now: I was able to figure this out on my own, but the random 4 posts is where I'm stumped. The client is requesting that the "Random" aspect only happens every 24 hours instead of every time the page is reloaded.
So basically... how would I alter my existing query so that it only changes the output every 24 hours, instead of every time the page is loaded?
Please see my existing code below:
<ul>
<?php query_posts("post_type=chapter&orderby=rand&posts_per_page=4");?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<li>
<div class="authors">
<a href="<?php the_permalink();?>"><img src="<?php
$post_object = get_field('article_author');
if( $post_object ):
// override $post
$post = $post_object;
setup_postdata( $post );
the_field("profile_image");
$first=get_field("first_name");
$last=get_field("last_name");
endif;
wp_reset_postdata();
?>"></a>
<div class="author-name-home"><?php the_title();?></div>
<div class="author-title-home"><?php echo $first;?> <?php echo $last;?></div>
</div>
</li>
<?php endwhile; endif; wp_reset_query(); ?>
</ul>
There are a few ways you could do this. Here are some options:
Within a nominated post (custom or otherwise), add some additional metadata - you could store the resultant IDs of your 4 random posts (eg: metaname: 'dailyrand' value: '44,55,11,23'). You would have your routine check the time and date of the last time this particular post was updated every time it runs. Once the time and date reaches 24 hours after the last edit, overwrite the metavalue with newly generated random post IDs. If it is not 24 hours yet, pull back the stored post IDs and display. Of course, if the post data changes for some other reason, it could refresh at the wrong interval - maybe it would be better to also set up a time and date metatag to update as well instead of relying on the actual post updated time.
Create a table in your database with a few fields (dailyrand, recordtime, postids, etc) and essentially do the same thing. Check each time for 24 hours since the last update to the table and rinse and repeat.
Get some plugin or widget to do it for you. :) Here's one: http://wordpress.org/plugins/static-random-posts-widget/ - it doesn't look like it has been updated for a while.
Of course, some may think these are terrible ideas - just offering some quick suggestions as no one has commented as yet.

Wordpress: Can't see custom field after the Loop

I have created a loop to show some products on my wordpress site and they seem to be working fine they reel out the products however if I place one of custom fields after the loop it doesn't show. I know its not an issue with the custom field itself as it works fine if I put it above the loop. Does anyone know where I could be going wrong?
Here is my code:
http://pastebin.com/SVxYK0XP
Thanks
You are calling setup_postdata() within your loops, therefore overwriting the $post object.
When you are calling the_field('monoblock_valves_text'); after the foreach loop, it's trying to get that custom field out of the last post of the loop, while it clearly needs to get it from the actual post/page showing.
You need to store the old $post object before the loop, and restore it after the loop, as such:
$old_post = $post;
foreach($products_mono_posts as $post):
setup_postdata($post);
// Rest of code
endforeach;
$post = $old_post;
setup_postdata($post);
the_field('blahblahblah');

Resources