WordPress.org

Ready to get started?Download WordPress

Forums

[resolved] [Plugin: Select posts with custom date field smaller than date('ymd')] (2 posts)

  1. kramer65
    Member
    Posted 1 year ago #

    Hello,

    I wrote a simple plugin which shows posts on the frontpage on the basis of whether a custom field (called 'featured') is ether 1 or 0. I now want to take this one step further by creating a date field which the author can fill in. In the query on the frontpage I now want to display the post when the field 'featureddate' is filled in and check whether that date lies in the past (AKA: not display it when the date is in the future).

    So I wrote the following:

    <?
    function only_featured( $query ) {
        if ( $query->is_home() && $query->is_main_query() ) {
    //        $query->set('meta_key', 'featured');
    //        $query->set('meta_value', '1');
    	$query->set('meta_key', 'featureddatum');
            $query->set('meta_compare', '<=');
            $query->set('meta_value', date('ymd'));
        }
    }
    add_action( 'pre_get_posts', 'only_featured' );
    ?>

    The commented out code is what I used before. I now check whether the field 'featureddate' actually exists and whether it is smaller than the actual date at this time. This however doesn't work, since it doesn't display anything, whether the featureddate is before or after today.

    I searched around for a solution, but can't find anything on the topic. Does anybody have an intelligent idea?

    All tips are welcome!

  2. kramer65
    Member
    Posted 1 year ago #

    Excuse me! The mistake was in the date('ymd'), which should have been date('Ymd').

    So the final solution (including sorting on the featureddate) is as follows:

    <?
    function alleen_featured( $query ) {
        if ( $query->is_home() && $query->is_main_query() ) {
    	$query->set('meta_key', 'featureddatum');
            $query->set('meta_compare', '<=');
            $query->set('meta_value', date('Ymd'));
            $query->set('orderby', 'featureddatum');
            $query->set('order', 'DESC');
        }
    }
    add_action( 'pre_get_posts', 'alleen_featured' );
    ?>

    Thanks anyway for reading!

Topic Closed

This topic has been closed to new replies.

About this Topic