简体   繁体   中英

Display 10 recently added posts category name only in wordpress using WP_Query()

Now I'm displaying the category list like this code:

<?php
    $arg = array(
       'orderby' => 'name',
       'number'   => 6,
    );
    $categories = get_categories($arg);
    foreach ($categories as $cat) {
?>
     <span class="firstMenuSpan" style="padding-right:34px;color:#000;">
          <a href="?catId=<?php echo $cat->cat_ID; ?>"><?php echo $cat->name; ?></a>
     </span>
<?php
}
?>

Now categories are displayed in alphabetical order, But i need to display categories of recent added post.

Any idea or code will be helpful.

Or else is there any sort the category values by means of in built WP_Query arguments

And I need a clarification that can i able to get category names with the help of method like below code:

<?php
    $args = array(
     'numberposts' => 10,
     'offset' => 0,
     'category' => 0,
     'orderby' => 'post_date',
     'order' => 'DESC',
     'include' => '',
     'exclude' => '',
     'meta_key' => '',
     'meta_value' =>'',
     'post_type' => 'post',
     'post_status' => 'draft, publish, future, pending, private',
     'suppress_filters' => true
   );

   $recent_posts = wp_get_recent_posts( $args, ARRAY_A );
?>

If i get categories by the above method, Can i able to limit the values and make displaying as one for repeating post category value.

Any help regarding above method also useful.

Main Quote/Aim/Requirement or End-line:

Need to display only a list of 10 category name of recently updated/added post as a menu.

There are multiple ways to solve this problem and get you the list you require. I'll show you a couple of different ways to get a list of categories for the last 10 posts.

Note: See the feature request interpretation below, as the code I'm giving you is for the second one.

Code Snippet 1 - Using WordPress Built-ins

The first code solution does the following:

  1. Gets an array of post IDs
  2. If an array is returned, then it fetches the categories from that list.

I've broken the functionality into separate purposeful functions for reusability:

/**
 * Get a list of the most recent Post IDs.
 *
 * @since 1.0.0
 *
 * @return array|false Returns an array of post
 *                      IDs upon success
 */
function get_most_recent_post_ids() {
    $args = array(
        'posts_per_page' => 10,
        'orderby'        => 'post_date',
        'post_status'    => 'publish',
        'fields'         => 'ids',
    );

    $query = new WP_Query( $args );
    if ( ! $query->have_posts() ) {
        return false;
    }

    wp_reset_postdata();

    return $query->posts;
}

/**
 * Get the categories of the most recent posts.
 *
 * @since 1.0.0
 *
 * @return array|bool Returns an array of WP_Term objects upon success;
 *                      else false is returned.
 */
function get_most_recent_posts_categories() {
    $most_recent_post_ids = get_most_recent_post_ids();
    if ( ! $most_recent_post_ids ) {
        return false;
    }

    $categories = wp_get_object_terms( $most_recent_post_ids, 'category');
    if ( ! $categories || is_wp_error( $categories ) ) {
        return false;
    }

    return $categories;
}

Code Snippet 2 - Writing your own SQL Query

Another way to get this list is to write a native SQL query and use $wpdb . In this code example, we do one database hit to grab a list of categories. For each category, it returns the term ID, name, and slug for you to use.

/**
 * Get a list of categories for the most recent posts.
 *
 * @since 1.0.0
 *
 * @param int $number_of_posts Number of the most recent posts.
 *                              Defaults to 10
 * 
 * @return array|bool
 */
function get_most_recent_posts_categories( $number_of_posts = 10 ) {
    global $wpdb;

    $sql_query = $wpdb->prepare(
"SELECT t.term_id, t.name, t.slug
FROM {$wpdb->term_taxonomy} AS tt
INNER JOIN {$wpdb->terms} AS t ON (tt.term_id = t.term_id)
INNER JOIN {$wpdb->term_relationships} AS tr ON (tt.term_taxonomy_id = tr.term_taxonomy_id)
INNER JOIN {$wpdb->posts} AS p ON (tr.object_id = p.ID)
WHERE p.post_status = 'publish' AND tt.taxonomy = 'category'
GROUP BY t.term_id
ORDER BY t.term_id ASC, p.post_date DESC
LIMIT %d;", 
        $number_of_posts );

    $categories = $wpdb->get_results( $sql_query );
    if ( ! $categories || ! is_array( $categories ) ) {
        return false;
    }

    return $categories;
}

Using the Code Above

You use both options above like this:

$categories = get_most_recent_posts_categories();
if ( ! $categories ) {
    return;
}

foreach ( $categories as $category ) : ?>
    <span class="firstMenuSpan" style="padding-right:34px;color:#000;">
              <a href="?catId=<?php esc_attr_e( $category->term_id ); ?>"><?php esc_html_e( $category->name ); ?></a>
    </span>
<?php endforeach;

The above code gets the list of categories. If none was returned, then you bail out. Otherwise, you can loop through each of them and build your HTML list.

A few things to note about the code:

  1. If no categories are returned, the code bails out. You'll need to adjust this if you have other code running below this snippet.
  2. You want to properly escape the values before rendering them out to the browser. Notice that the code uses esc_attr_e and esc_html_e . Keep your web pages clean, sanitized, and safe.

Again there are multiple ways to accomplish this feature request. I gave you two options. You can adjust them how you want and then select the one that fits your needs.

Interpreting the Feature Request

The feature request has two different meanings:

Need to display only a list of 10 category name of recently updated/added post as a menu.

We can interpret the request as follows:

  1. Reading it literally, it says I want 10 category names period. I want them from the most recent posts.
  2. Or... For the last 10 posts (the most recent), get the list of category names.

Interpretation 1

There's a difference in the intent of this feature request. The first interpretation says it wants 10 categories regardless of the number of recent posts.

Let's think about that. If the last 10 posts had only a population of 5 categories amongst them, then you'd have to expand the post search until you gathered all 10 categories.

That's a different requirement than the second interpretation and it will require different code.

Interpretation 2 (The one I used)

This one says for the last 10 posts, get their categories. This feature request makes more sense as the list is tied to the last and most recent content.

Make sure you find out which version they want.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM