The Better Way to Query Posts, Woo Products, and CPT Items in WordPress

WordPress is an extremely adaptable platform and one of the key aspects that allows for this versatility is the WP_Query class. This class enables developers to obtain material from the database in a very customized manner, allowing them to display posts, pages, WooCommerce products, and custom post types (CPT) in almost any configuration. However, depending only on WP_Query might provide certain issues, especially as your site’s complexity increases. In this post, we’ll look at the disadvantages of using WP_Query directly and propose an improved way to handle queries with the Advanced Views Framework.

Drawbacks of Straight WP_Query Usage

WP_Query is powerful, providing fine-grained control over how content is obtained from the database. However, direct consumption has certain important drawbacks:

Steep learning curve

WP_Query requires a thorough understanding of WordPress’ query system and PHP, which makes it difficult for beginners and anyone inexperienced with WordPress development. The need to comprehend multiple arguments and their proper application can be a substantial barrier to entrance, especially when dealing with difficult questions.

Error-Prone

Manually constructing queries with WP_Query can introduce significant risks, especially in complex environments. You need to be meticulous with argument structures and syntax, as even minor mistakes can lead to unexpected results, visible bugs, or, in the worst case, completely break your site.

Time-Consuming

Building custom queries using WP_Query from scratch is time-consuming. This simply means that the bigger and more complex the site is, the greater the time it takes to create, test, and debug the queries. Not only does this slow down development, but it also makes your codebase harder to maintain.

WordPress does not structure these queries for you or manage how the display templates go with them. Most often, developers end up with one overly bloated functions.php file or scattered pieces of code throughout the theme, making the code base difficult to manage and inefficient.

Enhanced Database Queries using the Advanced Views Framework

The Advanced Views Framework is a powerful tool that transforms the way you manage database queries and shows content in WordPress. Unlike the traditional way of handling WP_Query posts, the framework has smart templates that make post-queries easier and ultimately lead to streamlined template creation—an obvious must-have for all developers.

The Advanced Views Framework is intended to improve and personalize content display and functionality. It offers a modern, simple, yet versatile method for achieving high-quality outcomes without the traditional time-consuming stages. This framework provides a strong foundation that considerably decreases the time necessary for project implementation while avoiding the common problems of page builders.

To discover more about how the Advanced Views Framework can improve your WordPress development, watch this AVF overview video. You can also dig deeper into its core features in the official documentation.

Benefits of Using Advanced Views Framework over WP_Query

Simplifies Query Building

The Advanced Views Framework (AVF) eliminates the need to memorize specific argument names like meta_query, tax_query, and others. With AVF, you can effortlessly create complex queries through a user-friendly interface, reducing errors and streamlining development.

Reusable Components

AVF is built with a modular design, allowing you to create queries using existing “Cards” or elements that can be reused across different parts of your site. This promotes consistency and minimizes duplication, making updates and adjustments much easier to manage.

Low Learning Curve

The visual interface of AVF significantly reduces the learning curve, making it accessible to developers of all experience levels. Even a relatively inexperienced WordPress developer can quickly become proficient with AVF.

Full Control Over Layout and Markup

Beyond simplifying query construction, AVF gives you complete control over the HTML markup and layout of the retrieved content. This ensures that you can display content exactly as envisioned, without being constrained by predefined templates.

Mastery Over WP_Query Arguments

While AVF simplifies the query process, it doesn’t compromise on power. It allows users to leverage the full capabilities of WP_Query, passing any argument necessary to build precise queries, filter results optimally, and enhance performance—all through an intuitive frontend interface.

Besides the Lite edition, the Advanced Views Framework is also available in the Pro edition, which brings a row of additional integrations to streamline complex tasks. 

How to create queries using AVF

Creating a query with the Advanced Views Framework (AVF) requires several steps to guarantee that your WordPress site displays the appropriate posts or Custom Post Type (CPT) items based on your requirements. Here’s a step-by-step guide for creating a query using AVF by configuring a Card.

Step 1: Create a new card.

  • Visit the Advanced Views Framework Tab.

In the WordPress backend, go to the “Advanced Views Framework” tab. This is where you’ll organize and create your views and cards.

  • Switch to the Cards Tab:

Once on the AVF tab, navigate to the “Cards” tab. This is where you’ll design a new card to showcase your posts or CPT goods.

  • Add a new card.

To create a new card, click the “Add New” button. This Card will serve as a container for showing your posts according to the query you specify.

  • Enter a name for your card.

Enter a name for your Card. Naming your Card is vital because you will be unable to publish it without one. The publish button will be disabled until a name is entered.

Step 2: Assign a View

Select Your View:

In the “View” dropdown, select the View you previously created. This View will be assigned to your Card, and the posts displayed will be based on this View.

Select the Source:

Choose the source for your posts:

  • Posts Query (WP_Query): This option fetches posts based on a custom query you define.
  • Page Context (Archive Pages): This option fetches posts from the context in which the Card is inserted, such as an archive, author, or category page.

Choose the Post Type:

  • In the “Post Type” dropdown, select the type of post or CPT items you want to filter. This allows you to narrow down the posts displayed to a specific post type.

Step 3: Filter and Sort Your Posts

Select Post Status:

  • In the “Post Status” dropdown, choose one or more statuses from the list (e.g., Published, Draft). This filter ensures that only posts with the selected statuses are displayed.

Limit the Number of Posts:

  • Use the “Maximum number of posts” field to set a limit on how many posts are displayed. This is particularly useful for controlling the amount of content shown on a page.

Sort the Posts:

  • In the “Sort by” dropdown, choose how you want to sort the posts. By default, you can sort by “Date.” If you have the Pro version, you can sort by a Meta field, Then, choose the “Sort order” by selecting either “Ascending” or “Descending.”

Step 4: Configure Advanced Settings

  • Switch to the Advanced Tab:

Navigate to the “Advanced” tab to access more detailed settings for your Card.

Add a Description

  • Provide a description for your Card. This description will only be visible on the Cards list in the backend and is useful for identifying the purpose of the Card.

Set a ‘No Posts Found’ Message:

  • If needed, fill out the “No Posts Found Message” field. This message will be displayed if the query returns no posts.

Select a Pool of Posts:

  • In the “Pool of posts” dropdown, you can manually select specific posts to include in your Card. Be aware that if you select posts here, only these posts will be displayed.
  • Warning: Avoid using the “Exclude posts” feature together with the “Pool of posts” option, as this can cause conflicts in your query.

Exclude Specific Posts:

  • If necessary, manually exclude specific posts from being displayed in your Card using the “Exclude posts” option.

Step 5: Adjust the Template Engine (Optional)

Change the Template Engine:

  • If desired, you can change the template engine from Twig to Blade. This option requires PHP 8.2, and it’s only necessary if you prefer Blade for templating.

Step 6: Publish Your Card

  • After configuring all settings, click on the “Publish” button to save and make your Card live.

Step 7: Embed the Card on Your Site

Copy the Shortcode:

  • Once your Card is published, copy the shortcode from the sidebar. This shortcode will be used to display the content generated by your Card.

Paste the Shortcode:

  • Paste the shortcode into the desired location on your page, post, or theme section where you want the posts to appear.

By following these steps, you’ll have successfully created a query using AVF, and your posts or CPT items will be displayed according to the criteria you defined.

Use Cases

Displaying the Latest WooCommerce Products

Showcasing the most recent products is crucial for promoting new inventory. With AVF, you can easily set up a query to display the latest products added to your WooCommerce store, ensuring that this section remains automatically updated.

How-to:

Use the Advanced Views Framework to target the ‘product’ post type and order by the ‘post_date’ field in descending order. Limit the results to the latest 10 products to ensure that only the newest items are displayed.

Displaying Posts Within a Specific Category

Creating focused sections or archives based on specific categories can help users find relevant content more easily. AVF simplifies this process by allowing you to filter and sort posts by category.

How-to:

Configure the Advanced Views Framework to query the ‘post’ post type with a filter applied to the ‘category’ taxonomy. Specify the desired category and sort by date or relevance to ensure that the most pertinent posts are displayed.

Querying Custom Post Type Items by Meta Field

Targeting custom post types based on specific meta fields allows for highly tailored content presentation. AVF enables you to set up complex queries with ease.

How-to:

Create a query targeting the custom post type of interest, applying a meta query filter to retrieve items based on specific meta field values. This can be particularly useful for displaying upcoming events, products with specific attributes, etc.

Creating Dynamic Product Lists Based on User Preferences

Offering personalized product recommendations based on user activity can significantly enhance the shopping experience. AVF makes it possible to generate dynamic product lists that adapt to user-selected criteria.

How-to:

Build a dynamic query with AVF that updates in real-time based on user input. Integrate filters for attributes like size, color, or price range to display products that match user preferences.

Building a Testimonials Section with Randomized Entries

Rotating customer testimonials can keep the content fresh and engaging. With AVF, you can easily set up a query that randomizes and rotates testimonial entries.

How-to:

Configure AVF to query testimonial entries, applying a random sorting method to ensure a diverse display each time the page is loaded.

Aggregating Recent Blog Posts from Multiple Authors

Displaying recent posts from multiple authors can provide a more comprehensive view of content. AVF makes it easy to aggregate and present this information.

How-to:

Set up a query targeting the ‘post’ post type, filtered by multiple authors. Sort by the most recent posts to ensure a well-rounded display of content.

Displaying Event Listings Based on Custom Taxonomies

Categorizing events by custom taxonomies like ‘event_type’ or ‘location’ allows for better content organization. AVF supports this kind of specialized query.

How-to:

Create a query that targets the ‘event’ custom post type, applying filters based on custom taxonomies to display events by specific categories.

Showing Related Products Based on User Activity

Enhance the shopping experience by displaying related products based on user activity or preferences. AVF can facilitate the creation of complex, dynamic queries to achieve this.

How-to:

Leverage AVF’s capabilities to track user interactions and display related products dynamically. Filter products by attributes or previous purchases to provide highly relevant recommendations.

List of Supported meta fields

The Advanced Views Framework (AVF) provides extensive support for a variety of field types across several meta-field plugins, enabling seamless integration and advanced content management.

1. Advanced Custom Fields

Advanced Custom Fields pluginsupports 36 sorts of fields, which include text, textarea, numbers, ranges, emails, URLs, and passwords.

  • Content Types: Image, File, WYSIWYG, oEmbed, Gallery.

Options include Select, Checkbox, Radio, Button Group, and True/False.

  • Relational Groups include Link, Post Object, Page Link, Relationship, Taxonomy, and User.
  • Advanced Group includes Google Map, Google Map Multiple Markers, OpenStreetMap, Date Picker, Date-Time Picker, Time Picker, Color Picker, and Icon Picker.
  • Layout Group: Repeater, Group, Flexible, Clone, and Tab (only in Pro Edition).

2. Meta Box

The Meta Box plugin supports 43 field types:

  • Basic Group: Checkbox, Checkbox List, Radio, Select, Text, and Textarea.
  • Advanced Group includes Autocomplete, Background, Button Group, Color, Date, Datetime, Map, Hidden, Icon, Image Select, oEmbed, OSM, Password, Select Advanced, Slider, Switch, Time, and WYSIWYG.
  • HTML5 categories include email, number, range, select, WordPress, post, sidebar, taxonomy, taxonomy advanced, and user.
  • Upload Types: File, File Advanced, File Input, File Upload, Image, Image Advanced, Image Upload, Single Image, and Video.
  • Layout Group: (Pro Edition only).

3. Pods

From the Pods plugin, 18 field types are supported: Plain text, website, phone number, email, and password.

  • Plain paragraph text, WYSIWYG (Visual Editor), and syntax highlighting.
  • Date/Time Categories include Date/Time, Date, and Time.
  • Number Types: Plain Numbers, Currency.
  • Relationship/Media Group: File/Image/Video, oEmbed, Relationship (with limitations).

Conclusion

WP_Query is an essential component of WordPress, but its complexities can be intimidating, particularly for large or elaborate projects. The Advanced Views Framework provides a strong alternative by simplifying the query process, improving maintainability, and offering extensive customization options.

Whether you’re a seasoned developer or new to WordPress, AVF can help you create more efficient and dynamic websites with fewer steps. By introducing AVF into your workflow, you not only speed up the query-building process but also open up a plethora of options for presenting and managing content on your WordPress website

Leave a Reply