6

Is there a way to limit the following code that I've added to my functions.php file so that it only applies to a single wordpress category?

<?php remove_filter('the_content', 'wpautop'); ?>

I tried this, but it didn't seem to work:

<?php if (in_category('work')) { remove_filter('the_content', 'wpautop'); } ?>

I should also add that I solved this problem by placing the code directly in the specific category template, but I'd prefer to keep the filter in my functions file.

Thanks!

2
  • 1
    I think you would need to add it to single.php instead of category template. Best way would be to add it to your header file so that it applies to all pages. I don't know why it doesn't work in functions.php
    – Tarun
    Jul 18, 2011 at 4:29
  • where r u triggering this? after init or before?
    – Tarun
    Jul 18, 2011 at 4:29

2 Answers 2

1

I believe you will want to hook into the pre_get_posts action. It fires right after the query string is parsed. Some but not all of the conditionals are set up. You can test if in_category() is one of them, but I don't think it matters. Why? Glad you asked.

The hook is going to pass you the query object, which has the property category_name. All you have to do is check if it has your category and if so fire your filter. Something like this:

function ns_function_name($wpq){
    if($wpq->category_name == 'work'){
        remove_filter('the_content', 'wpautop');
    }
}
add_action( 'pre_get_posts', 'ns_function_name' );

This is totally untested. But since you seem to know what you are doing, it should be enough to put you on the right path.

2
  • Your code have a bug "Notice: Undefined property: WP_Query::$category_name " Apr 8, 2014 at 14:49
  • The answer is more of an illustration of the pattern OP should use to accomplish his task. I did note that it is untested, and clearly other checks should first be made, such as is_set(). Without seeing your code, I can't really know what you are doing right or wrong. You might try creating a new question if you are having trouble with it. Also, according to WP docs, "pre_get_posts runs before WP_Query has been setup".
    – undefined
    Apr 9, 2014 at 15:43
0

Your functions.php is not aware of the current request like your index and category pages are. To make this code work in functions.php, you'll have to grab the raw server vars and parse through them to load up wp_query functionality that is relevant to the current url:

$url = explode('?', 'http://'.$_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
$ID = url_to_postid($url[0]);

Once you have that ID you can do a query loop and trigger your filter based on the category.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.