How can i loop WordPress specific post - wordpress

How can i loop WordPress post like-
Last one.
3rd last one from below.
As far as I know I can select last and first one by adding order by asc/desc but i cant figure out 2nd one.

Did you try an offset of recent posts with a limit of 1? Like this:
$args = array(
'numberposts' => 1, // only return 1 post
'offset' => 2, // select the third item found
'orderby' => 'post_date', // field for order by
'order' => 'DESC', //DESC for 3th most recent, ASC for third oldest post
'post_type' => 'post', // could be any post type, remove if you want all post types
'post_status' => 'publish' // only show published posts, remove if you want all even trashed
);
$recent_posts = wp_get_recent_posts( $args );

Related

Wordpess Timber - combine $context to get two post-types?

On my homepage I would like to show the most recent new items (standard Wordpress 'posts') OR events (custom post-type) in date order. I have the following bringing in each content-type, but what I get is all the events in date order; followed by all the news items in date order - what I want is News OR Events in date order, so if the newest item is an Event, then that's what comes first, followed by a News item, followed be an Event if necessary and so on. I assume there's some way to combine the context?
<?php
$context = Timber::context();
$context['home_page_content'] = new Timber\PostQuery('post_type=vopthomepage');
// below are the two I want to combine
$eventArgs = array(
'post_type' => 'mec-events',
'posts_per_page' => -1,
'orderby' => array(
'date' => 'DESC'
));
$context['mec_events'] = new Timber\PostQuery($eventArgs);
$postArgs = array(
'post_type' => 'post',
'posts_per_page'=> -1,
'category_name' => 'featured',
'orderby' => array(
'date' => 'DESC'
));
$context['featured_items'] = new Timber\PostQuery($postArgs);
Timber::render( 'index.twig', $context );
Any help greatly appreciated!
If you wanted to combine the two queries and then sort them, you could first merge the query results into a single array that you then sort with wp_list_sort().
<?php
$context = Timber::context();
$context['home_page_content'] = new Timber\PostQuery('post_type=vopthomepage');
$eventArgs = [
'post_type' => 'mec-events',
'posts_per_page' => 10,
'orderby' => [
'date' => 'DESC',
],
];
$postArgs = [
'post_type' => 'post',
'posts_per_page' => 10,
'category_name' => 'featured',
'orderby' => [
'date' => 'DESC',
],
];
$events = new Timber\PostQuery( $eventArgs );
$featured_items = new Timber\PostQuery( $postArgs );
$posts = array_merge( $events->get_posts(), $featured_items->get_posts() );
$posts = wp_list_sort( $posts, 'post_date', 'DESC' );
// Restrict to certain amount of items.
$posts = array_slice( $posts, 0, 6 );
$context['posts'] = $posts;
Timber::render( 'index.twig', $context );
You can then loop through that custom-built posts array in Twig
{% for post in posts %}
{# Display post teaser #}
{% endfor %}
What I would do is restrict the amount of posts that you fetch for each of the queries.
This works well if the amount of published posts and events are about the same over time. However, you could end with only events or posts showing up, if the newest posts are only from one type.
To work around that, you could e.g. only fetch 3 posts of each post types to make it a total of 6. You could still use wp_list_sort(), but that way you would have at least 3 of each post types displayed.
You could also try to use more than one post type for the post_type argument in WP_Query – it accepts an array of post types, but I guess that wouldn’t work if you only want to include posts from the featured category.

WP_Query arguments setting for ID

I would like to do the WP_Query with the arguments setting as below, plus "WHERE ID > $post_id" (specific post id).
Pls advise how to add this WHERE clause into the $arg setting?
Thanks a lot.
$args = array (
'cat' => $category_id,
'nopaging' => false,
'posts_per_page' => '5',
'order' => 'DESC',
'orderby' => 'ID'
);
$query = new WP_Query( $args );
If you want to query "all post with an ID superior to X", I think you need to do like this :
$post_ids = range(25, 50); //we need an array of post IDs
$args = [
'posts_per_page' => 25, // if you want to limit/paginate the query
'post__in' => $post_ids
];
$posts = get_posts($args);
This will query all post from IDs 25 to 50 included. Pagination may be useful if you have a very large range of IDs to query. source.
Note that this will not generate a WHERE SQL clause, but a WHERE IN. To get a real MySQL WHERE, I think you'll to go with custom SQL query, as WP_Query doesn't provide a lot of operators on the post IDs.
oops, didn't see the > sign
you can use post__in with posts ids as #Mtxz answered above
'post__in' => array( )

wordpress get post where category is not equal to blog

i am trying to get the latest post which is not a blog . I know how to get a post by category name but how to get the post which is not equal to a specific category name . Here is the code i use to get for a category name
$query = array (
'category_name' => 'Blog',
'posts_per_page' => 1,
'post_status' => array('publish')
);
As stated in the Codex (http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters) you can use 'category__not_in' and feed it the id of the category you want to exclude.
$args = array(
'category__not_in' => array($id), // Pass in one or more IDs here.
'posts_per_page' => 1,
'post_status' => 'publish', // no need to pass it in a array
'orderby' => 'date' // Since you wanted the latest post, this is default value so not really needed
);
You can find out the ID of the category by hovering the category-link in the WP-backend and go to the category and then check the adress in your adress-bar, it should look something like this:
/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=2
There's a category_not_in query parameter. To use it you'll need the ID, not the slug, of the category you want to exclude from your result.
http://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters
$BlogObj = get_category_by_slug('Blog');
$query = array (
'category_not_in' => array($BlogObj->term_id),
'posts_per_page' => 1,
'post_status' => array('publish')
);
You may try this:
$query = array (
'category_not_in' => array(get_cat_ID('Blog'),
'posts_per_page' => 1,
'post_status' => 'publish'
);
Think we need to combine answers of #the-alpha and #o-jones here.
$BlogObj = get_category_by_slug('Blog');
$query = array (
'category__not_in' => array($BlogObj->term_id),
'posts_per_page' => 1,
'post_status' => array('publish')
);
Simply you have to change 'category__not_in' instead of 'category_not_in'. Adding this for future users may come around.

wordpress get_posts ordered by custom field which is a custom date

i have a custom post type for members and the birth date is saved like 01.01.2013
$args = array(
'numberposts' => -1,
'post_type' => 'mitglied',
'post_status' => 'publish',
'meta_key' => 'geburtsdatum',
'meta_value' => date("d.m.Y"),
'meta_compare' => '>',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$geburtstage = get_posts ( $args );
i want a list with the birthdays of the members ordered by month and day like this
4th of january, person 10
8th of march, person 2
...
1st of december, person 3
with the code above the list is ordered by day
1st of december, person 3
4th of january, person 10
8th of march, person 2
also important is, that the ordering is not influenced by the year of birth
You have stored the date in the wrong format in your custom field. You should have used a UNIX stamp or else a format like Y-m-d, which allows to sort chronologically.
The only solution you have now is to retrieve your results without sorting them (forget 'order' => 'ASC') but also without limiting them (because your date limit is not working even if it looks like it does), create an array with all that, convert the date time as a UNIX timestamp (using strtotime) and sort by date...
But my real advice would be to refactor your site using timestamps or properly formated dates (Y-m-d). You could create a loop that goes through every post and replaces the value of your custom field with the equivalent value in UNIX, using this :
$oldvalue = get_post_meta($post_id, 'geburtsdatum', true);
update_post_meta($post_id, 'geburtsdatum', strtotime($old_value));
Please backup your database before this or at least make a test on ore or two posts, but this should solve it. Then you will be able to later use :
date("d.m.Y", $yourunixstamp)
to get formated dates.
And then, also, your previous code will just become :
$args = array(
'numberposts' => -1,
'post_type' => 'mitglied',
'post_status' => 'publish',
'meta_key' => 'geburtsdatum',
'meta_value' => time(),
'meta_compare' => '>',
'orderby' => 'meta_value',
'order' => 'ASC'
);
$geburtstage = get_posts ( $args );
I think my task is not solveable with get_posts only, so i did it in 3 steps.
First, i used get_posts to get all members
$args = array(
'numberposts' => -1,
'post_type' => 'mitglied',
);
$geburtstage = get_posts ( $args );
Then filled an array with the data. For sorting I made a timestamp with the day and month of the birthday, but the actual year.
Although with this solution it would not have been necessary, I changed the date format to yyyy-mm-dd. #barakadam explained in his answer to my question how to do this.
I use the wordpress plugin Advanced Custom Fields, so I fetch the custom fields with get_field()
$mitglieder = array( array() );
$i = 0;
foreach($geburtstage as $post){
setup_postdata( $post );
$datum = explode( "-",get_field('geburtsdatum') );
$mitglieder[$i]['orderby'] = mktime(0, 0, 0, (int)$datum[1], (int)$datum[2], date('Y'));
$mitglieder[$i]['name'] = get_field( 'name' );
$i++;
}
The last step is using array_multisort to get the intended order
foreach ($mitglieder as $key => $row) {
$dates[$key] = $row['orderby'];
}
array_multisort($dates, SORT_ASC, $mitglieder);
Thanks to #barakadam and #Christopher for participating.

get_posts not returning all posts

I have to mount the blog posts manually, but I'm not sure if this is the correct way to work, It only brings 9 pages, with 4 posts each, but the blog has 83 posts!
<?php
$paged = get_query_var('paged');
$args = array(
'numberposts' => 4,
'offset' => $paged*4,
'orderby' => 'post_date',
'order' => 'DESC',
'post_type' => 'post',
'post_status' => 'publish',
'suppress_filters' => true
);
$posts_array = get_posts( $args );
?>
Thanks anyway.
Problem is your 'numberposts' is set to 4
Put it at -1 to get all posts:
'numberposts' => -1,
If you don't set numberposts here, WordPress will pull the number of posts from your Dashboard settings (under Settings -> Reading)
The below note is from this codex section.
Note: With use of the offset, the above query should be used only on a
category that has more than one post in it, otherwise there'll be no
output.
So in-order to display all posts, there should be at-least 2 posts in each categories.
You can try Loops to get all posts. Check The Loop in Action also.

Resources