Support » Plugins » Hacks » problems with WP_Query and my plugin

  • Resolved CygnusH33L


    I have just started trying my hand at coding a WordPress plugin, I would like the plugin to hide posts in the category private from non-logged in users.

    I know the issue is with WP_Query and I have tried query_posts also, both with no luck. I’m sure i’m just making a noobie mistake but would appriciate a push in the right direction.

    This is what I have so far;

    /* to avoid name collisions check this function is not already defined. */
    if (!function_exists("post_restrictor")) {
    	/* Start of post restrictor function */
    	function post_restrictor($content) {
    	/* Get category ID for private */
    	$cate = get_cat_id('private');
    	/* retrieve posts without including the 'private' category. */
    	global $contentResult;
    	$contentResult = new WP_Query("cat=-$cate");
    		/* loop current posts */
    		if ( have_posts() ) : while ( have_posts() ) : the_post();
    			/* check if post is in category private */
    			if(in_category('private')) {
    				/* check if user is logged in */
    				if(is_user_logged_in()) {
    					return $content;
    				} else { // if user is not logged in return modified result.
    					return $contentResult;
    	} // end post_restrictor function
    	/* add our filter function to the hook */
    	add_filter('the_content', 'post_restrictor');
    } // end name collision check

    forgive me if i’m way of track 😛

    This is my first attempt at a WordPress plugin so I really want to finish it.

    Thanks for any help you can give 🙂

Viewing 2 replies - 1 through 2 (of 2 total)
  • It appears as though you want to alter the content only if you are on a post in the ‘private’ category and the user is not logged in. Here is what I would recommend:

    add_action( 'init', 'my_init' );
    function my_init() {
        if( in_category( 'private' ) && ! is_user_logged_in() ) {
            add_filter( 'the_content', 'post_restrictor' );
    function post_restrictor( $content ) {
        $content = "Sorry, you don't have access to this post.  Please login.";
        return $content;

    Thanks for the reply Micah, I have tried what you suggested but was unable to get it working.
    I have however managed to resolve it, this is how

    function exclude_category($query) {
    	if(!is_user_logged_in()) {
    		if ($query->is_main_query()) {
    			$cate = get_cat_id('private');
            		$query->set( 'cat', '-'.$cate );
    add_action( 'pre_get_posts', 'exclude_category' );

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘problems with WP_Query and my plugin’ is closed to new replies.