how to retrieve WP_Query without ordering by date - wordpress

I want to use
$ps = "9126,8955,8554,8620,8825,8912,8937,8813,9054,9022";
$recent = new WP_Query( array('post__in' => explode(',', $ps)) );
to retrieve posts by ID, I do and the result ordered by publish date but I want to retrieve in same of IDs in this example in this order:
9126,8955,8554,8620,8825,8912,8937,8813,9054,9022

Personally, if the order of posts as well as your ID numbers are going to be that strict, I would probably avoid using WP_Query:
<?php
$ids = array(9126,8955,8554,8620,8825,8912,8937,8813,9054,9022);
foreach($ids as $id)
{
$post = get_post($id);
setup_postdata($post);
?>
<!-- YOUR HTML HERE -->
<?php
}
?>
Otherwise, since Posts do not have any kind of Menu Order option like Pages do, you will probably have to set a Custom Field and give it a value (with lower numbers taking priority over higher numbers). Then you can do something like this:
<?php
$ids = array(9126,8955,8554,8620,8825,8912,8937,8813,9054,9022);
$recent = new WP_Query(array('post__in' => $ids, 'orderby' => 'meta_value_num', 'meta_key' => 'postOrder', 'order' => 'ASC'));
?>
This second option is untested and I can't guarantee it will work right off the bat, but it should get you started. Good luck.

in the future in wordpress 3.5 you can use: 'orderby'=>'post__in'

Related

Wordpress query_posts with ID and slug combination

is it possible to use query_posts with a combination of id's and slugs?
I have an array of id's and slugs from user input and want to know if I can use the two in the same post query, or do I have to convert the slugs into their respective post ID's before and then use posts__in?
I have the following mixture of slugs and ID's in an array…
$values = array('this-is-a-test-slug', '2345', '4510', 'another-slug-here', '8934');
How can I use this in query_posts? Can I at all?
query_posts(array('post_type' => 'post', 'post__in' => $values, 'orderby' => 'rand'));
I know that post__in works ok with numeric ID's but I don't think slugs work here as it expects a numerical array.
Thanks
If you're doing something like this, i don't see why it wouldn't be a problem to just convert them all over to ID? There's a thread that sort of helps, and I've written some code (with help from that link) that might help you get started
function allToID($array){
$id = array();
foreach($array as $convert):
if(is_numeric($convert)):
continue; // skip if it's already an ID
else:
$the_slug = $convert;
$args=array(
'name' => $the_slug,
'numberposts' => 1
);
// Ask wordpress to get this post
$my_posts = get_posts($args);
if( $my_posts ) :
// push onto our new array of only IDs
array_push($id, $my_posts[0]->ID);
else continue;
endif;
endif;
endforeach;
}
Ideally you'll be able to run post__in => alltoID($values)
Hope this helps!

how to fire wp_query for tag for custom post type?

I want to fetch all article_type post that have tag "hot".
I am using bellow query but it return all post
query_posts(array( 'posts_per_page' => -1,'post_type'=>'article_type','order' => 'ASC','tags'=>array('hot')));
help me , thanks in advance
Do not use query_posts
Use WP_Query instead.
As for your code, there is no tag parameter called "tags". If you want to query multiple tags, use 'tag__in'. If not, use 'tag'. This example uses 'tag__in':
<?php
$q = new WP_Query(array(
'posts_per_page' => -1,
'post_type'=>'article_type',
'order' => 'ASC',
'tag__in'=>array('hot')
));
if($q->have_posts()) : while($q->have_posts()) : $q->the_post();
//Post stuff.....
endwhile;endif;
?>
Instead of using tag= in your wp_query use post_tag= this will surely solve your problem.
Don't use Query period. Both query_posts and wp_query effect global variables. Use get_posts instead, then you don't have to worry about your queries impacting other parts of the application/theme.
<?php
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type'=>'article_type',
'order' => 'ASC',
'tag__in'=>array('hot')
));
foreach ($posts as $post) {
setup_postdata($post);
// post stuff
}
?>
Alternatively, if you don't want to disturb the $post global you can rename your value. The caveat here is you cannot use setup_postdata() and therefore will have to GET values using the id. For instance:
<?php
$posts = get_posts(array(
'posts_per_page' => -1,
'post_type'=>'article_type',
'order' => 'ASC',
'tag__in'=>array('hot')
));
foreach ($posts as $pst) {
echo get_the_title($pst->ID);
}
?>
In Example 2 you needn't reset the query either.

Let users sort posts in Wordpress

I’d like to create a page for filtering posts based on a number of criteria.
I can work with wp_query and deliver posts quite easily, my problem is that I can’t figure out (nor can I find any answers online about this, believe me I looked) how to let users do this.
Take this for example, returns the posts in order of price (custom field meta value) from highest to lowest with 33 posts.
<?php
$featuredPosts = new WP_Query( array(
'posts_per_page' => 33,
'meta_key'=>'Price',
'orderby' => 'meta_value_num',
'order' => DESC
) );
?>
<?php if ( $featuredPosts->have_posts() ) : ?>
<?php while ( $featuredPosts->have_posts() ) : $featuredPosts->the_post(); ?>
<article <?php post_class('item-post block'); ?> id="post-<?php the_ID(); ?>">
<h2 class="price-title"><?php the_title(); ?> </h2>
</article> <!-- end div post -->
<?php endwhile; wp_reset_query(); ?>
<?php endif; ?>
Now, even after reading and googling, I’ll be damned if I can figure out how I’d implement this on the front end for users to filter posts.
I mean, I know you can append to the URLs in Wordpress to alter the order of posts, but in this context I’m totally lost.
I tried this, but it doesn't work.
<?php
$by_price = esc_url(add_query_arg(array(
'meta_key' => 'price',
'orderby' => 'meta_value_num',
'order' => ASC
)));
$by_date = esc_url(add_query_arg(array(
'orderby' => 'date',
'order' => DESC
)));
?>
<ul>
<li>Order by price</li>
<li>Order by date</li>
</ul>
What I’m trying to achieve is actually quite simple as well, let the user choose the category, choose the price range (guessing I’d write something in JQuery to deliver a value into an field), set the number of results they’d like to be returned.
I’ve tried googling everything under the sun I can think of for this, no dice.
Try Simple Custom Post Order plugin.
It is using AJAX and JavaScript, you don’t have to load anything else. You have to just drag and drop the posts.
OK, I update the code to make it clear:
---I do not think meta_key would be auto-pickup---
functions.php
...
$whitList = array(
'price' => array(
'posts_per_page' => 33,
'meta_key'=>'price',
'orderby'=>'meta_value_num',
'order' => ASC
),
'date' => array(
'posts_per_page' => 33,
'orderby'=>'date',
'order' => DESC
)
);
...
Your first loop php:
<?php
gloabl $whitList; //to use the $whitList in your functions.php.
$aryQuery = $whitList[$_REQUEST['orderby']] ? $whitList[$_REQUEST['orderby']] : $whitList['price'];
$featuredPosts = new WP_Query( $aryQuery );
....
....
?>
For your list page:
<ul>
<?php
gloabl $whitList; //to use the $whitList in your functions.php.
foreach( $whitList as $orderby => $aryOrderBySettings){
?>
<li> Order by <?php echo $orderby;?></li>
<?php
}
?>
</ul>
Using $_GET parameters is the way to go here. First of all you'll want to allow your visitors access to these add these variables. The link approach is fine, overall, so we can generate augmented links by using the add_query_arg to tack on extra parameters to the current URL.
<?php
$urla = add_query_arg( 'sort' => 'price', 'asc' => '1' );
$urld = add_query_arg( 'sort' => 'price', 'asc' => '0' );
?>
Sort by price (asc)
Sort by price (desc)
When clicked, the tacked on variables can thus be detected:
<?php
// Get an allowed sort variable and the order
$sort = isset( $_GET['sort'] ) && in_array( $_GET['sort'], array( 'price' ) ) )
? $_GET['sort'] : null;
$order = isset( $_GET['asc'] ) && $_GET['asc'] == '0' ? 'DESC' : 'ASC';
?>
Now you would augment your main query with the data you just retrieved. If you're using the default way of querying posts on a page you should be able to get away with query_posts, although it is not recomended. And, if you're using a custom loop, simply inject the new arguments into it:
<?php
$args = array();
switch ( $sort ):
case 'price':
$args['order'] = $order;
$args['orderby'] = 'meta_value_num';
$args['meta_key'] = 'price';
break;
default:
break;
endswitch;
$defaults = array( 'posts_per_page' => 33 );
$query = new WP_Query( wp_parse_args( $args, $defaults ) );
?>
You can add more variables, by creating more URLs and buttons to press, and more cases in the switch statement to extend the basic example above.
The first piece of code would go wherever you want your buttons to appear. The second piece of code goes before the third one, which goes before outputting the results.

Order WP_Query by meta and post date

I'm currently working on a small blog which has a sidebar that displays all "special projects".
"Special projects" is just a category, the sidebar will only display 4 posts at a time which are filtered by post date, but I also have a custom meta box to allow the user to feature posts.
These featured post should show up on the top of the special projects.
Right now my query is like this:
new WP_Query("showposts=" . $instance['num'] . "&cat=" . $instance["cat"] . "&order=ASC&order_by=date")
And I can get the featured meta data like this:
$featured = get_post_meta($single_cat_post->ID, 'soy_featured_post', true);
But how could I integrate this inside the WP_Query?
First of all, 'showposts' has been replaced by 'posts_per_page' when using WP_Query. I've corrected that in your code. Also, within a loop you should just be able to use $post->ID instead of $single_cat_post->ID.
I would use two loops. Set your paramaters, then in the first loop include a condition to check for the meta value, reset the query, then do another loop and include a condition that checks for the meta value and outputs nothing if it exists.
In the first query, I added a check to see how many posts are returned by the first loop. Then using that value (subtracted by 4) I calculated a variable to use for posts_per_page in the second loop. Then I added a conditional to only run the loop if the result is greater then 0.
This is untested, but it should work or at least put you on the right path!
<?php
$args = array(
'posts_per_page' => 4,
'meta_key' => 'soy_featured_post',
'cat' => $instance["cat"],
'orderby' => 'date',
'order' => 'ASC'
);
$special_post_query = new WP_Query( $args );
$special_posts_found = $special_post_query->found_posts;
if ($special_post_query->have_posts()) :
while( $special_post_query->have_posts() ) : $special_post_query->the_post();
// POST WITH META VALUE OUTPUT
the_title();
endwhile;
endif;
wp_reset_query();
$second_loop_posts_per_page = 4 - $special_posts_found;
if ($second_loop_posts_per_page > 0) {
$args = array(
'posts_per_page' => $second_loop_posts_per_page,
'cat' => $instance["cat"],
'orderby' => 'date',
'order' => 'ASC'
);
if ($special_post_query->have_posts() ) :
while( $special_post_query->have_posts() ) : $special_post_query->the_post();
// Condition to test for NO meta value
if (get_post_meta($post->ID, 'soy_featured_post', true) == null) {
// CODE
the_title();
} else {
// Don't print anything because the meta value exists
}
endwhile;
endif;
wp_reset_query();
} ?>

Wordpress theme options page query_posts

I am busy building a small theme options page for one of clients and need some help with an issue.
currently i have the option to manually put in IDS of wordpress pages to extract the data with query_posts
based on the theme options is creates a variable called $euro_box_1_vehicles;
my options are filled in as 32,39,43,54 in the input, and when I print this statement with echo, I get the same result.
When I just replace array(32,39,43,45) with array($euro_box_1_vehicles) it only returns one result.
<?php
$vehicle1 = array(
'post__in' => array(32,39,43,45),
'post_type' => 'page',
);
query_posts( $vehicle1 );
while (have_posts()) : the_post();
?>
When I echo var_dump = string(11) "32,39,43,45"
In which case, you need to explode $vehicle1, since post__in expects an array;
query_posts(array(
'post_type' => 'page',
'post__in' => #explode(',', $vehicle1)
));
Update
When I just replace array(32,39,43,45) with array($euro_box_1_vehicles) it only returns one result.
Shouldn't you replace array(32,39,43,45) with $euro_box_1_vehicles not array($euro_box_1_vehicles)? The latter seems it would make a nested array with one argument, i.e. array(array(32,39,43,45)). Which is not what you want.
Old Answer....
If I read you right then query_posts() expects a list of IDs? (32,39,43,45)
But when you pass it $vehicle1 you are not giving it a list of IDs, but a 2-dimensional array.
<?php
$vehicle1 = array(
'post__in' => array(32,39,43,45),
'post_type' => 'page',
);
query_posts( $vehicle1['post_in'] ); //use sub-array that contains list
while (have_posts()) : the_post();
?>

Resources