Skip to content

Instantly share code, notes, and snippets.

@iamchetanp
Created June 26, 2019 10:52
Show Gist options
  • Save iamchetanp/4078ea0b129468167f6ece273aafdfc4 to your computer and use it in GitHub Desktop.
Save iamchetanp/4078ea0b129468167f6ece273aafdfc4 to your computer and use it in GitHub Desktop.
Title function for WordPress
/**
* Return title based on current page, post, taxonomy, post type, category, tag etc.
*/
function cpdivi_title() {
if ( is_home() ) {
$page_for_posts = get_option( 'page_for_posts' );
$title = sprintf( __( '%s', 'cpdivi' ), get_the_title( $page_for_posts ) );
} elseif ( is_category() ) {
/* translators: 1: category title. */
$title = sprintf( __( 'Category: %s', 'cpdivi' ), single_cat_title( '', false ) );
} elseif ( is_tag() ) {
/* translators: 1: tag title. */
$title = sprintf( __( 'Tag: %s', 'cpdivi' ), single_tag_title( '', false ) );
} elseif ( is_tax() ) {
$title = sprintf( '%s', single_term_title() );
} elseif ( function_exists( 'is_post_type_archive' ) && is_post_type_archive() && function_exists( 'post_type_archive_title' ) ) {
$title = post_type_archive_title( '', false );
} elseif ( is_author() ) {
/* translators: 1: author title. */
$title = sprintf( __( 'Author: %s', 'cpdivi' ), get_the_author() );
} elseif ( is_year() ) {
/* translators: 1: year title. */
$title = sprintf( __( 'Year: %s', 'cpdivi' ), get_the_time( 'Y' ) );
} elseif ( is_month() ) {
/* translators: 1: month title. */
$title = sprintf( __( 'Month: %s', 'cpdivi' ), get_the_time( 'F Y' ) );
} elseif ( is_day() ) {
/* translators: 1: day title. */
$title = sprintf( __( 'Day: %s', 'cpdivi' ), get_the_date() );
} elseif ( is_time() ) {
$title = __( 'Time Archive', 'cpdivi' );
} elseif ( is_search() ) {
/* translators: 1: search keyword. */
$title = sprintf( 'Search for: %s', get_search_query() );
} elseif ( is_404() ) {
$title = __( '404 - Page not found', 'cpdivi' );
} else {
$title = sprintf( '%s', get_the_title() );
}
// If paginated query.
if ( is_paged() ) {
return sprintf( '%s – Page %d', $title, get_query_var( 'paged' ) );
} else {
return $title;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment