custom orderby meta wp_query "fix"
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' );
}
I am a bit skeptical about adding this, why not hook it to the publish post hook instead?
Sorry, I wasn't clear enough. I didn't mean to get this into the plugin. I just posted this here for future reference if anyone had the same problem.
This code is meant to run only once, then delete it. Could be made into a tiny plugin or as a setting in your plugin.
PS: hooking it to the publish post hook doesn't add it to all posts that don't already have a meta_key views.
Arh I see! Cool, let me apply a label to it and keep it open
as I have the same problem, could we run that code during the activation of the plugin and then add the metadata for newer posts in the publish post hook? I'm a Wordpress beginner, but I think we would fix the problem one time for all. I consider this issue a bug, not a feature request. Btw, the code posted in the previous posts doesn't work. These lines
if ( ! get_post_meta( $post->ID, 'views', true ) )
add_post_meta( $post->ID, 'views', 0, true );
should be changed to
if ( ! get_post_meta( $post, 'views', true ) )
add_post_meta( $post, 'views', 0, true );
i create a pull request for that! #39 hope its helpful