I am trying to order some data by 'rand' on a foreach loop I have created which is outputting some users which I have created a custom role for. all the other bits are great apart from this.
This is the current state of the loop:
<?php
// Featured Consultants
$consultants = get_users( 'role=consultant&number=2' );
// Array of WP_User objects.
foreach ( $consultants as $consultant ) {
// Check for 'featured' Consultants
if($consultant->featured == 'Yes'){
echo '<div class="columns six consultantCard">';
echo '<div class="columns four">';
echo get_avatar( $consultant->id, 150 );
echo '</div>';
echo '<div class="columns eight">';
// Get users details
echo '<span class="name">' . esc_html( $consultant->first_name ) . ' ' . esc_html( $consultant->last_name ) . '</span>';
echo '<span class="jobTitle">' . esc_html( $consultant->job_title ) . '</span>';
echo '<span class="location">Currently based in ' . esc_html( $consultant->current_location ) . '</span>';
// Check if user is less than 30 days old
if( strtotime($consultant->user_registered) < strtotime('30 days') ){
echo '<span class="newTag">New</span>';
}
// Check if user is featured
if($consultant->featured == 'Yes'){
echo '<span class="featuredTag">Featured Candiate</span>';
}
// Check if user is accredited
if($consultant->accredited == 'Yes'){ ?>
<span class="icon"><img src="<?php bloginfo('template_url');?>/assets/img/icons/accreditedIcon.png" /></span>
<?php echo '<span class="accreditedTag">Bench Accredited</span>';
}
echo '</div>';
echo '</div>';
} else{
echo 'No Featured Consultants';
}
}
?>
It just appears to be showing the latest entries and nothing more. I tried to also create an array but still the same result like so:
$consultant = array(
'role' => 'consultant',
'order' => 'rand'
);
We can use the get_users() to get a list of authors, users with a specific role, a user with specific meta, etc. The function returns users which can be ordered by ID, login, nickname, 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 the 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 in users randomly. In this example below, we I ‘rand’ and you can use your own order by name.
// Add this code in your function.php
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 );
Related
In a WP site I'm trying to set up an events page. I've set up a custom post type and defined a metabox using the metabox.io plugin. The metabox contains a date-picker with the id of 'date_1'. I am now attempting to find a way to display a list of posts with the date and title of the event. Title works just fine but I'm having trouble getting the date to display.
The line
$events .= '' . get_post_meta(get_the_ID(), 'date_1', true) . " - " . get_the_title() .'';
returns title, but not the date. If I wrap the get_post_meta line in a print_r it returns a 1.
I've also experimented with:
$events .= '' . get_post_meta($post->ID, $field['date_1'], TRUE ). " - " . get_the_title() .'';
but this returns "array" instead of one.
Full code
if ( ! function_exists('events_shortcode') ) {
function events_shortcode() {
$args = array(
'post_type' => 'kalender',
'post_status' => 'publish',
'order' => 'ASC',
'posts_per_page' => 10,
);
$postslist = new WP_Query( $args );
global $post;
if ( $postslist->have_posts() ) :
$events .= '<div class="events-lists">';
while ( $postslist->have_posts() ) : $postslist->the_post();
$events .= '<div class="items">';
$events .= '' . get_post_meta(get_the_ID(), 'date_1', true) . " - " . get_the_title() .'';
$events .= '</div>';
endwhile;
wp_reset_postdata();
$events .= '</div>';
endif;
return $events;
}
add_shortcode( 'events', 'events_shortcode' );
}
Please read metabox.io plugin date field documentation.
I hope you can fix your problem
I'm working in Wordpress and implemented some PHP to display all categories on a page (by a shortcode). By clicking on a category it links to a new page displaying all posts of that very category.
How do I display only certain categories, for instance by id and/or name of the cateogry?
One post has two categories (a : A & B or A & C). So one post a always has one category A, and one category B or C.
Here's my code:
function swerft_categories( ){
ob_start();
$categories = get_categories();
echo '<div class="swerft_cat">';
foreach($categories as $category) {
echo '<div class="swerft_cat_single col-lg-3 col-md-3 col-sm-6 col-xs-12">';
echo '<div class="swerft_cat_single_inner">';
$thim_group_custom_title_bg_img = get_term_meta( $category->term_id, 'thim_group_custom_title_bg_img', true );
if ($thim_group_custom_title_bg_img) {
$image_id = $thim_group_custom_title_bg_img['id'];
if ($image_id) {
$post_thumbnail_img = wp_get_attachment_image_src( $image_id, 'full' );
echo '<img src="' . $post_thumbnail_img[0] . '" alt="' . $category->name . '" />';
}
}
echo '<h5>'. $category->name .'</h5>';
echo '<p>'. $category->description . $category->count . '<span> Seminare </span>' . '</p>';
echo '</div>';
echo '</div>';
}
echo '</div>';
return ob_get_clean();
}
add_shortcode( 'swerft_categories', 'swerft_categories' );
I tried this in the first few lines for example with no success:
function swerft_categories($args){
ob_start();
$args = array('hide_empty'=> 1,
'name' => 'B');
$categories = get_categories($args);
1) I want only one certain relation to be displayed. Let's say: only the relation of a : A & B
2) I want the count to only show the amount of posts based on the relation above.
3) By clicking on a category based on this relation, I want only those posts to be displayed of course.
I was able to find a solution for the above mentioned problem together with a colleague. See the code below, I hope it may help someone maybe; and thanks for anyone considering this task though ;)
// Function to only show individual seminars after click on category on category-page
function swerft_filter_posts_open_individual_seminare( $query ) {
$offene_seminare = isset($_GET['offene_seminare']) ? boolval($_GET['offene_seminare']) : false;
$individual_seminars_category_id = 91;
if($query->is_category() && $query->is_main_query()) {
if ($offene_seminare) {
$query->set( 'category__not_in', $individual_seminars_category_id );
} else {
$query->set( 'category__in', $individual_seminars_category_id );
}
}
}
add_action( 'pre_get_posts', 'swerft_filter_posts_open_individual_seminare' );
// Function to only count individual seminars in overview
function swerft_count_individual_seminars_in_category($category_id) {
$individual_seminars_category_id = 91;
$query_args = array(
'post_type' => 'post',
'category__and' => array($individual_seminars_category_id, $category_id)
);
$query = new WP_Query( $query_args );
$count = $query->found_posts;
return $count;
}
I need to create a recent posts section outside a WordPress website, but the result is incorrect (see image). I used this PHP code:
// elsewhere in code...
require "wp-load.php";
// the code that is generating the recent posts section
$posts = get_posts( array( 'posts_per_page' => 1 ) );
$recent_posts = wp_get_recent_posts(array('numberposts' => 7 ) );
foreach ($posts as $_post) {
foreach($recent_posts as $post) {
if ( has_post_thumbnail( $_post->ID ) ) {
echo '<div class="owl-item">';
echo '<figure class="blog-item-container">';
echo '<span class="blog-item-img">';
echo get_the_post_thumbnail( $_post->ID, array(480, 305) );
echo '</span>';
echo '<figcaption>';
echo '<h3>', $post['post_title'], '</h3>';
echo '</figcaption>';
echo '</figure>';
echo '</div>';
}
}
}
I was expecting to get the image for each specific recent post. This result gives to me the correct recent post, but the image is the same for all the posts. Why is the image the same?
Here's some comments on your code, which will hopefully explain what's going wrong, or help you get to the bottom of it:
// Here you are getting ONE post for some reason, and putting it in the $posts variable
$posts = get_posts( array( 'posts_per_page' => 1 ) );
// Here you are getting 7 posts, and putting in the $recent_posts variable
$recent_posts = wp_get_recent_posts(array('numberposts' => 7 ) );
// Here you are "looping" over the ONE post and putting into $_post variable.
// So here, $_post is made to reference the single most recent post
foreach ($posts as $_post) {
// Here, you are "looping" over the 7 recent posts, putting into $post variable
foreach($recent_posts as $post) {
// Here you ask if the ONE most recent post ($_post) has a featured image.
// I doubt this is what you actually want, as this will
// be run for all 7 recent posts, but is only referencing
// the single ONE post
if ( has_post_thumbnail( $_post->ID ) ) {
echo '<div class="owl-item">';
echo '<figure class="blog-item-container">';
echo '<span class="blog-item-img">';
// here you are displaying the image for the ONE post, not the 7 most recent posts
echo get_the_post_thumbnail( $_post->ID, array(480, 305) );
echo '</span>';
echo '<figcaption>';
// Here you are referencing the title, link, etc.
// for the 7 most recent posts
echo '<h3>', $post['post_title'], '</h3>';
echo '</figcaption>';
echo '</figure>';
echo '</div>';
}
}
}
So, given your question of "recent posts", and your comment that it is incorrect to show the same featured image for all of them, I suspect the code should look like this (NOTE: you can remove all of the commented code, I left it here to explain what the changes are):
// remove this - no need for the single most recent post
// $posts = get_posts( array( 'posts_per_page' => 1 ) );
$recent_posts = wp_get_recent_posts(array('numberposts' => 7 ) );
// remove this - don't loop over the single most recent post
// foreach ($posts as $_post) {
foreach($recent_posts as $post) {
// change this to $post['ID'] (from $_post->ID)
if ( has_post_thumbnail( $post['ID'] ) ) {
echo '<div class="owl-item">';
echo '<figure class="blog-item-container">';
echo '<span class="blog-item-img">';
// change this to $post['ID'] (from $_post->ID)
echo get_the_post_thumbnail( $post['ID'], array(480, 305) );
echo '</span>';
echo '<figcaption>';
echo '<h3>', $post['post_title'], '</h3>';
echo '</figcaption>';
echo '</figure>';
echo '</div>';
}
}
// remove this, since we are removing the loop
// }
I am using advanced custom fields pro to store and display information on estate sale dates. These are held in a repeater field, each row in the field has a start time, end time and a date. I need to display the information ordered by the date in the repeater field row. Currently it is ordered by date modified. I have tried several solutions but none seem to work for what I need to do.
This is what I have currently:
<?php
$latestes = new WP_Query(
array(
'post_type' => 'estate-sales',
'post_status' => 'publish',
'posts_per_page' => 10,
'orderby' => 'modified',
'order' => 'DESC'
)
);
while ( $latestes->have_posts() ) : $latestes->the_post();
echo '<li class="frontpage-esale"><a href="';
the_permalink();
echo '">';
the_title();
echo ' ';
$rowses = get_field('estate_sale_dates');
$first_row = $rowses[0];
$first_row_date = $first_row['es-date'];
$first_row_start = $first_row['es-start-time'];
$first_row_end = $first_row['es-end-time'];
echo ' - ';
if ($first_row_date) {
echo date('F j, Y',strtotime($first_row_date));
}
else {
echo 'Sale Dates TBA';
}
endwhile;
wp_reset_query();
?>
The most common answer when searching for a solution is to do something like this:
$latestes = new WP_Query(
array(
'post_type' => 'estate-sales',
'post_status' => 'publish',
'posts_per_page' => 10,
'orderby' => 'modified',
'order' => 'DESC'
)
);
while ( $latestes->have_posts() ) : $latestes->the_post();
$repeater = get_field('estate_sale_dates');
foreach( $repeater as $key => $row )
{
$column_id[ $key ] = $row['es-date'];
}
array_multisort( $column_id, SORT_ASC, $repeater );
foreach( $repeater as $row ) {
echo '<li class="frontpage-esale"><a href="';
the_permalink();
echo '">';
the_title();
echo ' ';
$rowses = get_field('estate_sale_dates');
$first_row = $rowses[0];
$first_row_date = $first_row['es-date'];
$first_row_start = $first_row['es-start-time'];
$first_row_end = $first_row['es-end-time'];
echo ' - ';
if ($first_row_date) {
echo date('F j, Y',strtotime($first_row_date));
}
else {
echo 'Sale Dates TBA';
}
}
endwhile;
wp_reset_query();
?>
However, when I try that, it lists each sale 3 times, does not order by the date at all, and if no date is entered (which needs to just default to Sale Dates TBA) it throws an error.
Any help greatly appreciated.
Note, that your integration isn't complete, signaled by having two get_field('estate_sale_dates');, and the name $first_row being out of place when iterating all of them. Without the sort, you're basically doing
$repeater = get_field( 'estate_sale_dates' );
...
foreach ( $repeater => $row_that_isnt_used )
{
$rowses = get_field( 'estate_sale_dates' );
$first_row = $rowses[0];
}
I think something like this is what you're after:
<?php
while ( $latestes->have_posts() ) {
$latestes->the_post();
echo '<li class="frontpage-esale"><a href="';
the_permalink();
echo '">';
the_title();
echo '</a> ';
if ( ! count( $sale_dates = get_field('estate_sale_dates') ) )
echo '<span>Sale Dates TBA</span>';
else
{
// $order = array_column( $sale_dates, 'es-date' ): (php 5.5+)
foreach( $sale_dates as $ignore => $row )
$order[] = $row['es-date'];
array_multisort( $order, SORT_ASC, $sale_dates );
echo "<ul>";
foreach( $sale_dates as $row ) {
$date = $row['es-date'];
$start = $row['es-start-time'];
$end = $row['es-end-time'];
echo "<li>" . date('F j, Y',strtotime($row_date)) . " $start-$end</li>";
}
echo "</ul>";
}
echo "</li>";
}
I have the same problem with a calendar. There is no solution to do this in the right way with a repater field. The best way to do this, is to use an custom field in an hidden post type and a relation field.
Because any PHP solution is inperformant.
Make a Custom Post Type "Sales Dates" an in this a custom field "date" and a second "Post Relation".
Then select from Post Type "Sales Dates" all Posts order by meta key "dates" with the relation field you get the data from the not hidden post type.
I use a crowdfunding-plugin for wordpress called personal fundraiser which you can see here. It uses one post-type called cause and another called campaign. The campaign posts uses the cause posts as a template. The reason why i ask here is that the plugin-developer answer questions every second month or so.
There are one shortcode which i want to change the content of. The first thing i want is to get the campaing-image. I probably need a code to get it from the asociated cause (the template). The second thing i want is to echo shortcodes in the $list_content you see below. How do i add shortcodes there? If i use $list_content .= '<?php echo do_shortcode( $content ) ?>' i get php-error. The code i want to change looks like this:
`function pfund_campaign_list() {
global $wp_query;
wp_enqueue_style( 'pfund-user', pfund_determine_file_location('user','css'),
array(), PFUND_VERSION );
$post_query = array(
'post_type' => 'pfund_campaign',
'orderby' => 'title',
'order' => 'ASC',
'posts_per_page' => -1
);
if ( isset( $wp_query->query_vars['pfund_cause_id'] ) ) {
$post_query['meta_query'] = array(
array(
'key' => '_pfund_cause_id',
'value' => $wp_query->query_vars['pfund_cause_id']
)
);
}
$campaigns = get_posts($post_query);
$list_content = '<ul class="pfund-list">';
foreach ($campaigns as $campaign) {
$list_content .= '<li>';
$list_content .= ' <h2>';
$list_content .= ' '.$campaign->post_title.'</h2>';
$list_content .= '</li>';
}
$list_content .= '</ul>';
return $list_content;
}`
In another function to list the causes, this code is used to get the cause-image, but when i use it in the campaign_list nothing happens:
`$cause_img = get_post_meta($cause->ID, '_pfund_cause_image', true);
if ( $cause_img ) {
$list_content .= '<img class="pfund-image" width="100%" src="'.wp_get_attachment_url( $cause_img ).'"/>';
}`
You can see the whole .php-file here
Any help is very much apreciated.
To get a shortcode in your theme do this
$list_content .= do_shortcode($content);
then you can change in your $list_content, you cant echo in a predefined variable.
In-place of
$list_content .= '<?php echo do_shortcode( $content ) ?>'