This tutorial shows two different methods for running advanced WordPress Queries when using Oxygen.
Method 1: Using Advanced WP Query option of Easy Posts / Repeater
Beginning from v3.8 Alpha 1, Oxygen comes with advanced option in the WP Query settings of Easy Posts and Repeater components. This allows us to build complex queries without writing code (to a large extent).
For example, let’s show the list of posts by the currently logged-in user on a static Page using Easy Posts.
Add an Easy Posts component > Query > advanced.
Select the closest from the available presets and edit the query or start from scratch.
In this case let’s select the last one, “Posts by author of current post or archive” and click Edit Query.
The value of the author parameter with this preset is the current post’s author ID which is not what we want. We need the value to be the currently logged-in user’s ID instead.
So click on data button for the author’s value input, then PHP Function Return value.
Function Name: get_current_user_id
Click INSERT.
Once done, Oxygen should generate this shortcode:
[oxygen data="phpfunction" function="get_current_user_id"]
Next add another parameter for setting post_type
to post
.
Check the front end and you should only see the posts that have been published by you.
In a practical scenario, you would want to set this to be output only if the user is logged in and show a heading/text that reads something like
You need to be <a href="/wp-login.php/">logged in</a> to view your posts.
with a condition set to be output only if the user is not logged in.
Method 2: Using pre_get_posts
For developers that want full freedom or prefer hand-coding the WP query parameters, there is the pre_get_posts
method originally shared by Yan Kiara.
Continuing with the earlier example of listing posts by the currently logged-in user on a static Page using Easy Posts, this is how you would do it:
Add an Easy Posts component and set the query to either custom or manual depending on whether you want to show the pagination or not respectively. Select post
post type.
Remember that to not show pagination you need to append &no_found_rows=true
in the manual query string. Reference.
Add a Code Block above the Easy Posts having this code:
<?php
add_action( 'pre_get_posts', 'wpdd_published_by_current_user' );
function wpdd_published_by_current_user( $query ) {
// remove the filter; the query is done.
remove_action( 'pre_get_posts', 'wpdd_published_by_current_user' );
$query->set( 'author', get_current_user_id() );
}
?>
Tip: When writing queries by hand, this is must-have reference.
Check the front end and you should only see the posts that have been published by you (the currently logged-in user).