get the current post title in wordpress in php

To get the current post title in WordPress, you can use the get_the_title() function in PHP. This function retrieves the post title for the current post in the WordPress Loop.

Here's an example:

main.php
<?php
if ( have_posts() ) {
    while ( have_posts() ) {
        the_post(); // displays the post content
        $post_title = get_the_title(); // gets the post title
        echo '<h1>' . $post_title . '</h1>'; // displays the post title
    }
}
?>
251 chars
10 lines

In this example, we're using the have_posts() and the_post() functions to loop through the current post. We then use the get_the_title() function to retrieve the post title and store it in the $post_title variable. Finally, we echo the post title using an HTML heading tag.

Keep in mind that this code should be used within a WordPress Loop, as it relies on the Loop to identify the current post.

gistlibby LogSnag