Last active
May 30, 2024 09:18
-
-
Save raftaar1191/c2e3870ea741263fa2f2859f187302c1 to your computer and use it in GitHub Desktop.
Get Draft post for non login user as well via WP REST API
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* Filter to alter the rest_query args to add draft and filter | |
* | |
* @param array $args Array of arguments for WP_Query. | |
* @param WP_REST_Request $request The REST API request. | |
* | |
* @return array $args Array of arguments for WP_Query. | |
*/ | |
function lubus_custom_allow_drafts_in_rest_query( $args, $request ) { | |
if ( ! is_user_logged_in() ) { | |
if ( isset( $request['slug'] ) ) { | |
$args['post_status'] = array( 'publish', 'draft' ); | |
add_filter( 'the_posts', 'lubus_update_post_status_in_query_result', 10001, 2 ); | |
add_filter( 'the_posts', 'lubus_remove_update_post_status_in_query_result', 10002 ); | |
} | |
} | |
return $args; | |
} | |
add_filter( 'rest_testimonial_query', 'lubus_custom_allow_drafts_in_rest_query', 10, 2 ); | |
/** | |
* Filter to update the post status from draft to publish | |
* | |
* @param WP_Post[] $posts Array of post objects. | |
* @param WP_Query $query The WP_Query instance (passed by reference). | |
* | |
* @return WP_Post[] $posts Array of post objects. | |
*/ | |
function lubus_update_post_status_in_query_result( $posts, $query ) { | |
// Check if the query is for the REST API and includes a draft post. | |
if ( isset( $query->query_vars['post_status'] ) && in_array( 'draft', $query->query_vars['post_status'] ) ) { | |
foreach ( $posts as $post ) { | |
if ( 'draft' === $post->post_status ) { | |
// Change the post status value (for example, to 'publish'). | |
$post->post_status = 'publish'; | |
} | |
} | |
} | |
return $posts; | |
} | |
/** | |
* We are using this function only to remove the filter with functions name update_post_status_in_query_result | |
* | |
* @param WP_Post[] $posts Array of post objects. | |
* | |
* @return WP_Post[] $posts Array of post objects. | |
*/ | |
function lubus_remove_update_post_status_in_query_result( $posts ) { | |
remove_filter( 'the_posts', 'lubus_update_post_status_in_query_result', 10001 ); | |
return $posts; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment