Support

Account

Home Forums Search Search Results for 'pre_get_posts'

Search Results for 'pre_get_posts'

reply

  • when I checked my code it was not working although I was sure it had been before!!!

    Anyhow with a combination of things this is definitely working on my site now, you need the filters to modify the numbers of posts shown at the top of the list of posts screen.

    function listings_for_current_author($query) {
    	
    	if( !$query->is_admin )
    		return $query;
    		
    	if( isset($query->query_vars['post_type']) &&  $query->query_vars['post_type'] == 'acf' )
    {
    	return $query;
    }
    		
    	
    	if( !current_user_can( 'moderate_comments' ) ) {
    		global $user_ID;
    		$query->set('author', $user_ID );
    		add_filter('views_edit-site_listings', 'fix_listing_counts');
                    add_filter('views_upload', 'fix_listing_media_counts');
    	}
    	return $query;
    }
    
    add_action('pre_get_posts', 'listings_for_current_author');
    
    // Fix post counts
    function fix_listing_counts($views) {
        global $current_user, $wp_query;
    	/*
    	unset($views['all']);
                unset($views['publish']);
                unset($views['trash']);
    	*/
    	
    	
        unset($views['mine']);
        $types = array(
            array( 'status' =>  NULL ),
            array( 'status' => 'publish' ),
            array( 'status' => 'draft' ),
            array( 'status' => 'pending' ),
            array( 'status' => 'trash' )
        );
        foreach( $types as $type ) {
            $query = array(
                'author'      => $current_user->ID,
                //'post_type'   => 'post',
    			'post_type'   => 'site_listings',
                'post_status' => $type['status']
            );
            $result = new WP_Query($query);
            if( $type['status'] == NULL ):
                $class = ($wp_query->query_vars['post_status'] == NULL) ? ' class="current"' : '';
                $views['all'] = sprintf(__('<a href="%s"'. $class .'>All <span class="count">(%d)</span></a>', 'all'),
                    admin_url('edit.php?post_type=site_listings'),
                    $result->found_posts);
            elseif( $type['status'] == 'publish' ):
                $class = ($wp_query->query_vars['post_status'] == 'publish') ? ' class="current"' : '';
                $views['publish'] = sprintf(__('<a href="%s"'. $class .'>Published <span class="count">(%d)</span></a>', 'publish'),
                    admin_url('edit.php?post_status=publish&post_type=site_listings'),
                    $result->found_posts);
            elseif( $type['status'] == 'draft' ):
                $class = ($wp_query->query_vars['post_status'] == 'draft') ? ' class="current"' : '';
                $views['draft'] = sprintf(__('<a href="%s"'. $class .'>Draft'. ((sizeof($result->posts) > 1) ? "s" : "") .' <span class="count">(%d)</span></a>', 'draft'),
                    admin_url('edit.php?post_status=draft&post_type=site_listings'),
                    $result->found_posts);
            elseif( $type['status'] == 'pending' ):
                $class = ($wp_query->query_vars['post_status'] == 'pending') ? ' class="current"' : '';
                $views['pending'] = sprintf(__('<a href="%s"'. $class .'>Pending <span class="count">(%d)</span></a>', 'pending'),
                    admin_url('edit.php?post_status=pending&post_type=site_listings'),
                    $result->found_posts);
            elseif( $type['status'] == 'trash' ):
                $class = ($wp_query->query_vars['post_status'] == 'trash') ? ' class="current"' : '';
                $views['trash'] = sprintf(__('<a href="%s"'. $class .'>Trash <span class="count">(%d)</span></a>', 'trash'),
                    admin_url('edit.php?post_status=trash&post_type=site_listings'),
                    $result->found_posts);
            endif;
        }
    	
        return $views;
    }
    
    // Fix media counts
    function fix_listing_media_counts($views) {
        global $wpdb, $current_user, $post_mime_types, $avail_post_mime_types;
        $views = array();
        $_num_posts = array();
        $count = $wpdb->get_results( "
            SELECT post_mime_type, COUNT( * ) AS num_posts 
            FROM $wpdb->posts 
            WHERE post_type = 'attachment' 
            AND post_author = $current_user->ID 
            AND post_status != 'trash' 
            GROUP BY post_mime_type
        ", ARRAY_A );
        foreach( $count as $row )
            $_num_posts[$row['post_mime_type']] = $row['num_posts'];
        $_total_posts = array_sum($_num_posts);
        $detached = isset( $_REQUEST['detached'] ) || isset( $_REQUEST['find_detached'] );
        if ( !isset( $total_orphans ) )
            $total_orphans = $wpdb->get_var("
                SELECT COUNT( * ) 
                FROM $wpdb->posts 
                WHERE post_type = 'attachment' 
                AND post_author = $current_user->ID 
                AND post_status != 'trash' 
                AND post_parent < 1
            ");
        $matches = wp_match_mime_types(array_keys($post_mime_types), array_keys($_num_posts));
        foreach ( $matches as $type => $reals )
            foreach ( $reals as $real )
                $num_posts[$type] = ( isset( $num_posts[$type] ) ) ? $num_posts[$type] + $_num_posts[$real] : $_num_posts[$real];
        $class = ( empty($_GET['post_mime_type']) && !$detached && !isset($_GET['status']) ) ? ' class="current"' : '';
        $views['all'] = "<a href='upload.php'$class>" . sprintf( __('All <span class="count">(%s)</span>', 'uploaded files' ), number_format_i18n( $_total_posts )) . '</a>';
        foreach ( $post_mime_types as $mime_type => $label ) {
            $class = '';
            if ( !wp_match_mime_types($mime_type, $avail_post_mime_types) )
                continue;
            if ( !empty($_GET['post_mime_type']) && wp_match_mime_types($mime_type, $_GET['post_mime_type']) )
                $class = ' class="current"';
            if ( !empty( $num_posts[$mime_type] ) )
                $views[$mime_type] = "<a href='upload.php?post_mime_type=$mime_type'$class>" . sprintf( translate_nooped_plural( $label[2], $num_posts[$mime_type] ), $num_posts[$mime_type] ) . '</a>';
        }
        $views['detached'] = '<a href="upload.php?detached=1"' . ( $detached ? ' class="current"' : '' ) . '>' . sprintf( __( 'Unattached <span class="count">(%s)</span>', 'detached files' ), $total_orphans ) . '</a>';
        return $views;
    }
    
  • Hi @rainstorminc

    Because your case is quite specific, I would encourage you to add a filter to the pre_get_posts and edit the ‘wrong’ settings that the events post type plugin is adding.

    I would rather not bloat the core and add potential issues for other users if possible.

    Thanks for understanding and thanks for the bug report.

    Cheers
    E

  • Hi Elliot,

    Thanks for the response!

    Yes, I agree — it’s perfectly reasonable to suspect that post__in would be enough. The conflict occurs with another plugin that handles Event custom post types.

    This events plugin uses the “pre_get_posts” method. During the process of using this method, the plugin will end up adding a tiny piece to the query if it has to do with a post_type that the plugin is responsible for. Ie, your query says “Give me all post types” and then the event plugin says “hey, that query has to do with events — so add on this event-related piece”. The end result is that the query doesn’t return anything because the event piece isn’t appropriate to be added in this case since it’s not really about events.

    I’ll be the first to admit that there’s probably something that could change in the event plugin to avoid this issue. Having said that, my guess is that ACF is more widely supported than the other and therefore, more likely to be updated. Plus, I figured the update actually made sense anyway to restrict the results to certain post_types. Especially, since it was already filtering to certain post_types anyway, it just wasn’t being that specific.

    What do you think?

  • Hi @homax

    So, if you were to now remove the above code, your archive page will load as expected?

    I think there is something fishy going on in your theme in regards to the wp posts loop.

    Perhaps you have a pre_get_posts filter or one of the many other filters in WP / ACF which is modifying the $query.

    It is very easy to accidentally break the global $query in WP and I believe this is what is happening to you.

    Maybe in your code, you are hooking in somewhere and performing a new WP_Query object? If so, make sure you are resetting the query afterwards.

    It may be beneficial to create a new WP install on your local server and just install ACF. Create the same field and edit the twenty12 theme to use this $posts loop. It should work and hopefully give you an idea of where the issue must stem from.

  • Woops – I checked the “this solved it”-button, but I’m still struggling with it.

    I’m not much of a coder, but I tried various ways of coding and thus far without luck.

    Right now I’ve changed it to

    function posts_for_current_author($query) {
    global $user_level;
    
    if($query->is_admin && $user_level < 5 && get_post_type() != "acf") {	
    	
    		global $user_ID;
    		$query->set('author', $user_ID);
    		
    		unset($user_ID);
    	}
    unset($user_level);
    
    return $query;
    }
    
    add_filter('pre_get_posts', 'posts_for_current_author');
    

    But unfortunately that doesn’t change a thing.. Any thoughts?

  • I don’t usually work custom fields into admin hooks very often, so I would imagine that this is only happening to get_field() calls that exist in admin-side hooks (pre_get_posts for an example). Also not really familiar with how the plugin update process works, but I do know that the plugin folder is cleaned out and the new plugin is extracted, so the errors are probably firing somewhere between those two events.

    Solution? No idea. Maybe just do your function_exists checks on the hooks and filters that apply to admin-side functions…

  • You’re looking at doing some custom wp_query filtering! Check out the Custom Field Parameters, this will give you a rundown on how to implement.

    I don’t have quite enough time to look into pulling in GET parameters, but here’s a sample of custom field filtering that I have open in front of me. The first one does actually look at the URL for variables, but probably not the proper WP way.

    Use an action hook, make sure that you have your URL variable and the right post type, then apply your field filters:

    
    add_action('pre_get_posts', 'wpse71814_filter_search');
    function wpse71814_filter_search( $query ){
    
         if( isset($_REQUEST['search']) && ($query->query_vars['post_type'] == 'properties') ){
    
             //Collect user input from $_GET for example
            // Protect yourself!
            foreach($_REQUEST as &$get){ $get = mysql_real_escape_string($get); }
            $meta_query = $query->get('meta_query');
    
            $meta_query[] = array(
                'key'       => 'price',
                'value'     => array($_REQUEST['price_min'], $_REQUEST['price_max']),
                'type'      => 'NUMERIC',
                'compare'   => 'BETWEEN'
            );
    
            if($_REQUEST['location'] != 'any'){
                $meta_query[] = array(
                    'key'       => 'district-rel',
                    'value'     => serialize(array(0=>$_REQUEST['location'])),
                    'compare'   => 'LIKE'
                );
            }
            $query->set('meta_query',$meta_query);
    
        } // if isset
    
        return $query;
    }
    

    For this example, I’m filtering post type “properties” and doing 2 meta queries: firstly inside a price range (price_min and price_max), and secondly if a location variable has been provided I am filtering on a district_rel custom post relation field.

    Let me know if you want a hand adapting this for your date field 😉

  • A quick snippet for you:

    add_action( 'pre_get_posts', 'filtre');
    function filtre($query) {
       //echo '<pre>'.print_r($query->query_vars['post_type'], true).'</pre>';
    
        switch($query->query_vars['post_type']){
    
            
            case 'attachment':  // Media library
                if( current_user_can('manage_own_media') ) $query->set('author', get_current_user_id() );
                break;
            
            case 'post':        // Posts
                if( current_user_can('manage_own_posts') ) $query->set('author', get_current_user_id() );
                break;
    
            case 'page':        // Pages
                if( current_user_can('manage_own_pages') ) $query->set('author', get_current_user_id() );
                break; 
                
       } // switch post_type
        
        return $query;
    }

    Of course this is assuming that there are custom permissions set up using the User Role Editor!

  • Yes, this works for me. The cache made me crazy!

    
    add_action( 'pre_get_posts', 'filtre');
    function filtre($query) {
    	global $user_ID;
    	//global $current_user;
    	if( !is_admin() ) {
    		$query->set('author',  $user_ID);
    		//$query->set('author',$current_user->id);
    	}
    	
    	return $query;
    }
    

    Now I’m gonna try to filter the media, taxonomies and ACF. Will see if there’s a problems!

  • Hi,
    not working. 🙁
    Scenario:
    I have 2 users (user1,user2), Rol Author.
    The user1 has created a CPT restaurant called rest1, and when I log into a Backend with user2 I can edit rest1. :S
    I’ve tried all the combinations:

    
    add_action( 'pre_get_posts', 'filtre');
    function filtre($query) {
    	 //tried option 0
            //global $user_ID;
     	//tried option 1
            //global $current_user;
     	if( !is_admin() ) {
                    $query->set('author', get_current_user_id());
    		 //tried option 0
                    //$query->set('author',  $user_ID);
     		 //tried option 1
                    //$query->set('author',$current_user->id);
                    //tried option 2
                    //$user = wp_get_current_user();
                    //$query->set('author_name', $user->data->user_nicename );
    	}
    	
    	return $query;
    }
    

    I don’t know whatelse.
    Help please!
    Thanks!

  • Aha, well in that case you were totally on the right path!

    Filtering by “author” takes a user ID, while filtering by “author_name” will take a text string. Try this:

    add_action( 'pre_get_posts', 'filtre');
    function filtre($query) {
    
    	if( !is_admin() ) {
    		$query->set('author', get_current_user_id() );
     	}
    	return $query;
    }

    Or alternatively, you could get the string name first and filter by “author_name” instead:

        $user = wp_get_current_user();
        $query->set('author_name', $user->data->user_nicename );
    
Viewing 11 results - 351 through 361 (of 361 total)