Site icon Anthony Carbon

How to get current post/page/custom post type post data (ID, Post Name, Post Title, Etc.) in init action?

How to get current post/page/custom post type post data (ID, Post Name, Post Title, Etc.) in init action? If you have something to get in your current page and don’t know how to get the current post ID, post name, post type, post content, and many more, the codes below is the solution. Using init action, some of the WordPress codex might not work and you need to find another way of getting the information manually.

To get started, copy the codes to your functions.php. Try it on your own.

add_action( 'init', 'wdes_init_function' );

function wdes_init_function(){
	$post_type = 'business_listing'; // post type can be page, post, or custom post type
	$url = explode('/', $_SERVER["REQUEST_URI"] );
	$count = count( $url ); // get the total array in $url
	$slug = $url[($count-2)]; // get the second to the last array value
	$data = get_page_by_path( $slug, OBJECT, $post_type );
	echo $data->ID; //echo the ID of the current post/page/custom post type
	echo $data->post_type; //echo the post_type of the current post/page/custom post type
	echo $data->post_name; //echo the post_name of the current post/page/custom post type
}

Happy coding 🙂

Exit mobile version