WordPress.org

Forums

[resolved] pre_get_posts Within Template File (3 posts)

  1. Gemfruit
    Member
    Posted 2 years ago #

    I've recently learned that it's much better to use pre_get_posts rather than query_posts. I've noticed that all usage I've found consists of adding a function to functions.php, which requires conditions to not mess up queries around the rest of the website.

    My question is this, is it viable to simply add a function to your template file(s), and use the custom querying there? I have a specific file in mind that I would be editing, where as the rest of the site can remain the same, so it just makes sense to me that I would leave functions.php alone, and add a bit of code to these specific cases. Any thoughts on this are greatly appreciated!

  2. keesiemeijer
    moderator
    Posted 2 years ago #

    You can create a plugin for it. It's not that difficult
    http://codex.wordpress.org/Writing_a_Plugin
    http://wordpress.org/plugins/pluginception/

    Or only include a file with the pre_get_post code in your theme's functions.php.
    http://codex.wordpress.org/Function_Reference/get_template_part

    Even better would be to put it in a child theme's functions.php file.
    http://codex.wordpress.org/Child_Themes

  3. Joan Boluda
    Member
    Posted 1 year ago #

    You must place your function in functions.php (or a plugin). WordPress needs to build the query to figure out what template to load, so if you put this in a template file like category.php it will be too late.

Topic Closed

This topic has been closed to new replies.

About this Topic