Wordpress [Plugin: Event Post Type] How to arrange posts by event date instead of posted? - wordpress

Currently using the Wordpress Plugin [Event Post Type] and the posts are currently ordered by when I post them. I really need them ordered by event date which the plugin adds to the post type for me.
I am currently using this code and am not sure how to get it to order:
<div id="events-teaser"><?php
$args = array( 'post_type' => 'event', 'posts_per_page' => 10, 'orderby' => '_date_start', 'order' => 'DESC' );
$loop = new WP_Query( $args );
if ( have_posts() ) : while ( $loop->have_posts() ) : $loop->the_post();?>
<div class="teaser-event <?php echo do_shortcode('[xydac_field]promo[/xydac_field]'); ?>">
<div class="event-meta gold">
<div class="event-date"><?php echo get_post_meta($post->ID, "_date_start", true); ?></div>
<div class="event-time"><?php echo get_post_meta($post->ID, "_time_start", true); ?></div></div>
<div class="event-title"><?php the_title(); ?></div></div><?php
endwhile; else:
?><p><?php _e('Sorry, no posts matched your criteria.'); ?></p>
<?php endif; ?>
</div>

Place a call to query_posts() in one of your Template files before The Loop begins. The wp_query object will generate a new SQL query using your parameters. When you do this, WordPress ignores the other parameters it receives via the URL (such as page number or category). If you want to preserve that information, you can use the $query_string global variable in the call to query_posts().
For example, to set the display order of the posts without affecting the rest of the query string, you could place the following before The Loop:
global $query_string;
query_posts( $query_string . '&order=ASC' );
change its order from 'ASC' to whatever you want.

Related

Get post publish date inside ACF foreach

In the post loop I have a foreach loop which displays selected team members in the admin(from the "team" custom post type) from an ACF post object.
What I want to achieve is to display the post-publish date inside the foreach.
The problem is that the code echo get_the_date('M d, Y'); shows the date of the "team" custom post type and not the blog post date because is in the foreach.
I tried to pass the post id but it's shows the posts id of the "team" post types and not the actual "post".
How can I show the 'post_type' => 'post' publish post date inside in the foreach?
<?php
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10,
'orderby' => 'date',
'order' => 'DSC'
);
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
$postAuthors = get_field('select_post_author'); // ACF post object - custom post type - team
if( $postAuthors ): ?>
<?php foreach( array_slice($postAuthors, 0, 1) as $post): ?>
<div class="post-date">
<span>
<?php
echo get_the_date('M d, Y'); // here I want to get the post publish date but it show the publish date of the team post type items
?>
</span>
</div><!-- /.post-date -->
<?php endforeach; ?>
<?php endif; ?>
<?php endwhile;
wp_reset_postdata();
?>
Thanks
So the issue is due to $post being a global variable. I assume ACF stores an array of posts for get_field('select_post_author') then you need to change your foreach statement local variable name, e.g:
<?php foreach( array_slice($postAuthors, 0, 1) as $postAuthor): ?>
<div class="post-date">
<span>
<?php echo get_the_date('M d, Y', $postAuthor->ID); ?>
</span>
</div><!-- /.post-date -->
<?php endforeach; ?>
I solved the issue by passing the post id in the date.
<?php
$pid = get_the_ID(); //get the post id
$postAuthors = get_field('select_post_author');
 if( $postAuthors ): ?>
Pass the post id in the get_the_date.
echo get_the_date('M d, Y',$pid);

ACF get_field not returning value

I'm trying to use get_field to return a simple text field and it returns empty for some reason. A field itself is where it should be and there is text in it, so that part is all set. This PHP code is loaded via php snippet, post thumbnail for example, shows up perfectly. So everything works except for ACF field value.
<div class="your-class">
<?php
$args = array(
'post_type' => 'home_test',
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'ASC',
);
$the_query = new WP_Query($args);
$brand = get_posts($args);
foreach ($brand as $post) {
setup_postdata($post);
$thumbnail = get_the_post_thumbnail_url($post->ID, 'full');
$homelinkvalue = get_field("home_brand_link");
if (!$thumbnail)
continue;
?>
<div>
<p><?php echo $homelinkvalue; ?></p><img src="<?php echo $thumbnail; ?>">
</div>
<?php
}
wp_reset_postdata();
?>
</div>
I think the issue is that you are mixing together a custom post loop (your foreach and setup_postdata()) but then are using functions like get_field(), which make use of the global post object. In this case, get_field() tries to lookup the field value by checking against the global $post, but it has not been properly set. See warning here about setup_postdata($post):
You must pass a reference to the global $post variable, otherwise functions like the_title() don't work properly.
You can implement this in your code with a slight modification:
global $post;
foreach ($brand as $currPost) {
$post = $currPost;
setup_postdata($post);
// Rest of code as normal
}
Or, since get_field() can accept a specific post as an argument instead of automatically using the global one, you could change:
$homelinkvalue = get_field("home_brand_link");
to:
$homelinkvalue = get_field("home_brand_link",$post->ID);
Side note: Normally, the recommended way to iterate posts is with the special "WP loop" pattern, something like:
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<!-- Do something -->
<?php endwhile; ?>
Using the above pattern automatically sets the global $post variable as it loops through, which allows devs to use functions like get_field() without having to worry about explicitly passing in a specific post; makes things a bit easier.
Try this one:
<div class="your-class">
<?php
$args = array(
'post_type' => 'home_test',
'posts_per_page' => -1,
'orderby' => 'name',
'order' => 'ASC',
);
$the_query = new WP_Query( $args );
if ($the_query->have_posts) :
while($the_query->have_posts) : $the_query->the_post();
?>
<div>
<p><?php the_field( "home_brand_link" ); ?></p>
<img src="<?php the_post_thumbnail_url(); ?>">
</div>
<?php
endwhile;
wp_reset_postdata();
endif;
?>
</div>

Pagination shows empty pages for date based archive.php loop

I'm using wordpress and have a custom archive page for a custom post type.
The custom loop gets the logged in users registration date and only shows posts that were published on or after they registered. Works great.
However, the pagination is still using the main query so if there are 4 posts in total set to 2 posts per page the pagination always shows there are two pages even if only one post is displayed due to the logged in users registered date.
Can anyone help me modify what I have so the pagination only shows for results in more than 2 posts for that users query? I've been trying for hours now using various changes I've found on the web...
<?php if ( have_posts() ): ?>
<?php
# Get the current user's info
$user_info = get_userdata(get_current_user_id());
# Use date_parse to cast your date to an array
$regdate = date_parse($user_info->user_registered);
# Set your arguments for WP Query
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'inner',
'posts_per_page' => '2',
'posts_per_archive_page' => '2',
'paged' => $paged,
'date_query' => array(
array(
'after' => array(
# Setting date to array above allows to call specific values within that date
'year' => $regdate['year'],
'month' => $regdate['month'],
'day' => $regdate['day'],
),
# Include posts from the day the user registered
'inclusive' => true,
),
),
# Display all posts on a single page.
);
$my_query = new WP_Query( $args );
while ($my_query->have_posts()) : $my_query->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile; ?>
<div class="nav-previous alignleft"><?php next_posts_link( 'Older posts' ); ?></div>
<div class="nav-next alignright"><?php previous_posts_link( 'Newer posts' ); ?></div>
<?php else: ?>
Nada
<?php endif; ?>
Working with Custom Archive and Pagination
#Scott Eldo Your approach with create custom query will not change main query on your custom archive. FYI and you are correct, pagination only work for main query.
In your case, the recommended approach, I will use filter pre_get_posts to work with custom archive and pagination. Please take a look my answer here how to modify main query on post type archive page, you can figure it out with your query parameters.
BUT if you intent to create query direct into your template ( even it is not change main query ), you need to match your custom query with $GLOBALS['wp_query'] that use in pagination and don't forget to use wp_reset_query() ( MUST ). Take a look my approach here related with your code:
<?php if ( have_posts() ): ?>
<?php
# Get the current user's info
$user_info = get_userdata(get_current_user_id());
# Use date_parse to cast your date to an array
$regdate = date_parse($user_info->user_registered);
# Set your arguments for WP Query
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$args = array(
'post_type' => 'inner',
'posts_per_page' => '2',
'posts_per_archive_page' => '2',
'paged' => $paged,
'date_query' => array(
array(
'after' => array(
# Setting date to array above allows to call specific values within that date
'year' => $regdate['year'],
'month' => $regdate['month'],
'day' => $regdate['day'],
),
# Include posts from the day the user registered
'inclusive' => true,
),
),
# Display all posts on a single page.
);
$my_query = new WP_Query( $args );
while ($my_query->have_posts()) : $my_query->the_post();
get_template_part( 'template-parts/content', get_post_format() );
endwhile; ?>
<?php
/**
* Fix Pagination in custom page/archive
* Set global wp_query the same as our custom query
*
* Use function the_posts_pagination( $args ); for pagination will work too
* see https://developer.wordpress.org/reference/functions/get_the_posts_pagination/#source-code
*/
$GLOBALS['wp_query'] = $my_query;
?>
<div class="nav-previous alignleft"><?php next_posts_link( 'Older posts' ); ?></div>
<div class="nav-next alignright"><?php previous_posts_link( 'Newer posts' ); ?></div>
<?php else: ?>
Nada
<?php endif; ?>
<?php wp_reset_query(); ?> // MUST use to reset global query and post data
Another approach and still NOT recommended is use query_post for your custom query. More reading about it you can learn more in here.

Wordpress - Sorting post loop by meta data date

I have two CPTs, one called 'artist' and the other called 'release.' I've created a single-artist.php page that displays an artist and its' custom meta data. On that same page I am displaying all releases by that artist with the following code:
<!-- GET RELEASES -->
<?php
$category = get_the_category();
$artist_name_slug = $category[0]->slug;
$args = array ('post_type' => 'release', 'posts_per_page' => 20, 'category_name' => $artist_name_slug);
query_posts ($args);
?>
<?php if (have_posts()) : ?>
<h3 class="artist-col2-title">Releases</h3>
<?php while (have_posts()) : the_post(); ?>
<div class="artist-release"><?php echo the_post_thumbnail('small'); ?></div>
<?php endwhile; ?>
<?php endif; ?>
<div style="clear:both;"></div>
Within the release CPT I have a release date in the meta data.
I would like to sort the releases based on that date but I cannot figure out how to add that to my arguments. Any help would be greatly appreciated!
To sort by meta data you can use
$args = array (
'post_type' => 'release',
'posts_per_page' => 20,
'category_name' => $artist_name_slug,
'meta_key' => 'your_meta_key' // i.e. release_date
'orderby'='meta_value' // for numeric value use 'meta_value_num' instead
);
query_posts ($args);
But notice the meta_key should be present in the query that you want to use for sorting, see for more.

Get random post in Wordpress

How do I get a random post in Wordpress?
I would like to display a button on a page that, when pressed, goes to a random post from the blog. I don't want a random post to be displayed on the page, I just want a link that leads to that post.
I tried searching for a code on Google and here at stackoverflow but no success.
Thanks...
UPDATE:
Here is my template code:
<?php /*Template Name: Random*/ ?>
<?php get_header(); ?>
<nav><?php wp_nav_menu(array('menu' => 'Main Nav Menu')); ?></nav>
<div id="main-content-archive">
<div class="grey-text">Random post</div>
<?php $query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );?>
<?php if (have_posts()) : while ( $the_query->have_posts() ) : $the_query->the_post();
echo '<li>';
the_title();
echo '</li>';
?>
<?php endwhile; ?>
<?php else : ?>
<h2>Not Found</h2>
<?php endif; ?>
</div>
<?php get_sidebar(); ?>
<?php get_footer(); ?>
create a page template, and use the following code to get a random post:
//Create WordPress Query with 'orderby' set to 'rand' (Random)
$the_query = new WP_Query( array ( 'orderby' => 'rand', 'posts_per_page' => '1' ) );
// output the random post
while ( $the_query->have_posts() ) : $the_query->the_post();
echo '<li>';
the_title();
echo '</li>';
endwhile;
// Reset Post Data
wp_reset_postdata();
then in a page, just use:
see a random post
I found this post which gave me desired results...
Here's a solution copy/pasted from the wpbeginner blog post. No copyright infringement intended.
Just add the following code to the functions.php file:
add_action('init','random_add_rewrite');
function random_add_rewrite() {
global $wp;
$wp->add_query_var('random');
add_rewrite_rule('random/?$', 'index.php?random=1', 'top');
}
add_action('template_redirect','random_template');
function random_template() {
if (get_query_var('random') == 1) {
$posts = get_posts('post_type=post&orderby=rand&numberposts=1');
foreach($posts as $post) {
$link = get_permalink($post);
}
wp_redirect($link,307);
exit;
}
}
Use mydomain.com/random/ as your href for your button that leads to the random post.
Thanks everyone who contributed for your help...
Cheers!
I find it is more useful to have a URL that will redirect to a random post that you can use as link in sidebar or in menus. If it is a single WP site and even on wp.com it's really easy, for a blog at
http://mygroovywpsite.me/
All you need to do is append it with ?random
http://mygroovywpsite.me/?random
I found this did not work (nor the wp_beginner code above) on subsites in my multisite installation, either approach just loaded the home page. Maybe I had some funky cache issues. The way I do this on many sites is a few more steps w/o plugins.
First make a Page in your site called "Random" / with the slug "random" -- it does not need any content in it
Then create a page-random.php template
<?php
/*
Random Post Picker
Use on page to send viewer to random post optionally mod query
*/
// set arguments for WP_Query on published posts to get 1 at random
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 1,
'orderby' => 'rand'
);
// It's time! Go someplace random
$my_random_post = new WP_Query ( $args );
while ( $my_random_post->have_posts () ) {
$my_random_post->the_post ();
// redirect to the random post
wp_redirect ( get_permalink () );
exit;
}
?>
Then you get the re-direct for any link on your blog ...../random w/o any wrestling with .htaccess
I've done it this way because I've had to modify the query, sometimes for custom post type, sometimes to restrict to category, etc.
I only had one site that was a problem because the hosting suppressed the use of mySQL queries with ORDER BY RAND()
Another Simple solution to display Random Post
1.First a create a custom page template. Name it as random post or a name of your choice!
2.Open the page and remove the default wp loop and Paste the code below
3.To change the no of post change the number ‘1’ to your choice!
<?php
query_posts(array('orderby' => 'rand', 'showposts' => 1));
if (have_posts()) :
while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile;
endif; ?>
source: http://www.yengkokpam.com/displays-random-posts-in-a-page/
Check This
<ul>
<?php
$args = array( 'numberposts' => 5, 'orderby' => 'rand' );
$rand_posts = get_posts( $args );
foreach( $rand_posts as $post ) : ?>
<li><?php the_title(); ?></li>
<?php endforeach; ?>
</ul>

Resources