• Resolved searay

    (@searay)


    I want my visitors to have the ability to sort posts by stars rating and custom meta box(completed projects). I found both values in the database, but I don’t know how use them. I studied WP codex and found this code, which I tought might be useful, but don’t really know how to start.

    <?php
    /*
    Template Name: Qbased
    */
    ?>
    
    <?php get_header(); ?>
    
    <div id="content" class="narrowcolumn">
    
    <?php
    
     $querystr = "
        SELECT $wpdb->posts.*
        FROM $wpdb->posts, $wpdb->postmeta
        WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
        AND $wpdb->postmeta.meta_value = 'email'
        AND $wpdb->posts.post_status = 'publish'
        AND $wpdb->posts.post_type = 'post'
        AND $wpdb->posts.post_date < NOW()
        ORDER BY $wpdb->posts.post_date DESC
     ";
    
     $pageposts = $wpdb->get_results($querystr, OBJECT);
    
    ?>
     <?php if ($pageposts): ?>
      <?php global $post; ?>
      <?php foreach ($pageposts as $post): ?>
        <?php setup_postdata($post); ?>
    
        <div class="post" id="post-<?php the_ID(); ?>">
          <h2><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
          <?php the_title(); ?></a></h2>
          <small><?php the_time('F jS, Y') ?> <!-- by <?php the_author() ?> --></small>
          <div class="entry">
             <?php the_content('Read the rest of this entry ?'); ?>
          </div>
    
          <p class="postmetadata">Posted in <?php the_category(', ') ?> | <?php edit_post_link('Edit', '', ' | '); ?>
          <?php comments_popup_link('No Comments ?', '1 Comment ?', '% Comments ?'); ?></p>
        </div>
      <?php endforeach; ?>
    
      <?php else : ?>
        <h2 class="center">Not Found</h2>
        <p class="center">Sorry, but you are looking for something that isn't here.</p>
        <?php include (TEMPLATEPATH . "/searchform.php"); ?>
     <?php endif; ?>
    
    </div>
    
    <?php get_sidebar(); ?>
    
    <?php get_footer(); ?>

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    Meta boxes could store their related data anywhere, but usually this data is stored in the postmeta table. I’m assuming this is where you found the values? Also, the best approach depends on the context in which you are querying for posts. The code you found is fine in certain contexts, but it’s generally perhaps not the best approach.

    Unless you’re an SQL whiz, I’d suggest you use the WP_Query class. This is what WP uses internally to query for posts. It’s often inefficient to make new queries because WP has already made a query by the time your custom code is encountered. If you’re disregarding that query and making your own, you’re wasting server resource. If you’re still using the main query and making an additional query, maybe for related posts at the bottom of a category archive list for example, then making your own query is fine.

    If your best approach would be to alter the query WP makes by default, you alter this query by using the ‘pre_get_posts’ action.

    Whether you will be altering the main query or making your own, you use the ‘orderby’ query argument to specify the desired ordering. This Codex article does not address the issue of ordering complex meta queries though. Until recently, complex ordering was not possible with WP_Query. Since 4.2, this has changed.

    I fear that I’ve already overwhelmed you and we haven’t even talked about how to get user input into the query or how to query for meta data, only ordering by it. Break down these tasks into small parts and you’ll be able to work through it. I can provide more information if you give us specific information on how you would like this to work.

    Thread Starter searay

    (@searay)

    Yes, postmeta is the table that stores my meta box data. And I am not SQL whiz unfortunately, but I have some knowledge about it.

    Maybe I will show you what kind of sorting I need, here is the link

    The difference is I need to sort Builders posts not projects as in the link above. Here is the link to the builders list by star rating(taken from YASR plugin) or “2015 Projects” numerical value metabox.

    I looked at the code for sorting projects and it looks like this

    <div class="sort-controls">
        <strong><?php _e('Sort By','framework');?>:</strong>
        &nbsp;
        <?php
        if ( isset( $_GET['sortby'] ) ) {
            $sort_by = $_GET['sortby'];
        } else {
            if ( is_page_template( array (
                'template-property-listing.php',
                'template-property-grid-listing.php',
                'template-map-based-listing.php',
                ) ) ) {
                $sort_by = get_post_meta( get_the_ID(), 'inspiry_properties_order', true );
            } else {
                $sort_by = get_option( 'theme_listing_default_sort' );
            }
        }
        ?>
        <select name="sort-properties" id="sort-properties">
            <option value="default"><?php _e('Default Order','framework');?></option>
            <option value="price-asc" <?php echo ( $sort_by == 'price-asc' ) ? 'selected' : '' ; ?>><?php _e('Price Low to High','framework');?></option>
            <option value="price-desc" <?php echo ( $sort_by == 'price-desc' ) ? 'selected' : '' ; ?>><?php _e('Price High to Low','framework');?></option>
            <option value="date-asc" <?php echo ( $sort_by == 'date-asc' ) ? 'selected' : '' ; ?>><?php _e('Date Old to New','framework');?></option>
            <option value="date-desc" <?php echo ( $sort_by == 'date-desc' ) ? 'selected' : '' ; ?>><?php _e('Date New to Old','framework');?></option>
        </select>
    </div>

    It looks similar to pre_get_post option you mentioned. Well, you’re right, I am overwhelmed now…

    Moderator bcworkz

    (@bcworkz)

    That code tells us what the sort options are and what happens by default, but not how the sort is actually accomplished. Since this code appears to be from a template, I’m guessing the main internal query is not used for this and that a custom query is made somehow. Thus ‘pre_get_posts’ will not help us if you intend to stick with this custom query approach.

    If you’re going to be editing theme templates, you should create a child theme if possible. Many commercial themes are already installed as a child, you cannot make grandchild themes. Without your own child theme, any template edits you make will be lost when the theme is updated. It’s possible to force themes to use templates provided in a plugin if no child theme option exists, but the code involved does complicate things.

    To do a custom query using the WP_Query class, the basic code is provided as an example in the WP_Query class article I linked to previously. Depending on your specific needs, you build upon that example. You would at least be adding an orderby argument. Complex orderby arguments are done according to the example in the article I linked last on the make.www.remarpro.com site.

    The first thing for you to do is identify the code that actually makes a query for posts, either with query_posts(), get_posts(), new WP_Query() or an actual SQL query. Also identify the code before that that defines the arguments used in the query. Then identify the subsequent code that loops through the query results and outputs the list of posts. Post the code you found (use pastebin.com if the code is extensive) and we can determine how to change the sort order to meet your needs. The other details we can deal with later.

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Sorting Posts by stars rating and custom meta box’ is closed to new replies.