Inject Query Posts

plugin banner

Version: 2.0.5

Inject an array of posts into a WP query object as if queried, particularly useful to allow use of standard template tags.

Author:Scott Reilly (profile at wordpress.org)
WordPress version required:3.6
WordPress version tested:6.3
Plugin version:3.0.3
Added to WordPress repository:27-09-2010
Last updated:21-08-2023
Rating, %:0
Rated by:0
Plugin URI:https://coffee2code.com/wp-plugins/inject-que...
Total downloads:4 153
Active installs:10+
plugin download
Click to start download

This plugin provides a function for use by developers who have their own code for fetching posts according to a given criteria and now want to make use of loop-aware template tags to display those posts.

WordPress’s template tags are intended to be used within ‘the loop’. The loop is managed by a WP_Query object which sets up various global variables and its own object variables for use by the various template tags. The primary purpose of a WP_Query object is to actually query the database for the posts that match the currently specified criteria. However, if you don’t need to query for posts since you already have them by some other means, you can still take advantage of the template tags by injecting those posts into the WP_Query via this plugin.

Depending on the template tags you are looking to use, or the logic you are hoping to employ within a loop, you may need to manually configure some of the query object’s variables.

Example:

<?php // Say we're in the sidebar

// We've gotten some post objects on our own.
$posts = c2c_get_random_posts( 5, '' );

// Inject the posts
c2c_inject_query_posts( $posts );

// Now let's display them via template tags:
if ( have_posts() ) :
    while ( have_posts() ) : the_post(); ?>

        <li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></li>

    <?php endwhile;?>
<?php endif; ?>

Links: Plugin Homepage | Plugin Directory Page | GitHub | Author Homepage

Developer Documentation

Developer documentation can be found in DEVELOPER-DOCS.md. That documentation covers the template tag and hooks provided by the plugin.

As an overview, this is the template tag provided by the plugin:

  • c2c_inject_query_posts() : Template tag to inject an array of posts into a query object as if that query object had obtained those posts via a query.

Theses are the hooks provided by the plugin:

  • inject_query_posts_preserve_query_obj : Overrides the value of the $preserve_query_obj argument passed to the function. This is not typical usage for most users.
  • c2c_inject_query_posts : Allows use of an alternative approach to safely invoke c2c_inject_query_posts() in such a way that if the plugin were deactivated or deleted, then your calls to the function won’t cause errors in your site.

ChangeLog