I’m facing a problem I can’t solve.
I’d like to get the excerpt, title and link of the last post containing a particular meta-box button status.
For example: I would like to retrieve the last post with the status “1” on the meta-box button id “hotnews-status”. But I don’t know how to do this despite my multiple searches on the forum or in WordPress docs.
The final goal is to display these news in a component generated by the Visual Composer plugin.
Thank you in advance for your help and advice!
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
IF HOT NEWS IS A TAG (FIRST QUESTION ASKED FOR TAGS)
You gotta use a WP query where you query posts which have the tag “hot news” and order the result in descending order of the post ID, and then return 1 post, sth like this:
$query_args = array(
'post_type' => 'your_post_type',
'tax_query' => array(
array(
'taxonomy' => 'your_tag_taxonomy',
'field' => 'slug',
'terms' => 'hot_news'
)
),
'order_by' => 'ID',
'order' => 'DESC',
'posts_per_page' => 1
);
// Fire WP post query
$my_query = new WP_Query( $query_args );
// Check if at least one matching post was found
if ( $my_query->have_posts() ) {
// If yes, iterate through the found post(s)
while ( $my_query->have_posts() ) {
// Forward the post iterator to the currently iterated post of the loop.
// Like this you'll be able to get the iterated posts' content via the
// ```get_the...``` etc. functions
$my_query->the_post();
$posts_title = get_the_title();
$posts_excerpt = get_the_excerpt();
$link = get_the_permalink();
echo $posts_title." ".$posts_excerpt." ".$link;
}
}
// Reset the global $post object (should always be done after post queries)
wp_reset_postdata();
IF HOT NEWS IS A META KEY (LATER ASKED FOR META)
If you wanna query in function of metavalues, you need to formulate your query args as follows:
$query_args = array(
'post_type' => 'your_post_type',
'meta_query' => array(
array(
'key' => 'hotnews-status',
'value' => 1,
'type' => 'NUMERIC'
)
),
'order_by' => 'ID',
'order' => 'DESC',
'posts_per_page' => 1
);
The logic behind both queries is the following: Each time you create a newpost, that post will get an auto-incremented ID value associated to it (meaning = ID of the most recently added post + 1) in your database. To thus get the most recent post, order your queried posts in function of their post ID in descending order, and return 1 post (posts_per_page parameter of the query). And yeah then you add any additionally needed filters, such as tag / category / taxonomy / metavalue / whatever filters. Clear?
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0