Matt Fiddles

Life's so vast, there's just so much to do...

User Tools

Site Tools


Sidebar

"...[Arthur] leapt to his feet like an author hearing the phone ring..."

- Who says that the character of Arthur isn't autobiographical?



Where will you go today?

"I don't know, " said the voice on the PA, "apathetic bloody planet, I've no sympathy at all. "
computers:websites:wordpress:snippets

Wordpress Snippets

Just some parts and pieces to use.

Also see 25 Useful Code Snippets for WordPress

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.

Possible tool: http://generatewp.com/register_script/

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);

Ref: http://justintadlock.com/archives/2009/08/06/how-to-disable-scripts-and-styles

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 Codex 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.mydigitalwalk.com" target="_blank">Matt Bagley</a>| 
<a href="http://www.mattfiddles.com" target="_blank">View my Notes</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;
?>

More

Change date https://lorelle.wordpress.com/2007/09/03/displaying-the-date-in-your-wordpress-theme/

Author templates http://codex.wordpress.org/Author_Templates

Lists of snippets to add:

Add more numbers to the navagation bar at the bottom of the page, by finding that code and increasing mid_size:

$paginate_links = paginate_links( array(
  ...
  'mid_size' => 2,
  ...
);

Disable checking for updates: https://wordpress.stackexchange.com/questions/102554/prevent-disable-automatic-update-check

computers/websites/wordpress/snippets.txt · Last modified: Jan 31, 2015 (3 years ago) by Matt Bagley