Applying code in Wordpress functions.php to only one category

Is there a way to limit the following code that I added to my functions.php file so that it applies to only one 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 a template of a certain category, but I would prefer to keep the filter in my function file.

Thanks!

+6
source share
2 answers

I think you will want to connect to the pre_get_posts action . It starts immediately after parsing the query string. Some, but not all, conventions are established. You can check if in_category () is one of them, but I don't think that matters. What for? Glad you asked.

The hook will give you a query object that has a category_name property. All you have to do is check if it has its own category, and if so, run the filter. Something like that:

 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 completely untested. But since you seem to know what you are doing, this should be enough to put you on the right track.

+1
source

Your .php functions are not aware of the current request, for example, your index and category pages. In order for this code to work in functions.php, you will need to grab the raw server vars and analyze them in order to load the 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 this identifier, you can make a request loop and run a filter by category.

0
source

Source: https://habr.com/ru/post/892964/


All Articles