WP_Query ordering by "rand" and "name"? - wordpress

I am using Wordpress and for the posts on my homepage, I want them to get ordered both randomly and by name. What I mean is, I want to show different posts on my home page each time, yet ordered by their names. I changed the WP_Query args from my theme files as below, but it didn't work. I'm getting unrelated results for a reason I can't understand.
#setup wp_query
$args = array(
'posts_per_page' => $postsperpage,
'orderby' => array( 'rand', 'title' ),
'order' => 'DESC',
);
Is there any way to make that possible?
p.s. I am honestly sick of those who downvote the questions irrelevantly. I wouldn't have asked the question should i had found a solution on the internet. If you have a logical reason please either warn me or edit my post instead of blindly downvoting it.

As documented:
orderby (string | array) - Sort retrieved posts by parameter. Defaults to 'date (post_date)'. One or more options can be passed.
So:
$args = array(
'orderby' => array( 'rand', 'name' ),
'order' => 'DESC',
);
But I don't think this will get you the result you desire. You will most probably have to only use rand with posts_per_page setting to get your desired number of posts. Fetch all posts and sort these by name afterwards.
Example:
$args = array(
'orderby' => 'rand',
);
// get X random posts (10 by default)
$result = new WP_query( $args );
// sort these posts by post_title
usort( $result->posts, function($a, $b) {
if ( $a->post_title == $b->post_title )
return 0;
return ($a->post_title < $b->post_title) ? -1 : 1;
} );
// Start the loop with posts from the result.
while ( $result->have_posts() ) : $result->the_post();
// do your stuff in the loop
}

Related

Display list of woo commerce categories by user defined order

I want to display all woo commerce categories by user defined order. As an example . I tried the following code:
$args = array(
'number' => $product_number,
'order' => 'asc',
);
$product_categories = get_terms('product_cat', $args);
This code works fine and returns an array or all category name in ascending order. What I want now is allow users to pass an array of category ids and display category list by the supplied id order. Is that possible ? Did some research but can not find any close solution.
$product_number = 10; // Any number you have defined
$catsArray = array(1,2,3,4,5,8,10,20); // User provided array of terms ids
$product_categories= get_terms( array(
'number' => $product_number,
'taxonomy' => 'product_cat',
'include' => $catsArray,
'hide_empty' => false,
'orderby' => 'include',
'order' =>'ASC'
) );
Now you can get the categories in
You can do it with php loop. Which takes default ordered term array and build new, custom ordered array on it.
$user_arg = array(1,2,4,5);
$product_categories = get_terms('product_cat', $args);
$temporary_array=array();
foreach ($product_categorie as $pcat) {
$temporary_array[$pcat->term_id]=$pcat;
}
$final_array=array();
foreach($user_arg as $ua){
$final_array[$ua]=$temporary_array[$ua];
}
Now $final_array contains same data with $product_categories, but in custom order based on $user_arg.

Counting post meta based on key and value and get meta count, not post count

I'm using WordPress meta data to register clicks on images, to know which images each user has clicked - and also the total number of clicked images per user. The first part is fine, but I'm struggling to get the counter going, as it's returning a lower amount of meta data than what is actually there.
I have a custom post type gallerier and each gallery has a number of images. I'm using the meta key nedlasting, and I'm identifying each image individually by fetching the url.
Here is how I register clicks, after checking it isn't already:
// Add meta query if it doesnt already exist
function sjekk_nedlasting( $postid, $url, $dato) {
$brukerid = (string)get_current_user_id();
// Check if the image is downloaded previously
$args = array(
'post_type' => 'gallerier',
'meta_query' => array(
array(
'key' => 'nedlasting',
'value' => sprintf(':"%s";', $url),
'compare' => 'LIKE'
),
array(
'key' => 'nedlasting',
'value' => sprintf(':"%s";', $brukerid),
'compare' => 'LIKE'
)
),
'fields' => 'ids'
);
// Perform the query
$nedl_query = new WP_Query( $args );
$nedl_ids = $nedl_query->posts;
// If not already downloaded, register it
if ( empty( $nedl_ids ) ) {
$metaarray = Array(
'user_id' => $brukerid,
'url' => $url,
'date' => $dato
);
add_post_meta( $postid, 'nedlasting', $metaarray );
}
}
Then I'm trying to count those registered clicks using the following function:
// Count number of downloads for a single user
function tell_nedlastinger() {
$brukerid = (string)get_current_user_id();
$args = array(
'post_type' => 'gallerier',
'meta_query' => array(
array(
'key' => 'nedlasting',
'value' => sprintf(':"%s";', $brukerid),
'compare' => 'LIKE'
)
),
'fields' => 'ids'
);
// perform the query
$nedl_query = new WP_Query( $args );
$nedl_ids = $nedl_query->posts;
return count($nedl_ids);
}
The function returns a number, but always much lower than the actual amount of registered meta data/clicks. Anyone seeing a problem?
Edit: I'm pretty sure the problem is that I'm getting the total number of posts, not the total number of meta data entries/clicks - which more often that not is several per post. Any way around that?
I never found a solution to query meta data and get x results per post, so instead of using an array in a single key I split the post meta data into three keys. Then I used $wpdb for a custom query. The final code for the tell_nedlastinger() function:
$brukerid = (string)get_current_user_id();
global $wpdb;
$query = $wpdb->get_results("SELECT * FROM wp_postmeta WHERE (meta_key = 'nedlasting_brukerid' AND meta_value = '$brukerid')");
return count($query);
You can improve the speed of this by using:
$brukerid = (string)get_current_user_id();
global $wpdb;
$count = $wpdb->get_row("SELECT COUNT(*) AS THE_COUNT FROM $wpdb->postmeta WHERE (meta_key = 'nedlasting_brukerid' AND meta_value = '$brukerid')");
return $count->THE_COUNT;
The speed is improved by only having to fetch one row from the database. Also note the use of:
FROM $wpdb->postmeta
This allows for a variable table prefix instead of assuming a table wp_ prefix.
$metaCount = count( get_comment_meta($postId,'key','value') );

Get last post date for custom post type - Wordpress

This is probably a simple one but I can't seem to find an answer anywhere.
I have 2 custom post types. I display them in sections on my home page.
In each section I'd like to have "Last Updated [DATE]" text near the title for each section.
I've found <?php get_lastpostdate( $timezone ) ?> but is there a way of specifying which post type you'd like to query?
[UPDATE]
Here's the final code I used based on Howdy_McGee's answer below. I wanted the date to read as "16th May" for example.
`Thanks, that's the route I started to go down as well. I guess I was hoping to not do another WP_Query, but it works. This is the final code I used:
<p class="right last-update"><?php
$latest = new WP_Query(array('post_type' => 'car', 'post_status' => 'publish', 'posts_per_page' => 1, 'orderby' => 'modified', 'order' => 'ASC'));
if($latest->have_posts()){
$modified_date = $latest->posts[0]->post_modified;
}
//Get the last post update and display the date as "10th March"
$lastpost = strtotime($modified_date);
$lastmonth = date('F', $lastpost);
$lastday = date('jS', $lastpost);
echo 'Last Updated '.$lastday.' '.$lastmonth;
?>
</p>
You can use the_post_modified() function if you're in The Loop. The modified date will change any time the post is changed in any way / updated in any way.
Update
Ok, lets run a small query, what this does is pulls the latest post, modified or new. Since it's just 1 post we can just check if it has posts, and get the first posts modified date.
<?php
$latest = new WP_Query(
array(
'post_type' => 'car',
'post_status' => 'publish',
'posts_per_page' => 1,
'orderby' => 'modified',
'order' => 'DESC'
)
);
if($latest->have_posts()){
$modified_date = $latest->posts[0]->post_modified;
}
?>
For a full list of Date Format Options, View Codex. If you're using it outside The Loop, you can use get_the_modified_date() function. Hope it helps!
I needed something similar for a site I was working on and adapted your code slightly if this helps anyone else
<?php
$taxonomy = 'book'; // or post
$latest = new WP_Query(
array(
'post_type' => $taxonomy,
'post_status' => 'publish',
'posts_per_page' => 1,
'orderby' => 'modified',
'order' => 'DESC'));
if($latest->have_posts()){
echo 'Last Updated ' . mysql2date('jS F Y', $latest->posts[0]->post_modified);
}
?>
This shows the last modified date of the post_type selected
Update: just realised that someone else posted this answer, I only looked at the 1st post "update", but, meh

How to create/modfiy WP_Query to search in post title OR custom field?

I need to modify or create a WP_Query that will search for a search term in both the post title OR a custom field (called 'my_field').
I have been reading and trying for hours, but I am right back to this code (below) which, alas, only searches in 'my_field' and does not take the post_title into account.
function my_pre_get_posts_2( $query ) {
if ( is_admin() && $query->is_main_query() && $query->query['post_type'] === 'post' && isset($query->query['s']) ) {
$search_word = $query->query['s'];
$args = array(
//'s' => $search_word, //If I include this line, the WP query seems to AND post_title and my_field. If I comment out this line, the WP query only searches in my_field. (I need WP to OR post_title and my_field.)
'post_type' => 'post',
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'my_field',
'value' => $search_word,
'compare' => 'IN'
),
array(
'key' => 'post_title',
'value' => $search_word,
'compare' => 'IN',
)
)
);
//$query = new WP_Query( $args ); //Need to modify the existing WP_Query
$query->init();
$query->parse_query($args);
}
}
add_action( 'pre_get_posts', 'my_pre_get_posts_2' );
The reason I need to do this is because I need to modify the behaviour of the the 'Search Posts' button in the 'All Posts' (admin) page so that whatever the admin user searches for, it will return the posts that have a matching post title OR my_field value.
To do an OR search, I tried merging two separate WP_Query results as shown here - https://wordpress.stackexchange.com/questions/55519/can-i-merge-2-new-wp-queryvariable-s - in guidod's answer. That wasn't a great solution though, and resulted in erratic behaviour.
The correct solution I found was to modify the query using the WP Custom Query as shown in the code (which requires some modifications) here - http://codex.wordpress.org/Custom_Queries .

Wordpress - Retrieve blogroll links in PHP Array

Wordpress Experts,
I am trying to retrieve all blogroll links in PHP array but not having any luck. I found function for retrieving in HTML code. Is there any way to retrieve list in array?
Thanks,
Mihir
But of course. The get_bookmarks function will retrieve links from the dashboard's Links section.
Default arguments and use are as follows (taken from the above link):
$args = array(
'orderby' => 'name',
'order' => 'ASC',
'limit' => -1,
'hide_invisible' => 1,
'show_updated' => 0);
$bookmarks = get_bookmarks( $args );
foreach ( $bookmarks as $bm ) {
// Do something exceedingly clever
}

Resources