Created
August 13, 2025 18:18
-
-
Save kpirnie/cccd5876a3ed46dc7cd4ce313aba4cb0 to your computer and use it in GitHub Desktop.
WordPress - Get Current Post
This file contains hidden or 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
| /** | |
| * get_current_post | |
| * | |
| * Static method for getting the current post | |
| * | |
| * @since 7.3 | |
| * @access public | |
| * @author Kevin Pirnie <[email protected]> | |
| * @package Kevin's Framework | |
| * | |
| * @return WP_Post Returns a nullable WP_post object for the current post being browsed | |
| * | |
| */ | |
| public function get_current_post( ) : ?WP_Post { | |
| // let's get our post global | |
| global $post; | |
| // if it's empty, let's try to retrieve it based on the post querystring | |
| if ( empty( $post ) && is_array( $_GET ) ) { | |
| $post = ( ! empty( $_GET['post'] ) ) ? get_post( sanitize_key( $_GET['post'] ) ) : null; | |
| } | |
| // Optional: get an empty post object from the post_type | |
| if ( empty( $post ) && is_array( $_GET ) ) { | |
| // default standard class object | |
| $object = new stdClass( ); | |
| // set the objects post type | |
| $object -> post_type = ( ! empty( $_GET['post_type'] ) ) ? get_post( sanitize_key( $_GET['post_type'] ) ) : null; | |
| // return a new WP Pot object | |
| return new WP_Post( $object ); | |
| } | |
| // now... if our post object is still empty, let's try to figure it out via the URL | |
| if ( empty( $post ) ) { | |
| // grab our WP global | |
| global $wp; | |
| // try to get the current URL | |
| $current_url = home_url( add_query_arg( array( ), $wp -> request ) ); | |
| // try to get the post ID, from the URL | |
| $current_post_id = url_to_postid( $current_url ); | |
| // get the post | |
| $post = get_post( $current_post_id ); | |
| } | |
| // one more check if post is still empty. generally this means we're on the configured blog page | |
| if ( empty( $post ) ) { | |
| // get the post | |
| $post = get_post( ( int ) get_option( 'page_for_posts' ) ); | |
| } | |
| // return the WP Post object | |
| return $post; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment