how to get authors details and author page permalink randomly. I have checked the new get_users() function for wordpress which is returning the author but i can not sorting them randomly.
here is the site i am using the code: http://citystir.com
Any help?
Solution: Thanks to theomega i have solved the isse. Here is the code just for community sharing:
$args = array('role' => 'author');
$authors = get_users($args);
shuffle($authors);
$i = 0;
foreach ($authors as $author):
if($i == 4) break;
//do stuff
$i++;
endforeach;
Did not set the limit on the $args because i need the shuffle in all users. Hope it will help someone out there, in the wild. :D Thanks!
Try
$users = get_users('ciriteria');
shuffle($users)
//users is now shuffled
Using the PHP Shuffle-Function.
We can use the get_users() to get a list of authors, users with a specific role, user with specific meta, etc. The function returns users which can be ordered by ID, login, nicename, email, url, registered, display_name, post_count, or meta_value. But there is no random option such as what get_posts() function provides to shows posts randomly.
Since the get_users() function uses WP_User_Query class, there is an action hook pre_user_query we can use to modify the class variable. The idea is using our own ‘rand’ order by parameter. If we put “rand” to the orderby parameter, “user_login” will be used instead. In this case, we need to replace it with RAND() to result users randomly. In this example below, we I ‘rand’ and you can use your own order by name.
add_action( 'pre_user_query', 'my_random_user_query' );
function my_random_user_query( $class ) {
if( 'rand' == $class->query_vars['orderby'] )
$class->query_orderby = str_replace( 'user_login', 'RAND()', $class->query_orderby );
return $class;
}
The WP_User_Query contains order by query and the our arguments. Now, we have a new order by parameter to WordPress.
$users = get_users( array(
'orderby' => 'rand',
'number' => 5
));
print_r( $users );
Reference: http://www.codecheese.com/2014/05/order-wordpress-users-random/
Related
I am building a custom Wordpress plugin to integrate with Woocommerce Orders. This plugin receives a string as input. Upon receiving this string input, the plugin must search Woocommerce for an order that matches the passed in value. The Woocommerce Orders have a custom field my_number which stores the values I am searching. I read about WP_Query class. I read about get_posts function. Both takes a list of args as a parameter. All these do not answer my problem. The problem is that running queries using all these Wordpress built-in capabilities are not returning a result! What is fun to me is that if I use the same meta_key on a normal Wordpress post, I do get a result back. So, why am I not getting the same result back on a Wocommerce Order. You will see, I have tried even to remove post_type filter and all other fields and only left the meta_key. This is just one example:
$args = array(
'meta_key' => 'my_number',
);
$posts = get_posts( $args );
foreach ( $posts as $post ) {
return ("<pre>".print_r( $post,true)."</pre>");
}
So, my question is how to a search an Order in Woocomerce Wordpress using the existing functionalities.
I can see the record in MySQL when I run
SELECT * FROM `wordpressTable_postmeta` WHERE meta_key = 'my_number'
Attached screenshot shows this order, with the custom field.
Okay, so I came across this article. To query Woocommerce order, you need to use the Woocomerce class WC_Order_Query.
https://pluginrepublic.com/querying-woocommerce-orders/
Now my fixed query looks like this and it is returning something:
$args = array(
'meta_key' => 'my_number',
);
$query = new WC_Order_Query( $args );
$orders = $query->get_orders();
foreach ( $orders as $order ) {
return ("<pre>".print_r( $order,true)."</pre>");
}
I have an app for wordpress blog site. this app getting wordpress articles with php api call.
I am using this code for get article list.
function api_posts()
{
$args = [
'numberposts' => 99999,
'post_type' => 'post',
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach ($posts as $post) {
$data[$i]['id'] = $post->ID;
$data[$i]['title'] = $post->post_title;
$data[$i]['excerpt'] = $post->post_excerpt;
$data[$i]['content'] = $post->post_content;
$data[$i]['slug'] = $post->post_name;
$data[$i]['thumbnailImage'] = get_the_post_thumbnail_url($post->ID, 'thumbnail');
$data[$i]['mediumImage'] = get_the_post_thumbnail_url($post->ID, 'medium');
$data[$i]['largeImage'] = get_the_post_thumbnail_url($post->ID, 'large');
$data[$i]['date'] = $post->post_date;;
$data[$i]['post_url'] = get_permalink($post->ID);
$i++;
}
return $data;
}
I am getting ID, post_excerpt, post_content and others. So I am getting 10 information about one article. But I want to get more than 10 information about one artice. But I don' know the keys to get informations. For example I want to get article category. How can I do this. Where can I learn keys like post_title, post_excerpt. I know developers.wordpress but I don't understand it.
This is my custom wordpress api result
https://meshcurrent.online/wp/wp-json/api/v1/posts/
EDIT
Here's 1 more re-write but with a query as for some strange reason get_post_meta was not giving all the meta data as it used to before:
function api_posts(){
global $wpdb;
$posts_with_meta = $wpdb->get_results(
"SELECT *
FROM $wpdb->posts INNER JOIN $wpdb->postmeta
on $wpdb->posts.`ID` = $wpdb->postmeta.`post_id` where $wpdb->posts.`post_type` = 'post'
"
);
return $posts_with_meta;
}
OLD ANSWER
Here's how you can get all the meta keys and their values of all the posts:
function api_posts()
{
$args = [
'numberposts' => 99999,
'post_type' => 'post',
];
$posts = get_posts($args);
$data = [];
$i = 0;
foreach ($posts as $post) {
$allPostMeta = get_post_meta($post->ID);
foreach($allPostMeta as $key => $value) {
$data[$i][$key] = $value[0];
}
$i++;
}
return $data;
}
I've just done a re-write of your code to get you all the keys with their data. I can't test or replicate it as it's specific to your environment but I'm sure it'll work just fine for you.
Some keys might differ for your blog app and the website WordPress it's called post_title but your app reads it as the title. You'll need to work around that. But this will pretty much give you a list of all meta keys applicable to a post and you can then play around with your code and add only those keys which you need.
Once you know the fields you want in the API, You must also checkout WP_QUERY as that is more powerful and has a fields filter which can give you only those fields that you need for the app and not push all the data. Thus, saving API response time.
I hope this will help you.
I don't think there is any function available to return all data. You'll have to collect all the data manually.
If you're interested in getting categories and tags then you'll have to use wp_get_post_terms function to get the terms objects array and then loop through values and get the names/slugs/term_id etc.
If you're interested in metadata, then you'll have to use get_post_meta function to get meta data using meta keys.
I've got some custom post types set up in Wordpress using Pods and linking them using relationship fields. Now I'd like to display (and link to) the related custom posts 'postB' from a single post 'postA'. I also just want to display those posts which got a date in the future, which is also stored in a custom field in 'postB'.
This is what I've currently got so far, put into a theme template file (single-posta.php):
<?php
$id = get_the_ID();
$params = array(
'where' => 'postB.ID IN ('.$id.')',
'limit' => -1, // Return all
//'oderby' => 'postB.customDate, (order is not working, so I commented it out)
//'order' => 'ASC'
);
$postsB = pods( 'postB', $params );
if ( 0 < $postsB->total() ) {
while ( $postsB->fetch() ) {
?>
<p>
<?php echo $postsB->display( 'title' ); ?><br>
<?php echo $postsB->display( 'customDate' ); ?><br>
</p>
<?php
}
}
?>
So how can I
order the results?
link to these posts?
limit them to dates in the future?
Btw. is this the right way to get those posts anyway?
You could use WP_Query too, but since you're using the Pods find() syntax, I'll give you the correct code for what you're after using that:
$params = array(
'where' => 'postB.ID IN ('.$id.')',
'limit' => -1, // Return all
'orderby' => 'customDate.meta_value ASC'
);
$postsB = pods( 'postB', $params );
Pods doesn't let you create fields with capital letters though, so it's likely you created that one outside of Pods, correct? Just double checking, if it was created with Pods it would be named 'customdate'
UPDATE: I have tried using the following code:
<?php if (is_category(events)) {
$posts = query_posts($query_string . '&orderby=event_date&order=desc');
} else {
$posts = query_posts($query_string . '&orderby=title&order=asc');
}
?>
Is there any reason why that wouldnt work? It seems to work fine organising posts in alphabetical order, but still no luck on the date order within 'events'.
--
After searching through various existing questions I can't quite find a solution to what I am trying to do.
Currently all posts on my site are ordered alphabetically, which is fine except for one new category that I have added. For this category I want to order all posts by a value that I enter into a custom field. The field is called 'event_date' - so I want to order the posts by date essentially, but not the date the post was created, the date the user manually enters into this field.
I managed to get it working by using:
<?php if (is_category($events)) { $posts = query_posts($query_string . '&orderby=$event_date&order=asc'); } ?>
However this overrides the aphabetical order for all other pages.
For alphabetical order I am using:
<?php if (is_category()) { $posts = query_posts( $query_string . '&orderby=title&order=asc' ); } ?>
Essentially I want a statement that tells the page to order all posts in aphabetical order, unless the category is 'events', where I want to order them by the custom event date.
As you can probably tell I'm very much front end, not back end so a lot of this is fairly new to me, so any help or advice is appreciated.
To order posts by a custom field value, you need add the custom meta field to the query itself. orderby=meta_value in addition to meta_key=metafieldid will allow ordering in this fashion.
I would use the pre_get_posts hook and modify the query object if get_query_var( "cat" ) (or a similar query var) returns the desired post category.
add_action( "pre_get_posts", "custom_event_post_order" );
function custom_event_post_order( $query )
{
$queried_category = $query -> get_query_var( "cat" );
/*
* If the query in question is the template's main query and
* the category ID matches. You can remove the "is_main_query()"
* check if you need to have every single query overridden on
* a page (e.g. secondary queries, internal queries, etc.).
*/
if ( $query -> is_main_query() && $queried_category == 123 )
{
$query -> set( "meta_key", "event_date" ); // Your custom field ID.
$query -> set( "orderby", "meta_value" ); // Or "meta_value_num".
$query -> set( "order", "ASC" ); // Or "DESC".
}
}
Remember that this approach overrides all queries that are using the category in question. You can build custom WP_Query objects that use their own parameters for constructing loops.
You also should standardize the way you save the custom field data to the database. For dates I prefer using UNIX-timestamp formatted times that are easy to move around and manipulate. This way no accidents happen when querying and some data is formatted in another way that the rest is.
Disclaimer: I did not have the time to test the above code in action, but the general idea should work properly.
EDIT: of course the above code should be inserted to functions.php or a similar generic functions file.
What about:
<?php $posts = query_posts($query_string . (is_category($events)?'&orderby='.$event_date:'&orderby=title') . '&order=asc'); ?>
<?php
$recent = new WP_Query(“cat=ID&showposts=x”);
while($recent->have_posts()) : $recent->the_post();
?>
Hopefully I understood your question, use the WP_Query and within the orderby add a space between your order by columns:
$args = array(
'posts_per_page' => 100,
'orderby' => 'title',
'order' => 'ASC',
);
if(is_category($events)){
$args['orderby'] .= " meta_value_num";
$args['meta_key'] = 'event_date';
}
$posts = (array) new WP_Query( $args );
I have the following function that I've added to my functions.php file in WordPress. The idea is that it gathers all of the titles of 'fsmodel' posts (a custom post type that I've created). It then returns these as an array, which I then use to populate a select tag in the custom meta fields for a second custom post type.
Basically, 'fsmodel' will have posts with a boat model, and the 'fsboat' post type will have a drop-down with the names of each of the models to select from.
Now, this appears to works fine in the Dashboard - the drop-down is populated as expected. When I save, however, the post doesn't show up in the Edit list. Also on the website, all pages output as the 404 error page when this function is active.
I'm certain that the problem lies within the following code - does anyone have any idea what I might have done wrong?
function fs_model_array() {
$models_array = array();
$loop = new WP_Query(array(
'post_type' => 'fsmodel',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'post_status' => 'publish'
));
while ( $loop->have_posts() ) : $loop->the_post();
$models_array[] = get_the_title();
endwhile;
return $models_array;
};
OK, I've come up with a solution (I hope - it's holding up for now).
Instead of creating a loop, I've just used the $wpdb->get_results to search the database for the column with a WHERE filter for the custom post type.
Then run an array builder:
$models_array = array();
$model_db = $wpdb->get_results("SELECT post_title FROM $wpdb->posts WHERE post_type='fsmodel' AND post_status = 'publish'");
foreach ($model_db as $model_db) {
$models_array[] = $model_db->post_title;
}
Thanks again for your time, hsatterwhite! :-)
I think you might find that adding wp_reset_query() to the end of your function will solve your problems :)
I like your solution, but I'd be inclined to say that you need to call the global variable of $post whenever you use the loop like this in a function, as it assigns it to that variable.
function fs_model_array(){
global $post;
$models_array = array();
$loop = new WP_Query(array(
...