Home / Archive / Admin Functions for posts.
Duplicate Snippet

Embed Snippet on Your Site

Admin Functions for posts.

Make it easier to edit posts when viewing archives or single pages.
Add page slug to body class for better styling.
Automatically Link Featured Images to Posts
Add new badge to new posts.

Code Preview
php
<?php
// Add an Edit Post Link to Archives
edit_post_link( __( '{Edit}' ) );
// Add page slug to body class for better styling.
function wpcode_snippet_add_slug_body_class( $classes ) {
	global $post;
	if ( isset( $post ) ) {
		$classes[] = $post->post_type . '-' . $post->post_name;
	}
	return $classes;
}
add_filter( 'body_class', 'wpcode_snippet_add_slug_body_class' );
// Automatically Link Featured Images to Posts
/**
 * Wrap the thumbnail in a link to the post.
 * Only use this if your theme doesn't already wrap thumbnails in a link.
 *
 * @param string $html The thumbnail HTML to wrap in an anchor.
 * @param int    $post_id The post ID.
 * @param int    $post_image_id The image id.
 *
 * @return string
 */
function wpcode_snippet_autolink_featured_images( $html, $post_id, $post_image_id ) {
	$html = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_the_title( $post_id ) ) . '">' . $html . '</a>';
	return $html;
}
add_filter( 'post_thumbnail_html', 'wpcode_snippet_autolink_featured_images', 20, 3 );
// Add new badge to new posts.
add_filter( 'the_title', function ( $title, $id ) {
	if ( ! is_admin() && is_single( $id ) ) {
		$number_of_days = 7;
		$post_date      = get_the_date( 'U', $id );
		$current_date   = current_time( 'timestamp' );
		$date_diff      = $current_date - $post_date;
		if ( $date_diff < $number_of_days * DAY_IN_SECONDS ) {
			$title .= ' <span class="new-badge">New</span>';
		}
	}
	return $title;
}, 10, 2 );
add_action( 'wp_head', function () {
	echo '
        <style>
            .new-badge {
                background-color: #ff0000; 
                color: #ffffff; 
                padding: 2px 5px; 
                font-size: 12px; 
                border-radius: 3px;
                margin-left: 5px;
            }
        </style>
    ';
} );

Comments

Add a Comment