0
<?php

$args = array(
    'post_type' => 'product',  
    'post_status' => 'publish',
    'meta_key' => 'views',
    'orderby' => 'meta_value_num',
    'order'=> 'DESC', // sort descending
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {
    // Start looping over the query results.
    while ( $query->have_posts() ) {

        $query->the_post();

        printf( '<a href="%s" class="link">%s</a>', get_permalink(), get_the_title());

    }

}

// Restore original post data.
wp_reset_postdata();

?>

This is the first time i've worked with wpquery.

Two questions

  1. how do i add a comma each item but the last?
  2. How could i've written this better?
0

Try with this:

<?php

$args = array(
    'post_type' => 'product',  
    'post_status' => 'publish',
    'meta_key' => 'views',
    'orderby' => 'meta_value_num',
    'order'=> 'DESC', // sort descending
);

// Custom query.
$query = new WP_Query( $args );

// Check that we have query results.
if ( $query->have_posts() ) {
    // Start looping over the query results.
    while ( $query->have_posts() ) {

        $query->the_post();

        $comma_char = ($query->current_post + 1) < ($query->post_count) ? "," : "";//add comma if not last post
        printf('<a href="%s" class="link">%s</a>' . $comma_char, get_permalink(), get_the_title());

    }

}

// Restore original post data.
wp_reset_postdata();

?>

as for the second question (its 1 question for post by the way), looks like a standard WordPress query, its kind of hard to say how it can be improved without knowing the details about it.

  • Im still getting the last comma. – thomaswtran Feb 17 '17 at 0:08
  • updated, sorry i was using the wrong variable – David Lee Feb 17 '17 at 0:14
0

You really don't need to set up a global post object each time you ask for a title or a permalink. It is always better to search for a solution that doesn't involve globals. :)

For listing that should look like "Apples, Bananas, and Oranges", you can use wp_sprintf_l(). It uses a localized special separator for the last item. In English, this is an Oxford comma plus an and.

Here is how I would have done it.

if ( $query->have_posts() ) {

    $links = array_map(
        function( \WP_Post $post ) {
            return sprintf(
                '<a href="%s" class="link">%s</a>',
                get_permalink( $post ),
                get_the_title( $post )
            );
        },
        $query->posts
    );

    print wp_sprintf_l( '%l', $links );
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.