Support » Fixing WordPress » Attempts to exclude category with pre_get_posts action results in error

  • First let me mention that I’m new to basic php and this error was a result of my first attempt to install a custom plug-in and insert a do_action command. I’m hoping that the solution will be an easy fix that I overlooked due to my lack of experience.

    I was attempting to exclude the category “statfactcomic” from my home page blog by using the pre_get_posts action documented in the Codex here.

    I pasted the Codex code into a .php file and manually uploaded the plugin into my Plugins WordPress folder. The simple plugin contains the following code:

    Plugin Name: Exclude Comics
    Description: This function excludes webcomics from the WordPress posts loop.
    Author: Eric Erbes
    function exclude_category( $query ) {
        if ( $query->is_home() && $query->is_main_query() ) {
            $query->set( 'cat', '-statfactcomic' );
    add_action( 'pre_get_posts', 'exclude_category' ); 

    I then opened my theme’s (Liquorice version 2.2) index.php added a do_action command to the following location:

      if (have_posts()): ?>
      <ol id="posts">
      	<?php do_action( 'pre_get_posts', 'exclude_category' ); ?>
      	<?php while (have_posts()) : the_post(); ?>
        <li id="post-<?php the_ID(); ?>" <?php post_class('postWrapper'); ?>>

    When I refresh my website I get the following error message where my blog should be:

    Fatal error: Call to a member function is_home() on a non-object

    The error references the line in my custom plugin that contains the code:

    if ( $query->is_home() && $query->is_main_query() ) {

    I’ve spent waaay to much time troubleshooting this problem. Any insight would be much appreciated. 🙂

Viewing 1 replies (of 1 total)
  • The ‘cat’ argument requires category ids, not category names. Replace ‘statfactcomic’ in the line below with the category id:

    $query->set( 'cat', '-statfactcomic' );
Viewing 1 replies (of 1 total)
  • The topic ‘Attempts to exclude category with pre_get_posts action results in error’ is closed to new replies.