Modifying code to get recent commented posts above older post - php

I am trying to get this work, but it's not entirely working. This is how I currently query my posts:
<?php
// the query
$the_query = new WP_Query( array( 'posts_per_page' => -1 ) );
if ( $the_query->have_posts() ) :
?>
<!-- pagination here -->
<!-- the loop -->
<?php
while ( $the_query->have_posts() ) : $the_query->the_post();
?>
<li data-href="<?php $zlink = get_the_permalink(); echo preg_replace("#/$#im", '', $zlink);?>">
<div>
<a class="button" href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
</div>
What I am trying to achieve, is the following:
Show recently commented post on top of posts that have a newer publish date...
If a blog-post has a comment, regardless of how old that blog-post is, I want that blog-post above a newer blog-post, if that newer one has no update (meaning: no recent comments).
I started by showing the recently commented posts on top (see below), but this totally neglects the fact that there are posts without comments and I can't find a way to combine both and show them in one list.
<?php
$args = array(
'status' => 'approve',
'number' => 6,
'order' => 'DESC'
);
$comments = get_comments($args);
foreach($comments as $comment) : $count++;
$post_args = array(
'post_type' => 'post',
'p' => $comment->comment_post_ID,
'posts_per_page' => 1
);
$posts = get_posts($post_args);
foreach($posts as $post) : setup_postdata($post);
the_title();
endforeach;
endforeach;
?>
Could someone help?

The below creates an empty array, adds all the posts with comments to that array. It then adds all the posts without comments. Finally, it sorts them by the comment date or the post date, depending on whether that post had any comments or not
//create an array to stuff all your posts in
$arrAllPosts = array();
$args = array(
'post_type' => 'post', //show only posts (not pages, etc)
'comment_count' => array( //pass it an array
'value' => 1, //value is 1, with compare means greater than or equal to 1
'compare' => '>='
),
'posts_per_page' => -1 //gimme all of them
);
$postsWithComments = new WP_Query($args);
while($postsWithComments->have_posts()) {$postsWithComments->the_post();
//get the comments for this post
$comments = get_comments(array(
'post_id' => get_the_ID(), //pass the post ID
'orderby' => 'comment_date', //tell it to sort by the comment date, so you only get the latest
'number' => 1 //just get the latest
));
foreach($comments as $comment) { //we're only looping this once, since there is only one
$arrAllPosts[] = array(
'dateToSortBy' => $comment->comment_date, //we'll use comment date to sort by later, instead of the post date
'the_post_obj' => $post //add the global post object, which is currently set to the current post
);
}
}
//now we get the posts with no comments
$args = array(
'post_type' => 'post', //Only posts (not pages, etc)
'comment_count' => 0, //Posts with no comments only
'posts_per_page' => -1 //gimme all of them
);
$postsNoComments = new WP_Query($args); //run it
while($postsNoComments->have_posts()) {$postsNoComments->the_post(); //loop it
$arrAllPosts[] = array(
'dateToSortBy' => $post->post_date, //we'll use the post date to sort by
'the_post_obj' => $post //add the global post object, which is currently set to the current post
);
}
function date_compare($a, $b) { //create a custom function to sort the array by the date of the post or the date of the comment
$tmA = strtotime($a['dateToSortBy']); //convert to time
$tmB = strtotime($b['dateToSortBy']); //convert to time
return ($tmA < $tmB)?true:false;
}
usort($arrAllPosts, 'date_compare');
//Display the title for each post, from the sorted list
foreach($arrAllPosts as $curPost) {
$post = $curPost['the_post_obj']; //make this the global post object
setup_postdata($post); //setup the data
echo "<a href='" . get_the_permalink() . "'>" . get_the_title() . "</a>";
}

Related

Querying post by ID always returning the latest post (WordPress)

I'm trying to retrieve a single post by the ID. Stories is my custom post type and it currently has three posts:
Blog 1 (ID: 1)
Blog 2 (ID: 14)
Blog 3 (ID: 49)
I have a variable called $story_one. $story_one has the value of 14.
I'm now trying to retrieve information from the post with the ID of 14, so I've done:
<?php
$args = array(
'post_type' => 'stories',
'id' => $story_one,
'posts_per_page' => 1
);
$query = new WP_Query( $args );
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
the_title();
}
wp_reset_postdata();
}
?>
This returns Blog 3. Blog 3 is the newest post in stories. When I've specified it to pull content from the post with the ID of 14 (Blog 2), why is it. showing me content from the latest blog?
The query_var for post ID is p not id
$args = array(
'post_type' => 'stories',
'p' => $story_one,
'posts_per_page' => 1
);
$query = new WP_Query( $args );
if( $query->have_posts() ) {
while( $query->have_posts() ) {
$query->the_post();
the_title();
}
wp_reset_postdata();
}
Instead of using WP_Query(), you can use get_post(), like this:
<?php
$post = get_post($story_one);
if(!empty($post)):
echo $post->post_title;
echo get_field("field name", $story_one);
endif;
?>
About getting only from stories post type. Every post type is stored in the same posts table, so they have to use different post IDs.
The second parameter of get_field() function is the post ID.
I would suggest continuing to use WP_Query. The issue is just one of the query parameters.
I would ad 'p', to yours $args variable...like this...
$args = array(
'post_type' => 'stories',
'p' => $story_one,
'posts_per_page' => 1
);
And that should get you the result you're after.
Good luck!

Limit excerpts of post types

I have two post types, the regular posts and a custom post type. Everything is working fine and I show only 5 posts. One as a full post and four as excerpts. The problem I have is that the excerpts is showing the latest posts, independent of post category. I want to show two of the posts and two of the custom post type.
$args = array(
'post_type' => array( 'post', 'tutorial' ),
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) :
$count = 0;
while ( $query->have_posts() ) : $query->the_post();
if ( $count == 0 ) { ?>
<h2><?php the_title(); ?></h2>
<?php the_content();
$count ++;
} else { ?>
<h2><?php the_title(); ?></h2>
<?php the_excerpt();
}
endwhile;
endif;
wp_reset_postdata();
?>
Expected output should be the latest post as a full post, as it is working now. Then it should display the two latest posts of post type post and two latest posts of post type tutorial.
Basicly you only need to sort by posttype
$args = array(
'post_type' => array( 'post', 'tutorial' ),
'orderby' => 'post_type',
'order' => 'ASC',
);
If you want to keep the sorting of date as a secondary sort this should work (not tested).
$args = array(
'post_type' => array( 'post', 'tutorial' ),
'orderby' => array ('post_type' => 'ASC', 'order' => 'DESC' ),
);
For more information check the WP_Query documentation
Keep in mind that if you have 5 posts newer then any of your tutorials, none will show.
To guarantee 3 posts and 2 tutorials you will need to split the code in 2 wp_query loops with the posts_per_page parameter.

How to display posts of taxonomy in WordPress page template?

Not sure if this has been asked before, but I'm a bit lost. I've created a "Newsroom" Pods with a custom taxonomy of Newsroom Category. Newsroom Category has 3 fields: Press Release, Media, Others. I have a WordPress page template: taxonomy-newsroom_category.php
taxonomy-newsroom_category.php is used to display Pods posts if meets the following:
1 - pods = 'newsroom'
2 - taxonomy = 'press_release' || 'media' || 'others'
My issue right now is that I can't find a way to display the post details:
image(thumbnail), title(post title), date_published
I hope someone can help. Thanks
Here's the code I'm currently using:
<?php
//Setup Pod object
//Presuming permalink structure of example.com/pod-name/item-name
//See http://pods.io/code/pods/find
//Set $params to get 5 items
$params = array(
'limit' => 5,
);
//get current pod name
$pod_name = pods_v( 0, 'newsroom');
//get pods object
$pods = pods( $pod_name, $params );
//check that total values (given limit) returned is greater than zero
if ( $pods->total() > 0 ) {
//loop through items using pods::fetch
while ($pods->fetch() ) {
//Put title/ permalink into variables
$post_title = $pods->display('post_title');
$date_published = $pods->display('date_published');
$permalink = site_url( trailingslashit( $pod_name ) . $pods->field('permalink') );
?>
<div class="news-item col-sm-4">
<div class="news-item-img"></div>
<div class="news-item-header">
<h5 class="news-category"></h5>
<h2 class="news-item-title"><?php echo $post_title; ?></h2>
<h5 class="news-item-date"><?php echo $date_published; ?></h5>
</div>
</div><!-- close -->
<?php
} //endwhile;
} //endif;
// Output Pagination
//see http://pods.io/docs/code/pods/pagination
echo $pods->pagination( );
?>
I also found out solution for that... I had my Custom Post Type "studies" and I had to filter them, based on custom taxonomy category. If you want to write Posts of one taxonomy category, try to use something like that:
$type = $_GET['type'];
$args = array(
"post_type" => "studien",
"post_per_page" => -1,
"relation" => "AND"
);
if($type != "") {
$args['tax_query'][] = array(
'taxonomy' => 'market',
'field' => 'slug',
'terms' => $type
);
$wp_query = new WP_Query($args);
}
$type represents one category in my created Taxonomy (value comes from HTML code in select option), $args Is some query on database and 'market' is slug of my custom Taxonomy, $wp_query returns all filter Posts
screenshot of my custom taxonomy in custom post type. As you can see, I have two groups. First is clicked in two Posts and Second is clicked in last two Posts. Maybe it will helps you to give imagination
Check this out https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters. This document explained how to query with custom post type and taxonomy in details. Youd code could be something like this.
$args = array(
'post_type' => 'newsroom',
'tax_query' => array(
array(
'taxonomy' => 'newsroom_category',
'field' => 'slug',
'terms' => 'press_release',
),
),
);
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
$id = get_the_ID(); // with post id, you can get whatever you want.
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
/* Restore original Post Data */
wp_reset_postdata();
} else {
// no posts found
}
from the wordpress documenation:
https://codex.wordpress.org/Custom_Taxonomies
we have the below , for taxonomy person
$args = array(
'tax_query' => array(
array(
'taxonomy' => 'person',
'field' => 'slug',
'terms' => 'bob'
)
)
);
$query = new WP_Query( $args );

Wordpress loop inside loop

I have a normal loop that outputs posts based on the given $args.
After three posts I want to insert a post that is from a Featured category. I've tried starting a new WP_Query, simple query_posts in different combinations. Nothing seems to work. Any ideas why ?
$args = array(
'post_type' => 'post',
'posts_per_page' => $count,
'paged' => $paged,
'page' => $paged,
'cat' => $cat,
'ignore_sticky_posts' => 1
);
// create a new instance of WP_Query
$my_query = new WP_Query($args);
<ul>
<?php
$i = 0;
if ($my_query->have_posts()) : while ($my_query->have_posts()) : $my_query->the_post();
if($i == 3): ?>
<li> //insert here one post from featured category
</li>
<?php endif; ?>
<li>
// the normal query stuff is here
</li>
<?php $i++ //post counter
endwhile; //end loop while
endif; //end loop
?>
</ul>
I did it this way. Before the main query I did a special query for the featured post.
$args2 = array(
'post_type' => 'post',
'posts_per_page' => 1,
'category_name' => 'TheCategoryName-Slug',
'ignore_sticky_posts' => 1
);
$my_query2 = new WP_Query($args2);
$post_ids = array(); //create an array to store the ids of the posts
if ($my_query2->have_posts()) : while ($my_query2->have_posts()) : $my_query2->the_post();
$post_ids[] = get_the_ID();
endwhile;
wp_reset_postdata();
endif;
After you have all the ids you can use them to get the data you need. Basically, all the data from the wp_posts table (http://codex.wordpress.org/Database_Description#Table:_wp_posts). The post author is returned as an id that can be used to get the name using get_userdata() function.
echo get_post_field('post_title', $post_ids[0]);
echo get_post_field('post_author', $post_ids[0]);
echo get_post_field('post_date', $post_ids[0]);

How To Display Categories and the posts inside of a Custom Post Type

I need some help here as I've exhausted every place I can trying to find information. This is what I'm trying to do:
I have created a custom Post type in my admin called "Classes"
That works fine, the data works great and it's inputting in the admin.
I want to make a custom template to show this custom post type. However, everything I try it's not displaying properly. I've tried many code variations.
I know someones already done this and has the block of code to display this. This is what I need the code to do:
List All categories in my custom post type 'classes'
List all posts (show all content, not a link or excerpt) inside of each category.
Display it as such (I'm using Jquery Accordion)
the_category()
the_title()
the_content()
========================================================
By the way, Here is the block of code I'm currently using. It does work, but it ONLY shows the posts, all of them. It does not show the category with posts inside of them.
<?php
$type = 'classes';
$args = array (
'post_type' => $type,
'post_status' => 'publish',
'paged' => $paged,
'posts_per_page' => 10,
'ignore_sticky_posts'=> 1
);
$temp = $wp_query; // assign ordinal query to temp variable for later use
$wp_query = null;
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
echo '<h3 class="acc1">';
the_title();
echo '</h3>';
echo '<div class="sc"><div class="vs">View Schedule</div>';
the_content();
echo '</div>';
endwhile;
else :
echo '<h2>Not Found</h2>';
get_search_form();
endif;
$wp_query = $temp;
?>
Community, I need you. Please give your feedback!
What you want to do is actually start with a category query. You have to make sure you query all your categories with your custom post type:
Then for each category you would do pretty much what you have above.
$taxonomy = 'classes';
$args = array('hide_empty' => false,);
$terms = get_terms( $taxonomy, $args );
foreach($terms as $val) {
$term_id = $val->term_id;
$term_name = $val->name;
// now do post query
}
You most likely would have to display the category name as a header for your accordion as well.
Here's all the args for get_terms:
http://codex.wordpress.org/Function_Reference/get_terms
For that query you also most likely have to use a Simple Taxonomy Query (search for that on the page).
http://codex.wordpress.org/Class_Reference/WP_Query
By adding this arg to your above query:
'tax_query' =>
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( $term_name )
)
Is that what you were looking for?
There might be a better way to do this but I just had to recently do this and did pretty much what I just outlined here.
I should have been more clear and said to put the posts query within the foreach of the terms query.
Here's the updated answer based on your last reply (I have not tested this).
<?php
$taxonomy = 'classes';
$args = array('hide_empty' => false,);
$terms = get_terms( $taxonomy, $args );
foreach($terms as $val) {
$term_id = $val->term_id;
$term_name = $val->name;
$type = 'classes';
$args = array (
'post_type' => $type,
'post_status' => 'publish',
'paged' => $paged,
'posts_per_page' => 10,
'ignore_sticky_posts'=> 1,
'tax_query' =>
array(
'taxonomy' => 'category',
'field' => 'slug',
'terms' => array( $term_name )
)
);
$temp = $wp_query; // assign ordinal query to temp variable for later use
$wp_query = null;
$wp_query = new WP_Query($args);
if ( $wp_query->have_posts() ) :
while ( $wp_query->have_posts() ) : $wp_query->the_post();
echo '<h3 class="acc1">';
the_title();
echo '</h3>';
echo '<div class="sc"><div class="vs">View Schedule</div>';
the_content();
echo '</div>';
endwhile;
else :
echo '<h2>Not Found</h2>';
get_search_form();
endif;
$wp_query = $temp;
}
?>

Categories