Wordpress Snippets

There’s a lot of things you can do to improve and extend Wordpress, beyond plugins and themes.

wordpress work

Deny script access

Add to the top of a script (after <?php)

if ( !defined('ABSPATH') ) {
	die("<!-- Not allowed -->");
}
</php>

Scripts, css, fonts

Choose, modify, or erase unneeded ones.

function custom_replace_css() {
  // for those plugins that add fonts but not together:
  wp_deregister_style('freehand-regular-latin,all');
  wp_deregister_style('over_the_rainbow-regular-latin,all');  

  // list fonts here separated by |
  $allfonts='Freehand:regular|Over+the+Rainbow:regular';
  wp_register_style("many-fonts","https://fonts.googleapis.com/css?family=$allfonts&subset=latin,all");
  wp_enqueue_style('many-fonts');

  // remove unneeded scripts by their tag (usually id= but look in the plugin code)
  wp_deregister_style('script-tag');
}

add_action('wp_enqueue_scripts','custom_replace_css',11);

From here

function mytheme_dequeue_fonts() {
         wp_dequeue_style( 'twentytwelve-fonts' );
      }

add_action( 'wp_enqueue_scripts', 'mytheme_dequeue_fonts', 11 );

Ref: https://wordpress.stackexchange.com/questions/66524/remove-open-sans-from-twenty-twelve-theme

Use google jquery

     /* Disable WordPress jQuery */
     wp_deregister_script('jquery');
     /* Register jQuery's CDN Version */
     wp_register_script('jquery', 'http://code.jquery.com/jquery-1.7.2.min.js');
     /* Or Use Google CDN Version */
     wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js');
     /* Enable New Script */
     wp_enqueue_script('jquery');

Ref: http://www.shanestrong.com/jquery/wordpress-cdn-hosted-jquery

Redirect Comment post

You can do a lot more, but here’s an idea

add_action('comment_post_redirect', 'your_redirect_function');

// A function that redirects your users after they have commented.
function your_redirect_function ($location, $comment) {
    // Here all you need to do is return the url of your target page.
    $page = 'http://www.stackoverflow.com';
    return $page;
}

Ref: https://stackoverflow.com/questions/18561939/wordpress-redirect-user-after-commenting

Plugin: https://yoast.com/wordpress/plugins/comment-redirect/

Shortcodes and Widgets

To let widgets use shortcodes (well, process them, that is…), add to ‘‘functions.php’’ or custom plugin:

add_filter('widget_text', 'do_shortcode');

Ref: http://digwp.com/2010/03/shortcodes-in-widgets/

Remove post features

Sometimes you need to remove post features, like excerpt or trackbacks.

<?php remove_post_type_support( $post_type, $supports ) ?>
where $post_type is usually ‘post’ and type is the feature to remove see [[http://codex.wordpress.org/Function_Reference/remove_post_type_supportCodex]] for a list of types.

Example:

add_action( 'init', 'my_custom_init' );
function my_custom_init() {
	remove_post_type_support( 'post', 'excerpt' );
}

Add Design Credit

<?php
// Put a tagline on the admin panel
function remove_footer_admin () {
?>

<span id="footer-thankyou">
Fueled by <a href="http://www.wordpress.org" target="_blank">WordPress</a>|
Site Design and Layout by <a href="http://www.supertechcrew.com" target="_blank">Matt Bagley</a>|
<a href="http://www.megamatt.net" target="_blank">View my Site</a> |
<a href="http://www.mattbagleyphotography.com" target="_blank">Check out my Pictures</a>
</span><!-- .site-info -->

<?php    
}
add_filter('admin_footer_text', 'remove_footer_admin');
?>

Load Scripts Conditionally

if( !is_admin()){
   wp_register_script('flex', get_template_directory_uri() . '/js/flexslider.js', array('jquery'), '1.8.0', true );
   wp_register_script('vids', get_template_directory_uri() . '/js/fitvids.js', array('jquery'), '1.0.0', true );
   wp_register_script('custom', get_template_directory_uri() . '/js/custom.js', array('jquery'), '1.0.0', true );
}

Ref: http://www.organizedthemes.com/loading-scripts-conditionally/

Get list of scripts

Look in plugin code, or:

global $wp_styles;

    foreach($wp_styles as $main_obj => $vals){
    if(is_array($vals)){
        // echo var_dump($vals);
        foreach($vals as $name => $obj){
            if(!empty($obj->handle)){
                // echo $obj->handle, '<br />';
                echo '"'.$obj->handle. '", ';
            }    
        }
    }
}

Ref: https://stackoverflow.com/questions/12795689/in-the-wordpress-admin-area-how-to-deregister-default-styles

Remove url in comments

function remove_comment_fields($fields) {
    unset($fields['url']);
    return $fields;
}
add_filter('comment_form_default_fields','remove_comment_fields');

Break out of Frames

I will not be trapped…

// Break Out of Frames for WordPress
function break_out_of_frames() {
	if (!is_preview()) {
		echo "\n<script type=\"text/javascript\">";
		echo "\n<!--";
		echo "\nif (parent.frames.length > 0) { parent.location.href = location.href; }";
		echo "\n-->";
		echo "\n</script>\n\n";
	}
}
add_action('wp_head', 'break_out_of_frames');
// @ http://wp-mix.com/set-attachment-featured-image/
add_filter('the_content', 'set_featured_image_from_attachment');
function set_featured_image_from_attachment($content) {
	global $post;
	if (has_post_thumbnail()) {
		// display the featured image
		$content = the_post_thumbnail() . $content;
	} else {
		// get & set the featured image
		$attachments = get_children(array(
			'post_parent' => $post->ID,
			'post_status' => 'inherit',
			'post_type' => 'attachment',
			'post_mime_type' => 'image',
			'order' => 'ASC',
			'orderby' => 'menu_order'
		));
		if ($attachments) {
			foreach ($attachments as $attachment) {
				set_post_thumbnail($post->ID, $attachment->ID);
				break;
			}
			// display the featured image
			$content = the_post_thumbnail() . $content;
		}
	}
	return $content;
}

Add thumbnail to feed

function rss_post_thumbnail($content) {
	global $post;
	if(has_post_thumbnail($post->ID)) {
		$content = get_the_post_thumbnail($post->ID) . $content;
	}
	return $content;
}
add_filter('the_excerpt_rss', 'rss_post_thumbnail');
add_filter('the_content_feed', 'rss_post_thumbnail');

Add previous/next Name

There should be a better way to do this.

<?php
	$p = get_adjacent_post(false, '', true);
	if(!empty($p)) echo '<div class="prev"><a href="' . get_permalink($p->ID) . '" title="' . $p->post_title . '">' . $p->post_title . '</a></div>';

	$n = get_adjacent_post(false, '', false);
	if(!empty($n)) echo '<div class="next"><a href="' . get_permalink($n->ID) . '" title="' .
$n->post_title . '">' . $n->post_title . '</a></div>';
?>

Show Single Result

For search results.

add_action('template_redirect', 'redirect_single_post');
function redirect_single_post() {
    if (is_search()) {
        global $wp_query;
        if ($wp_query->post_count == 1 && $wp_query->max_num_pages == 1) {
            wp_redirect( get_permalink( $wp_query->posts['0']->ID ) );
            exit;
        }
    }
}

Req Real Comments

Set min length on comments

add_filter( 'preprocess_comment', 'minimal_comment_length' );
function minimal_comment_length( $commentdata ) {
	$minimalCommentLength = 20;
	if ( strlen( trim( $commentdata['comment_content'] ) ) < $minimalCommentLength )
        {
		wp_die( 'All comments must be at least ' . $minimalCommentLength . ' characters long.' );
        }
	return $commentdata;
}

Admin notice

Show a note only to other admins.

// Admin Note
function adminnote($atts, $content = NULL){
	if(current_user_can('edit_themes') || is_user_logged_in()){
		return 'Admin Notice‘ . $content . ‘';  	
}  }  add_shortcode('note', 'adminnote');  
// Use [note]This will appear only to admins[/note]  

Add Content to Feed

function feedFilter($query) {
    if ($query->is_feed) {
        add_filter('the_content','feedContentFilter');
    }
    return $query;
}
add_filter('pre_get_posts','feedFilter');

function feedContentFilter($content) {
    $content .= '<p>Extra RSS content goes here... </p>';

    return $content;
}

Allow PHP in Widgets

function php_text($text) {
 if (strpos($text, '<' . '?') !== false) {
 ob_start();
 eval('?' . '>' . $text);
 $text = ob_get_contents();
 ob_end_clean();
 }
 return $text;
}
add_filter('widget_text', 'php_text', 99)

Style First Paragraph

function first_paragraph($content){

global $post;

if ($post->post_type == "post"){
     return preg_replace('/&lt;p([^>]+)?>/', '&lt;p$1 class="first">', $content, 1); }
else {
       return $content;
      }
}
add_filter('the_content', 'first_paragraph');

Add Thumbnails to Post List

/****** Add Thumbnails in Manage Posts/Pages List ******/
if ( !function_exists('AddThumbColumn') && function_exists('add_theme_support') ) {

    // for post and page
    add_theme_support('post-thumbnails', array( 'post', 'page' ) );

    function AddThumbColumn($cols) {

        $cols['thumbnail'] = __('Thumbnail');

        return $cols;
    }

    function AddThumbValue($column_name, $post_id) {

            $width = (int) 35;
            $height = (int) 35;

            if ( 'thumbnail' == $column_name ) {
                // thumbnail of WP 2.9
                $thumbnail_id = get_post_meta( $post_id, '_thumbnail_id', true );
                // image from gallery
                $attachments = get_children( array('post_parent' => $post_id, 'post_type' => 'attachment', 'post_mime_type' => 'image') );
                if ($thumbnail_id)
                    $thumb = wp_get_attachment_image( $thumbnail_id, array($width, $height), true );
                elseif ($attachments) {
                    foreach ( $attachments as $attachment_id => $attachment ) {
                        $thumb = wp_get_attachment_image( $attachment_id, array($width, $height), true );
                    }
                }
                    if ( isset($thumb) && $thumb ) {
                        echo $thumb;
                    } else {
                        echo __('None');
                    }
            }
    }

    // for posts
    add_filter( 'manage_posts_columns', 'AddThumbColumn' );
    add_action( 'manage_posts_custom_column', 'AddThumbValue', 10, 2 );

    // for pages
    add_filter( 'manage_pages_columns', 'AddThumbColumn' );
    add_action( 'manage_pages_custom_column', 'AddThumbValue', 10, 2 );

Remove Images from Content

This is useful for showing full content on home page without the images. From here.

add_filter('the_content', 'filter_images',2);

function filter_images($content){
    return preg_replace(/< img alt=”” />]+./,,$content);
}

This one may be better for custom themes.

<?php
  $content = get_the_content();
  $postOutput = preg_replace('/<img[^>]+./','', $content);
  echo $postOutput;
?>