Wordpress - Query comments by post meta - wordpress

I am using the code below (simplified) to display a list of the last 10 comments:
<?php
$args = array(
'post_type' => 'tarefa',
'number' => '10',
'order' => 'DESC',
'orderby' => 'comment_date',
//'meta_key' => 'field_name',
//'meta_value' => 'field_value',
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
foreach ( $comments as $comment ) {
echo '<p>';
echo get_the_title($comment->comment_post_ID) . '<br>'; //post title
echo $comment->comment_content; // comment content
echo '</p>';
};
?>
Question:
Well, meta_key and meta_value seem to be associated to comment_meta... But in my case, I have to display comments based on post_meta key and value.
Any sugestions?

You can try this code.
You need to add a query for posts to get array of post ides with meta key.
Then use that array into comments query argument.
//QUERY FOR POSTS WITH META KEY AND VALUE (META QUERY)
$post_args = array(
'post_type' => 'post',
'meta_key' => 'meta key',//Meta key of post
'meta_value' => 'meta value',//String or Numeric value
'meta_compare' => '=',
);
$post_query = new WP_Query( $post_args );
$posts_array= array();
if ( $post_query->have_posts() ) {
while ( $post_query->have_posts() ) {
$post_query->the_post();
$posts_array[] = get_the_ID(); //Array of post ids
}
wp_reset_postdata();
}
//YOUR COMMENT ARGS SHOULD BE THIS
$args = array(
'post_type' => 'tarefa',
'number' => '10',
'order' => 'DESC',
'orderby' => 'comment_date',
'post__in' => $posts_array, //THIS IS THE ARRAY OF POST IDS WITH META QUERY
);
Try this , then let me know the result.

My first question here at Stackoverflow and that worked perfectly.
Thank you very much, Souvik!
Below the final result (simplified):
$post_args = array(
'post_type' => 'tarefa',
'posts_per_page' => -1,
'meta_key' => 'field_name',
'meta_value' => 'field_value',
);
$post_query = new WP_Query( $post_args );
$posts_array= array();
if ( $post_query->have_posts() ) {
while ( $post_query->have_posts() ) {
$post_query->the_post();
$posts_array[] = get_the_ID(); //Array of post ids
}
wp_reset_postdata();
}
//YOUR COMMENT ARGS SHOULD BE THIS
$args = array(
'number' => '30',
'order' => 'DESC',
'orderby' => 'comment_date',
'post__in' => $posts_array, //THIS IS THE ARRAY OF POST IDS WITH META QUERY
);
$comments_query = new WP_Comment_Query;
$comments = $comments_query->query( $args );
foreach ( $comments as $comment ) {
echo '<p>';
echo get_the_title($comment->comment_post_ID) . '<br>'; //post title
echo $comment->comment_content; // comment content
echo '</p>';
};

Related

Order posts by Title length in WP_QUERY

I am having problem ordering the posts based on the title length. Here is my code:
<?php
$terms = get_terms(array(
'taxonomy' => 'vendor_category',
'slug' => 'venues',
'hide_empty' => false
));
?>
<?php
foreach ($terms as $term) {
$eventargs = array(
'post_type' => 'vendor',
'posts_per_page' => -1,
'orderby' => 'title',
'order' => 'ASC',
'meta_key' => 'primary_category',
'meta_value' => $term->term_id,
);
$eventqry = new WP_Query($eventargs);
?>
How can i sort the posts based on the title length in ascending order.
You can save title length in post meta on save_post hook. and then you can retrieve post order by post meta value.
You can use save_post hook to save the post meta. put this code in your active theme.
//for existing vendors
add_action('admin_init', 'udpate_existing_vendor');
function udpate_existing_vendor(){
$existing_vendor_updated = get_option('existing_vendor_updated', 'no');
if( $existing_vendor_updated == 'no' ){
$vendor_args = array(
'post_type' => 'vendor',
'post_status' => 'publish',
'posts_per_page' => -1
);
$vendors = new WP_Query( $vendor_args );
if( $vendors->have_posts() ) {
while ( $vendors->have_posts() ) { $vendors->the_post();
$length = strlen( get_the_title() );
update_post_meta( get_the_ID(), 'title_length', $length );
} wp_reset_postdata();
}
update_option('existing_vendor_updated', 'yes');
}
}
// for new vendor
function save_vendor_title_length( $post_id ) {
$length = strlen( get_the_title( $post_id ) );
update_post_meta( $post_id, 'title_length', $length );
}
add_action( 'save_post_vendor', 'save_vendor_title_length');
Here your query will look like.
$terms = get_terms(array(
'taxonomy' => 'vendor_category',
'slug' => 'venues',
'hide_empty' => false
));
foreach ($terms as $term) {
$eventargs = array(
'post_type' => 'vendor',
'posts_per_page' => -1,
'orderby' => 'meta_value_num',
'order' => 'ASC',
'meta_key' => 'title_length'
);
$eventqry = new WP_Query( $eventargs );
}

Need example code for wp_playlist_shortcode

I trying to use wp_playlist_shortcode for creating playlist with audio-files from all blog posts.
In official documentation i saw this parameter:
'ids'
(array) Create a playlist out of these explicit attachment IDs. If empty, a playlist will be created from all $type attachments of $id. Default empty.
I trying this code, and its doesn't working:
$attch_id = array('76', '73', '70', '67');
wp_playlist_shortcode( array( 'ids' => '$attch_id' );
How to create playlist with audio-files from all blog posts? Now i use this code, but it is a not playlist.
$audios = array( 'post_type' => 'attachment', 'posts_per_page' => -1, 'post_status' => null, 'post_parent' => null, 'post_mime_type' => 'audio/mpeg' );
$attachments = get_posts( $audios );
if ($attachments) {
foreach ( $attachments as $post ) {
setup_postdata($post);
$media_url = $post->guid;
$media_title = $post->post_title;
echo wp_audio_shortcode( array( 'src' => $media_url) );
echo '<p>' . $media_title . '</p>';
// print_r($media_url);
}
}
wp_reset_postdata();

Why isn't this Wordpress query sorting properly

I have a custom post_type called special_listing which contains a custom field called listing_index. A special_listing with a listing_index of 20, should appear before one with an index of 15, then 10, and so on. However this doesn't appear to be working and listings appear in whatever order they choose.
I'm not a PHP or Wordpress guy, I mainly deal with ASP.Net and C# so this is a bit confusing for me. Is there some simple mistake I'm making?
Function:
// Get the first $count listings with the highest indices for a given $region_slug:
function get_listings($region_slug, $count) {
$args = array(
'post_type' => 'special_listing',
'meta_key' => 'listing_region_slug',
'meta_value' => $region_slug
);
$posts = get_posts($args);
sort_array_on_field($posts, 'listing_index', 'DESC');
truncate_array($posts, $count);
return $posts;
}
View:
<?php
$listings = get_listings(get_microsite_slug() . '-microsite-home-featured', 4);
$i = 0;
if (sizeof($listings) > 0) : while ($i < sizeof($listings)) : $listing = $listings[$i]; // Loop and set current listing
?>
<section>
<a href="<?php echo $listing->destination; ?>">
<h3><?php echo $listing->post_title; ?></h3>
<p><?php echo $listing->post_content; ?></p>
</a>
</section>
<?php $i++; ?>
<?php endwhile; ?>
<?php endif; ?>
My attempt:
I don't know how to return the listing_index value
function get_sorted_listings($region_slug, $count){
$args = array(
'post_type' => 'kodakalaris_listing',
'meta_query' => array(
'relation' => 'AND',
array (
'key' => 'listing_region_slug',
'value' => $region_slug
),
array (
'key' => 'listing_index',
'value' => ''
),
orderby: 'listing_index',
order: 'DESC'
)
);
$posts = get_posts($args);
truncate_array($posts, $count);
return $posts;
}
Update
Trying a new way and it now pulls the content in by the published date. Still not ordering by listing_index, but at least it's not completely random either. I began looking to meta_query. Won't this only return a result with a single value? I've also tried out this other SO answer, but I find it's implementation confusing.
<?php
$args = array(
'post_type' => 'kodakalaris_listing',
'meta_key' => 'listing_region_slug',
'meta_value' => get_microsite_slug() . '-microsite-home-featured',
'posts_per_page' => 4,
'order' => 'DESC',
'orderby' => 'listing_index'
);
$listings = new WP_Query($args);
if ($listings->have_posts()) : while ($listings->have_posts()) : $listings->the_post();
?>
...
...
<?php
endwhile;
endif;
?>
You don't need to sort after you query. WP_Query has orderby parameters:
function get_listings($region_slug, $count) {
$args = array(
'post_type' => 'special_listing',
'meta_key' => 'listing_region_slug',
'meta_value' => $region_slug,
'orderby' => 'meta_value_num'
);
$posts = new WP_Query($args);
return $posts;
}
You'll then want to use The Loop rather than a foreach loop, in your view.
So I was able to figure this out after reading this article, but basically assigning a name to each meta_query array allows you to call which one should take priority when using orderby.
$args = array(
'post_type' => 'special_listing',
'posts_per_page' => 4,
'orderby' => 'index_clause',
'meta_query' => array (
'site_clause' => array (
'key' => 'listing_region_slug',
'value' => get_microsite_slug() . '-microsite-home-featured'
),
'index_clause' => array (
'key' => 'listing_index',
)
)
);
Change the function to :
<?php
// Get the first $count listings with the highest indices for a given $region_slug:
function get_listings($region_slug, $count) {
$args = array(
'post_type' => 'special_listing',
'orderby' => 'listing_index',
'order' => 'DESC',
'meta_key' => 'listing_region_slug',
'meta_value' => $region_slug
);
$posts = get_posts($args);
return $posts;
}

Using Wp-query with serialized postmeta values

I've stored some serialized data in wp-postmeta table, e.g.:
$data = array(
'details' => $dettagli,
'vernice' => $vernice,
'reperibile' => $reperibile,
'valore2' => $valore2,
'valuta2' => $valuta2,
'subcat' => $subcat
);
add_post_meta($post_ID, 'meta', $data);
I would like to extract all the posts with the key "details" and value = "4". How can I do it?
I've tried doing this code:
$args = array(
'post_type' => 'custom-post-type',
'posts_per_page' => -1,
'meta_query' =>
array(
'key' => 'details',
'value' => '4',
'compare' => 'LIKE'
),
'meta_key' => 'meta',
);
$query = new WP_Query( $args );
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
the_ID();
}
}
What is wrong?
meta_query is an array of arrays.
You might try this:
$args = array(
//parameters here
'meta_query' => array(
array(
'key' => 'details',
'value' => '4',
'compare' => 'LIKE'
)
),
//remove meta_key => 'meta'
);
however i'm not 100% sure if this could help you, let's try it, please let me know if you get stuck.
UPDATE
Serialized array in post meta are not good deals. So i suggest you to change your save function to store custom fields individually.
I've found a way to unserialize your previous post meta values:
$args = array(
'post_type' => 'collectable',
'meta_key' => 'meta',
'posts_per_page' => -1
);
$query = new WP_Query( $args );
if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post();
//Get data for each post
$data = get_post_meta( $post->id, 'meta', true );
//Add post meta value individually for each field
add_post_meta( $post->ID, 'details', $data['details'] );
add_post_meta( $post->ID, 'vernice', $data['vernice'] );
add_post_meta( $post->ID, 'reperibile', $data['reperibile'] );
add_post_meta( $post->ID, 'valore2', $data['valore2'] );
add_post_meta( $post->ID, 'valuta2', $data['valuta2'] );
add_post_meta( $post->ID, 'subcat', $data['subcat'] );
//Delete serialized data
delete_post_meta( $post->ID, 'meta', $data );
endwhile; endif;
Now you should be able to query as you want.
Hope it helps!
Have you tried this .Just a try
$the_query = new WP_Query(array( 'meta_key' => 'open', 'meta_value' => 'yes' ));

wordpress advanced custom fields order posts by date-picker

For those familiar with the ACF plugin...
I have some events posts that are currently displaying in post order (see code below). I would like them to display in the order specified by the date-picker.
Can anyone tell me what to amend in the following - I have tried the documentation on the site, but my PHP is basic.
It says I need to add
'orderby' => 'meta_value_num',
But no joy.
<?php function le_whatson_aside() {
//THis loop is for the CPT
$args = array(
'post_type' => 'events', // enter your custom post type
'orderby' => 'menu_order',
'order' => 'ASC',
'posts_per_page'=> '10', // overrides posts per page in theme settings
'tax_query' => array(
array(
'taxonomy' => 'audience', //name of custom taxonomy
'field' => 'slug',
'terms' => 'everyone' //name of category
)
)
);
$loop = new WP_Query( $args );
if( $loop->have_posts() ):
?>
<div>
<h2>What's On</h2>
</div>
<div class="whatson entry-content">
<?php
while( $loop->have_posts() ): $loop->the_post(); global $post;
?>
<p class="whatson-date"><?php echo date("dS F Y",strtotime(get_field('date')));?></p>
<h4 class="whatson-title"><?php echo get_the_title(); ?></h4>
<?php
endwhile;
?>
</div>
<?php
endif; }
Thanks all.
Try
orderby=date or `post_date`
If not the easiest way is to save your custom field 'startdate' as a unix timestamp. To do this, add the following to your theme's functions.php
// CREATE UNIX TIME STAMP FROM DATE PICKER
function custom_unixtimesamp ( $post_id ) {
if ( get_post_type( $post_id ) == 'events' ) {
$startdate = get_post_meta($post_id, 'startdate', true);
if($startdate) {
$dateparts = explode('/', $startdate);
$newdate1 = strtotime(date('d.m.Y H:i:s', strtotime($dateparts[1].'/'.$dateparts[0].'/'.$dateparts[2])));
update_post_meta($post_id, 'unixstartdate', $newdate1 );
}
}
}
add_action( 'save_post', 'custom_unixtimesamp', 100, 2);
The do:
$today = time();
$args = array(
'post_type' => 'events',
'posts_per_page' => 5,
'meta_query' => array(
array(
'key' => 'unixstartdate',
'compare' => '>=',
'value' => $today,
)
),
'meta_key' => 'startdate',
'orderby' => 'meta_value',
'order' => 'ASC',
);
$query = new WP_Query( $args );
$events = $query->posts;
Got it from here
I spent hours looking for this and I can confirm it works. See my code below.
If you're trying for a loop on a page with other loops, with a bunch of template parts in there, and you would also like to sort by a category, it goes :
$today = time();
$the_query = new WP_Query( array(
'post_type' => 'events',
'posts_per_page' => 3,
'meta_query' => array(
array(
'key' => 'start',
'value' => $today,
'compare' => '>=',
)
),
'tax_query' => array(
array (
'taxonomy' => 'the_taxonomy',
'field' => 'slug',
'terms' => 'the-name'
)
),
'meta_key' => 'start',
'orderby' => 'meta_value',
'order' => 'ASC',
) );
while ( $the_query->have_posts() ) :
$the_query->the_post();
get_template_part( 'content-events' );
endwhile;
wp_reset_postdata();
Of course, you have to include Unix the function beforehand.
function custom_unixtimesamp ( $post_id ) {
if ( get_post_type( $post_id ) == 'events' ) {
$startdate = get_post_meta($post_id, 'start', true);
if($startdate) {
$dateparts = explode('_', $startdate);
$newdate1 = strtotime(date('d.m.Y H:i:s', strtotime($dateparts[1].'/'.$dateparts[0].'/'.$dateparts[2])));
update_post_meta($post_id, 'unixstartdate', $newdate1 );
}
}
}
add_action( 'save_post', 'custom_unixtimesamp', 100, 2);
I would approach it like this. Create a "named" meta query and then order by that query. The meta query uses "EXITS" to filter out posts that don't have a date set. This works with the ACF date picker when the dates are saved to the database using the default format d/m/Y. This approach also works with the datetime picker.
$query = new WP_Query([
"meta_query" => [
"custom_date" => [
"key" => "date",
"compare" => "EXISTS",
"type" => "DATETIME",
]
],
"orderby" => [
"custom_date" => "ASC",
],
]);
Be sure to update the value for key to whatever your ACF field name is.

Resources