Skip to content

custom orderby meta wp_query "fix" #3

Description

I post this here because I had issues with a custom loop ordered by views. It didn't show posts that didn't have the views meta_key.

Run this once in your functions.php and remove after.. or let it sit there but there really is no need for it.

This code adds a meta_key views if the post doesn't have one and fills the value with a 0.

add_action( 'init', 'post_views_default' );

function post_views_default() {

    if ( get_option( 'post_views_setup_has_run' ) )
        return;

    $args = array(
        'posts_per_page' => -1,
        'fields' => 'ids',
        'post_type' => array( 'post', 'page' )
    );
    $viewsToZero = new WP_Query( $args );

    foreach ( $viewsToZero->posts as $post ){

        if ( ! get_post_meta( $post->ID, 'views', true ) )
            add_post_meta( $post->ID, 'views', 0, true );
    }

    add_option( 'post_views_setup_has_run', 'yes', $deprecated = '', $autoload = 'yes' );
}

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions