• Resolved domy

    (@domy)


    I want to order posts by date and metafield. The problem is, that the meta field holds a date that is used to check if the post is still valid. The desired sorting order would show all valid posts by date descending first and after that all invalid posts sorted by date descending. To archive this, I seem to need to abstract the field value into something like a tinyint.

    Here a quick and simple sql solution for a very simplified posts table, where Im abstracting the validUntil date into a tinyint/bool:

    select id, validUntil, created,
    (
      case
        when validUntil >= now() then 1
        else 0
      end
    )
    as valid
    from example
    order by valid desc, created desc

    and the simplified example table to make it easier to understand what Im talking about:

    CREATE TABLE IF NOT EXISTS <code>example</code> (
      <code>id</code> int(11) NOT NULL AUTO_INCREMENT,
      <code>validUntil</code> datetime DEFAULT NULL,
      <code>post</code> varchar(1024) COLLATE utf8_unicode_ci NOT NULL,
      <code>created</code> datetime DEFAULT NULL,
      PRIMARY KEY (<code>id</code>)
    ) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
    
    INSERT INTO <code>example</code> (<code>id</code>, <code>validUntil</code>, <code>post</code>, <code>created</code>) VALUES
    	(1, '2013-06-18 09:17:07', '', '2013-06-06 09:18:09'),
    	(2, '2013-11-25 09:17:07', '', '2013-11-11 09:16:26'),
    	(3, '2013-12-30 09:17:07', '', '2013-12-12 09:16:26'),
    	(4, '2014-04-18 09:17:07', '', '2014-03-03 09:16:26'),
    	(5, '2014-10-25 09:17:07', '', '2014-06-06 09:16:26'),
    	(6, '2014-10-20 09:17:07', '', '2014-09-09 09:16:26');

    In WordPress itself I want to use the wp_query syntax, to make use of pagintation, something like this:

    $args = array(
                    'post_type' => array('post'),
                    'meta_key' => 'validUntil',
                    'orderby' => array(
                        'meta_value' => 'DESC',
                        'date' => 'DESC'
                    ),
                    'category_name' => 'example',
                    'meta_query' => array(
                        array(
                            'key' => 'validUntil',
                            'value' => $todayDate->format('Y-m-d'),
                            'compare' => '>=',
                        )
                    ),
                    'posts_per_page' => 5,
                    'paged' => $paged,
                );
    
    $query = new WP_Query();
    $query->query($args);

    But I have no idea how to hook into the meta query.
    Or maybe you have a completely different idea?

    Thank you for your time!

Viewing 2 replies - 1 through 2 (of 2 total)
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘How to temporarily change meta field values for wp_query?’ is closed to new replies.