WordPress.org

Ready to get started?Download WordPress

Forums

Attempts to exclude category with pre_get_posts action results in error (2 posts)

  1. eerbes
    Member
    Posted 1 year ago #

    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:

    <?php
    /*
    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:

    <?php
      get_header();
      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. :)

  2. vtxyzzy
    Member
    Posted 1 year ago #

    The 'cat' argument requires category ids, not category names. Replace 'statfactcomic' in the line below with the category id:

    $query->set( 'cat', '-statfactcomic' );

Topic Closed

This topic has been closed to new replies.

About this Topic