Display page and custom post title inside shortcode

I am trying to write a shortcode to display the page title. I only got the archive title to work, but not custom post type category and single post. Can anyone shed light how to do this?

The reason for going this path is Elemenentor theme builder generating too much code for simple page title and subheading inside secondary header that is masked wrap around an image. I use the shortcode widget to insert the code and style it.

So far this is what I have written:

// Page Title inside shortcode
function page_title_sc( ) {
    $title = ('Page Title');

   if ( is_post_type_archive() ) {
    $title = post_type_archive_title( '', false ); 
 }
  elseif ( is_page() ) {
    $title = single_post_title();
   } 
   return apply_filters( 'page_title_sc', $title );
}
 
add_shortcode( 'page_title', 'page_title_sc' );

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Add Below Code For post title, page title, category title , tag title , taxonmy title , Author title .

According to your Needed.

function page_title_sc( ) {

    $title = ('Page Title');

    if ( is_page() || is_singular() ) {
        $title = single_post_title();
    } else if ( is_category() ) {
        $title = single_cat_title( '', false );
    } else if ( is_tag() ) {
        $title = single_tag_title( '', false );
    } else if ( is_author() ) {
        $title = '<span class="vcard">' . get_the_author() . '</span>';
    } else if ( is_post_type_archive() ) {
        $title = post_type_archive_title( '', false );
    } else if ( is_tax() ) {
        $title = single_term_title( '', false );
    }

   return apply_filters( 'page_title_sc', $title );
}
 
add_shortcode( 'page_title', 'page_title_sc' );

Method 2

I’m not completely sure what you want to do but is_page will check for a page and exclude (custom) posts. If you want the condition to work for posts you will need is_single. If you want the condition to work for both posts and pages you will need is_singular.

That said, going this path may not be the smartest thing to do, because you will be polluting your post content. It would be more logical to write a filter for the title that cancels what Elementor does to it that you don’t like. If you write a filter with a high priority, you can achieve the same thing you are now doing with a shortcode without having to modify your post content.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x