I want to add a meta data to my attachment posts, so I can get them in order by meta value later. That meta value would be 'price'
.
So I thought this could work:
I have this args:
$args = array(
'order' => 'ASC',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => -1,
);
Then I get posts (attachment posts) with $att_posts = get_posts($args);
Then I would like to add to each attachment post, a meta data called 'price'
, which value I get by get_post_meta($post->ID, 'key', true)['price'];
.
So I thought this would do the work to add the meta data:
foreach( $att_posts as $att ){
wp_update_attachment_metadata(
$att->ID,
array( "price" => get_post_meta( $post->ID, 'key', true )['price'] ) )
);
}
So i declared other args again but this time to order by 'meta_value_num'
, with meta key 'price'
.
But it didn’t work.
Any body knows a simple way to make that possible? Any tips?
Thanks.
EDIT:
Here is all my code to get attachment images ordered by 'meta_key'
'price'
.
$args = array(
'order' => 'ASC',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => -1,
);
$att_posts = get_posts($args);
if ($att_posts) {
foreach( $att_posts as $att ) {
wp_update_attachment_metadata(
$att->ID,
array( 'price' => get_post_meta( $post->ID, 'price', true ) )
);
}
}
$args = array(
'order' => 'ASC',
'orderby' => 'meta_value_num',
'meta_key' => 'price',
'post_type' => 'attachment',
'post_parent' => $post->ID,
'post_mime_type' => 'image',
'post_status' => null,
'numberposts' => -1,
);
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
echo '<a href="https://wordpress.stackexchange.com/questions/181462/. $surl ."https://wordpress.stackexchange.com/" . $post->post_name. '>' .
wp_get_attachment_image( $attachment->ID, 'thumbnail_large' ) . '</a>';
}
} else {
echo '<a href=".$surl."https://wordpress.stackexchange.com/" . $post->post_name . '>' .
'<div class=\'thumbnail-small-img-search\'></div>' . '</a>';
}
But still doesn’t work.
Another way of asking is: How can I add meta data to attachment posts. And later, get the attachment posts ordered by this meta data called 'price'
.
The objective of this is to display a paged list of posts with images ordered by price from cheapest to expensive.
This would be invoked by a submit button to one page of the website.