If you own a website, there is little doubt that you haven’t seen something on another website and wished your site would do that. Personally, it happens to me all the time. You find yourself sitting there wondering how they exactly they did that and how you can make your site do something similar to that.
One of the easiest ways to do that if you use WordPress, is to install a WordPress plugin. Plugins extend the functionality of the base WordPress installation allowing it to provide both you and your users with additional functions not normally provided by the theme you are using.
While this is the most common way, you can easily add code snippets to your WordPress theme files to accomplish the same goal. In fact, most themes modify the base install of WordPress to change how use it.
Code Snippets are small pieces of code that you can easily insert into your theme’s functions that will enhance your WordPress installation in a variety of ways.
If you own a site running WordPress, one of the best things you can do for your site is to find these little tools and hacks that improve your site for both you, the administrator, as well as for your visitors.
Even if you don’t find a snippet that you think will work for your site, it can give you valuable insights on how WordPress functions and it can even provide inspiration for you on your site.
While you can easily incorporate many of these code snippets into your functions.php file, many developers have taken these handy snippets and created WordPress Plugins that can then be easily shared with the entire WordPress community.
But regardless of how you decide to use them, many of the snippets you will find can provide real value to your site and help improve both its function and performance.
In this article you will find several WordPress tips, tricks and hacks that can improve your website’s performance and usefulness and require very little work and code knowledge to use.
Delete WordPress post revisions
$wpdb->query( "
DELETE FROM $wpdb->posts
WHERE post_type = 'revision'
" );
Note: You have to remove this code immediately after saving your functions.php file. You only need to run this code once, there’s no need to keep this code in your theme.
Set the default image size in WordPress galleries
remove_shortcode('gallery');
add_shortcode('gallery', 'custom_size_gallery');
function custom_size_gallery($attr) {
$attr['size'] = 'medium';
return gallery_shortcode($attr);
}
Breadcrumb without plugin
function the_breadcrumb() {
echo '<ul id="crumbs">';
if (!is_home()) {
echo '<li><a href="';
echo get_option('home');
echo '">';
echo 'Home';
echo "</a></li>";
if (is_category() || is_single()) {
echo '<li>';
the_category(' </li><li> ');
if (is_single()) {
echo "</li><li>";
the_title();
echo '</li>';
}
} elseif (is_page()) {
echo '<li>';
echo the_title();
echo '</li>';
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}
echo '</ul>';
}
And then open header.php and call the function:
<?php the_breadcrumb(); ?>
Add custom text to WordPress login page
function wps_login_message( $message ) {
if ( empty($message) ){
return "<p class='message'>Welcome to this site. Please log in to continue</p>";
} else {
return $message;
}
}
add_filter( 'login_message', 'wps_login_message' );
Redirect to a custom page after registration
function __my_registration_redirect(){
return home_url( '/my-page' );
}
add_filter( 'registration_redirect', '__my_registration_redirect' );
How to paginate WordPress like Dribbble
Use this code below in your single.php file, where you want to have the dribbble-like pagination:
<?php $prev = get_previous_post(); $next = get_next_post();
<div class="float--left folio">
<a href="<?php echo get_permalink($prev->ID); ?>" title="<?php echo esc_attr($prev->post_title); ?>">
<?php echo get_the_post_thumbnail($prev->ID, 'thumbnail'); ?>
</a>
</div>
<div class="float--right folio">
<a href="<?php echo get_permalink($next->ID); ?>" title="<?php echo esc_attr($next->post_title); ?>">
<?php echo get_the_post_thumbnail($next->ID, 'thumbnail'); ?>
</a>
</div>
Efficient SEO without a plugin
function basic_wp_seo() {
global $page, $paged, $post;
$default_keywords = 'wordpress, plugins, themes, design, dev, development, security, htaccess, apache, php, sql, html, css, jquery, javascript, tutorials'; // customize
$output = '';
// description
$seo_desc = get_post_meta($post->ID, 'mm_seo_desc', true);
$description = get_bloginfo('description', 'display');
$pagedata = get_post($post->ID);
if (is_singular()) {
if (!empty($seo_desc)) {
$content = $seo_desc;
} else if (!empty($pagedata)) {
$content = apply_filters('the_excerpt_rss', $pagedata->post_content);
$content = substr(trim(strip_tags($content)), 0, 155);
$content = preg_replace('#\n#', ' ', $content);
$content = preg_replace('#\s{2,}#', ' ', $content);
$content = trim($content);
}
} else {
$content = $description;
}
$output .= '<meta name="description" content="' . esc_attr($content) . '">' . "\n";
// keywords
$keys = get_post_meta($post->ID, 'mm_seo_keywords', true);
$cats = get_the_category();
$tags = get_the_tags();
if (empty($keys)) {
if (!empty($cats)) foreach($cats as $cat) $keys .= $cat->name . ', ';
if (!empty($tags)) foreach($tags as $tag) $keys .= $tag->name . ', ';
$keys .= $default_keywords;
}
$output .= "\t\t" . '<meta name="keywords" content="' . esc_attr($keys) . '">' . "\n";
// robots
if (is_category() || is_tag()) {
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
if ($paged > 1) {
$output .= "\t\t" . '<meta name="robots" content="noindex,follow">' . "\n";
} else {
$output .= "\t\t" . '<meta name="robots" content="index,follow">' . "\n";
}
} else if (is_home() || is_singular()) {
$output .= "\t\t" . '<meta name="robots" content="index,follow">' . "\n";
} else {
$output .= "\t\t" . '<meta name="robots" content="noindex,follow">' . "\n";
}
// title
$title_custom = get_post_meta($post->ID, 'mm_seo_title', true);
$url = ltrim(esc_url($_SERVER['REQUEST_URI']), '/');
$name = get_bloginfo('name', 'display');
$title = trim(wp_title('', false));
$cat = single_cat_title('', false);
$tag = single_tag_title('', false);
$search = get_search_query();
if (!empty($title_custom)) $title = $title_custom;
if ($paged >= 2 || $page >= 2) $page_number = ' | ' . sprintf('Page %s', max($paged, $page));
else $page_number = '';
if (is_home() || is_front_page()) $seo_title = $name . ' | ' . $description;
elseif (is_singular()) $seo_title = $title . ' | ' . $name;
elseif (is_tag()) $seo_title = 'Tag Archive: ' . $tag . ' | ' . $name;
elseif (is_category()) $seo_title = 'Category Archive: ' . $cat . ' | ' . $name;
elseif (is_archive()) $seo_title = 'Archive: ' . $title . ' | ' . $name;
elseif (is_search()) $seo_title = 'Search: ' . $search . ' | ' . $name;
elseif (is_404()) $seo_title = '404 - Not Found: ' . $url . ' | ' . $name;
else $seo_title = $name . ' | ' . $description;
$output .= "\t\t" . '<title>' . esc_attr($seo_title . $page_number) . '</title>' . "\n";
return $output;
}
After putting this in functions.php, replace the $default_keywords (line 3) with your own and add the following code into your header.php file:
<?php echo basic_wp_seo(); ?>
How to load jQuery from Google CDN
function jquery_cdn() {
if (!is_admin()) {
wp_deregister_script('jquery');
wp_register_script('jquery', 'http://ift.tt/1fEahZI', false, '1.8.3');
wp_enqueue_script('jquery');
}
}
add_action('init', 'jquery_cdn');
Email alert for 404s
To implement, simply include this script at the top of your theme’s 404.php file. If your theme don’t have a 404.php file, then create it.
?php // WP 404 ALERTS @ http://ift.tt/WdpJX1
// set status
header("HTTP/1.1 404 Not Found");
header("Status: 404 Not Found");
// site info
$blog = get_bloginfo('name');
$site = get_bloginfo('url') . '/';
$email = get_bloginfo('admin_email');
// theme info
if (!empty($_COOKIE["nkthemeswitch" . COOKIEHASH])) {
$theme = clean($_COOKIE["nkthemeswitch" . COOKIEHASH]);
} else {
$theme_data = wp_get_theme();
$theme = clean($theme_data->Name);
}
// referrer
if (isset($_SERVER['HTTP_REFERER'])) {
$referer = clean($_SERVER['HTTP_REFERER']);
} else {
$referer = "undefined";
}
// request URI
if (isset($_SERVER['REQUEST_URI']) && isset($_SERVER["HTTP_HOST"])) {
$request = clean('http://' . $_SERVER["HTTP_HOST"] . $_SERVER["REQUEST_URI"]);
} else {
$request = "undefined";
}
// query string
if (isset($_SERVER['QUERY_STRING'])) {
$string = clean($_SERVER['QUERY_STRING']);
} else {
$string = "undefined";
}
// IP address
if (isset($_SERVER['REMOTE_ADDR'])) {
$address = clean($_SERVER['REMOTE_ADDR']);
} else {
$address = "undefined";
}
// user agent
if (isset($_SERVER['HTTP_USER_AGENT'])) {
$agent = clean($_SERVER['HTTP_USER_AGENT']);
} else {
$agent = "undefined";
}
// identity
if (isset($_SERVER['REMOTE_IDENT'])) {
$remote = clean($_SERVER['REMOTE_IDENT']);
} else {
$remote = "undefined";
}
// log time
$time = clean(date("F jS Y, h:ia", time()));
// sanitize
function clean($string) {
$string = rtrim($string);
$string = ltrim($string);
$string = htmlentities($string, ENT_QUOTES);
$string = str_replace("\n", "<br>", $string);
if (get_magic_quotes_gpc()) {
$string = stripslashes($string);
}
return $string;
}
$message =
"TIME: " . $time . "\n" .
"*404: " . $request . "\n" .
"SITE: " . $site . "\n" .
"THEME: " . $theme . "\n" .
"REFERRER: " . $referer . "\n" .
"QUERY STRING: " . $string . "\n" .
"REMOTE ADDRESS: " . $address . "\n" .
"REMOTE IDENTITY: " . $remote . "\n" .
"USER AGENT: " . $agent . "\n\n\n";
mail($email, "404 Alert: " . $blog . " [" . $theme . "]", $message, "From: $email");
?>
Automatically remove short words from the URL
Paste the code below into your functions.php file. Once you saved the file, WordPress will automatically remove short (less than 3 characters) words from the generated permalink.
add_filter('sanitize_title', 'remove_short_words');
function remove_short_words($slug) {
if (!is_admin()) return $slug;
$slug = explode('-', $slug);
foreach ($slug as $k => $word) {
if (strlen($word) < 3) {
unset($slug[$k]);
}
}
return implode('-', $slug);
}
Force specific pages to be SSL secure
Just add the following snippet to the functions.php file of your WordPress theme and specify the post or page ID desired.
function wps_force_ssl( $force_ssl, $post_id = 0, $url = '' ) {
if ( $post_id == 25 ) {
return true
}
return $force_ssl;
}
add_filter('force_ssl' , 'wps_force_ssl', 10, 3);
Crop uploaded images instead of scaling them
// Standard Size Thumbnail
if(false === get_option("thumbnail_crop")) {
add_option("thumbnail_crop", "1"); }
else {
update_option("thumbnail_crop", "1");
}
// Medium Size Thumbnail
if(false === get_option("medium_crop")) {
add_option("medium_crop", "1"); }
else {
update_option("medium_crop", "1");
}
// Large Size Thumbnail
if(false === get_option("large_crop")) {
add_option("large_crop", "1"); }
else {
update_option("large_crop", "1");
}
Setup different admin and theme languages on your WordPress blog
<?php
// setup one language for admin and the other for theme
// must be called before load_theme_textdomain()
function set_my_locale($locale) {
$locale = ( is_admin() ) ? "en_US" : "it_IT";
setlocale(LC_ALL, $local );
return $locale;
}
add_filter( 'locale', 'set_my_locale' );
?>
Add SVG upload support to your WordPress blog
add_filter('upload_mimes', 'my_upload_mimes');
function my_upload_mimes($mimes = array()) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
Run the loop outside of WordPress
Paste the following code on any PHP file where you want to run your WordPress loop. Don’t forget to modify the following:
line 4: Please specify the path to your WordPress wp-blog-header.php file.
line 5: Query posts using the query_posts() function.
<?php
// Include WordPress
define('WP_USE_THEMES', false);
require('/server/path/to/your/wordpress/site/htdocs/blog/wp-blog-header.php');
query_posts('posts_per_page=1');
?>
Run Loop
<?php while (have_posts()): the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_excerpt(); ?>
<p><a href="<?php the_permalink(); ?>" class="red">Read more...</a></p>
<?php endwhile; ?>
WordPress function to show a total share counter (FB, Twitter, G+)
function social_shares() {
$url = get_permalink( $post_id );
$json = file_get_contents("http://ift.tt/1COKx8o; .
rawurlencode($url));
$counts = json_decode($json, true);
$totalcounts= $counts["Twitter"] +
$counts["Facebook"]["total_count"] +
$counts["GooglePlusOne"];
echo "<div>$totalcounts Share</div>";
}
Easily make WordPress images responsive
The first thing to do is to create the shortcode. To do so, open your functions.php file and paste the following code in it:
function responsive_images($atts, $content = null) {
return '<div class="image-resized">' . $content .'</div>';
}
add_shortcode('responsive', 'responsive_images');
Once done, open your style.css file and add those CSS rules:
@media only screen and (max-width:767px) {
.image-resized img {
width:100%;
height:auto;
}
}
You can now use the [responsive] shortcode to insert responsive images in your blog:
[responsive]<img src="image_url" alt="alt" title="title" />[/responsive]
Automatically hide email adresses from spambots on your WordPress blog
function security_remove_emails($content) {
$pattern = '/([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4})/i';
$fix = preg_replace_callback($pattern,"security_remove_emails_logic", $content);
return $fix;
}
function security_remove_emails_logic($result) {
return antispambot($result[1]);
}
add_filter( 'the_content', 'security_remove_emails', 20 );
add_filter( 'widget_text', 'security_remove_emails', 20 );
Automatic “Nofollow” for external links in post content
add_filter('the_content', 'auto_nofollow');
function auto_nofollow($content) {
//return stripslashes(wp_rel_nofollow($content));
return preg_replace_callback('/<a>]+/', 'auto_nofollow_callback', $content);
}
function auto_nofollow_callback($matches) {
$link = $matches[0];
$site_link = get_bloginfo('url');
if (strpos($link, 'rel') === false) {
$link = preg_replace("%(href=S(?!$site_link))%i", 'rel="nofollow" $1', $link);
} elseif (preg_match("%href=S(?!$site_link)%i", $link)) {
$link = preg_replace('/rel=S(?!nofollow)S*/i', 'rel="nofollow"', $link);
}
return $link;
}
Secure your WordPress blog uploads directory
Edit the .htaccess file and paste the following code in it. The following example will only accept images files.
<Files ~ ".*..*">
Order Allow,Deny
Deny from all
</Files>
<FilesMatch ".(jpg|jpeg|jpe|gif|png|tif|tiff)$">
Order Deny,Allow
Allow from all
</FilesMatch>
Display a custom message on WordPress registration page
add_action('register_form', 'register_message');
function register_message() {
$html = '
<div style="margin:10px 0;border:1px solid #e5e5e5;padding:10px">
<p style="margin:5px 0;">
Joining this site you agree to the following terms. Do no harm!
</p>
</div>';
echo $html;
}
You will definitely like these articles
Source: http://ift.tt/1xgQMic
No comments:
Post a Comment