Change the Text of Reset Password Email

September 25, 2016 (4 years ago)
WordPress, PHP, Functions

Send a custom message to users who request a password re-set:

//* Password reset activation E-mail -> Body
add_filter( 'retrieve_password_message', 'dnlt_retrieve_password_message', 10, 2 );

function dnlt_retrieve_password_message( $message, $key ){
    $user_data = '';
    // If no value is posted, return false
    if( ! isset( $_POST['user_login'] )  ){
            return '';
    }
    // Fetch user information from user_login
    if ( strpos( $_POST['user_login'], '@' ) ) {

        $user_data = get_user_by( 'email', trim( $_POST['user_login'] ) );
    } else {
        $login = trim($_POST['user_login']);
        $user_data = get_user_by('login', $login);
    }
    if( ! $user_data  ){
        return '';
    }
    $user_login = $user_data->user_login;
    $user_email = $user_data->user_email;
    // Setting up message for retrieve password
    $message = "A password reset has been requested for this site:\n\n";
    $message .= network_home_url( '/' ) . "\r\n\r\n";
    $message .= sprintf(__('Username: %s'), $user_login) . "\r\n\r\n";  
    $message .= "Change this text to whatever you like.\n\n";
    $message .= "If you did not request this, just ignore this email and nothing will happen.\n\n"; 
    $message .= "To reset your password, visit the following address:\n";
    $message .= network_site_url("wp-login.php?action=rp&key=$key&login=" . rawurlencode($user_login), 'login');
    
    return $message;
}

 

Debugging Scripts in the Console

June 29, 2015 (5 years ago)
PHP, Functions

The easiest way to see what data is being used inside a script. Add this script to your page (or in functions.php for sitewide use).

function debug_to_console( $data ) {

    if ( is_array( $data ) )
        $output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
    else
        $output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";

    echo $output;
}

Then call it inside your function like this:

debug_to_console($mydata);

Then just look at your console log to see the output.

Hint: if you are tracking one variable through a script and want to see how it changes, try something like this:

debug_to_console('step 1 -' . $mydata);

 

Embedding a Video in a Template File

January 11, 2015 (6 years ago)
WordPress, PHP

Adding shortcodes to template files is a bit tricky. Although [ embed]myvideourl[ /embed] looks like a regular WP shortcode, it’s not handled the same way.

It works just as expected in a content block, but not so in a template file. Here’s the code to embed into the template:

global $wp_embed;

echo $wp_embed->run_shortcode('[ embed]myvideourl[ /embed]');

 NOTE: To use this code, you will need to remove the spaces inside the brackets before ’embed’ and ‘/embed’.

Allow HTML in Excerpts

December 9, 2014 (6 years ago)
WordPress, PHP, Functions

By default, WordPress strips all HTML tags from excerpts. To allow them, simply replace the filter that creates the excerpt from your content.

First, copy the default excerpt filter from wp-includes/formatting.php:

function wp_trim_excerpt($text) { // Fakes an excerpt if needed
    global $post;
    if ( '' == $text ) {
        $text = get_the_content('');
        $text = apply_filters('the_content', $text);
        $text = str_replace('\]\]\>', ']]&gt;', $text);
        $text = strip_tags($text);
        $excerpt_length = 55;
        $words = explode(' ', $text, $excerpt_length + 1);
        if (count($words)> $excerpt_length) {
            array_pop($words);
            array_push($words, '[...]');
            $text = implode(' ', $words);
        }
    }
    return $text;
}

 By changing the strip_tags parameters, you can allow whatever tags you want:

Also be sure to change the name of the function. Copy this to your functions.php file.

function lt_html_excerpt($text) { // Fakes an excerpt if needed
    global $post;
    if ( '' == $text ) {
        $text = get_the_content('');
        $text = apply_filters('the_content', $text);
        $text = str_replace('\]\]\>', ']]&gt;', $text);
        /*just add all the tags you want to appear in the excerpt --
        be sure there are no white spaces in the string of allowed tags */
        $text = strip_tags($text,'<p><br><b><a><em><strong>');
        /* you can also change the length of the excerpt here, if you want */
        $excerpt_length = 55; 
        $words = explode(' ', $text, $excerpt_length + 1);
        if (count($words)> $excerpt_length) {
            array_pop($words);
            array_push($words, '[...]');
            $text = implode(' ', $words);
        }
    }
    return $text;
}

 Then, replace the default filter with your new one in functions.php:

/* remove the default filter */
remove_filter('get_the_excerpt', 'wp_trim_excerpt');

/* now, add your own filter */
add_filter('get_the_excerpt', 'lt_html_excerpt');

 

Custom Post Type for a Menu

August 29, 2014 (6 years ago)
PHP, Plugins

I created this simple plugin for a restaurant to post their menu online.

Here’s the plugin file (put in plugins directory).

It includes categories (for menu sections), and several parameters for each item.

<?php
/*
Plugin Name: Grille Menu
Description: Custom Post Type for Menu Items
Author: Diana Nichols
Version: 1.0
Author URI: http://www.lavenderthreads.com
*/

add_action( 'init', 'register_grille_menu' );

function register_grille_menu() {

    $labels = array( 
        'name' => _x( 'Grille Menu', 'menu' ),
        'singular_name' => _x( 'Grille Menu Item', 'menu' ),
        'add_new' => _x( 'Add New', 'menu' ),
        'add_new_item' => _x( 'Add New Menu Item', 'menu' ),
        'edit_item' => _x( 'Edit Item', 'menu' ),
        'new_item' => _x( 'New Item', 'menu' ),
        'view_item' => _x( 'View Item', 'menu' ),
        'search_items' => _x( 'Search Items', 'menu' ),
        'not_found' => _x( 'No items found', 'menu' ),
        'not_found_in_trash' => _x( 'No items found in Trash', 'menu' ),
        'parent_item_colon' => _x( 'Parent Item:', 'menu' ),
        'menu_name' => _x( 'Grille Menu', 'menu' ),
    );

    $args = array( 
        'labels' => $labels,
        'hierarchical' => false,        
        'supports' => array( 'title', 'editor', 'page-atributes' ),
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,   
        'show_in_nav_menus' => true,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'has_archive' => true,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => true,
        'capability_type' => 'post'
    );

    register_post_type( 'grille_menu', $args );
}

add_action( 'init', 'register_grille_taxonomy_categories' );

function register_grille_taxonomy_categories() {

    $labels = array( 
        'name' => _x( 'Grille Categories', 'categories' ),
        'singular_name' => _x( 'Category', 'categories' ),
        'search_items' => _x( 'Search Categories', 'categories' ),
        'popular_items' => _x( 'Popular Categories', 'categories' ),
        'all_items' => _x( 'All Categories', 'categories' ),
        'parent_item' => _x( 'Parent Category', 'categories' ),
        'parent_item_colon' => _x( 'Parent Category:', 'categories' ),
        'edit_item' => _x( 'Edit Category', 'categories' ),
        'update_item' => _x( 'Update Category', 'categories' ),
        'add_new_item' => _x( 'Add New Category', 'categories' ),
        'new_item_name' => _x( 'New Category', 'categories' ),
        'separate_items_with_commas' => _x( 'Separate categories with commas', 'categories' ),
        'add_or_remove_items' => _x( 'Add or remove categories', 'categories' ),
        'choose_from_most_used' => _x( 'Choose from the most used categories', 'categories' ),
        'menu_name' => _x( 'Categories', 'categories' ),
    );

    $args = array( 
        'labels' => $labels,
        'public' => true,
        'show_in_nav_menus' => true,
        'show_ui' => true,
        'show_tagcloud' => true,
        'show_admin_column' => true,
        'hierarchical' => true,
        'rewrite' => true,
        'query_var' => true
    );

    register_taxonomy( 'grille_categories', array('grille_menu'), $args );
}

// the custom fields
add_action('admin_menu', 'lt_grille_add_box'); 

$prefix = 'grille_menu_';

$grille_meta_box['grille_menu'] = array(
    'id' => 'grille-menu-meta-details',
    'title' => 'Menu Item Information',
    'context' => 'side',
    'priority' => 'default',
    'fields' => array(
		array(
		'name' => 'Price 1',
		'id' => $prefix . 'price1',
		'type' => 'text',
		'desc' => '',
		'default' => '',
		'class' => '',
		),
		array(
		'name' => 'Price Label 1',
		'id' => $prefix . 'pricelabel1',
		'type' => 'text',
		'desc' => '',
		'default' => '',
		'class' => '',
		),
		array(
		'name' => 'Price 2',
		'id' => $prefix . 'price2',
		'type' => 'text',
		'desc' => '',
		'default' => '',
		'class' => '',
		),
		array(
		'name' => 'Price Label 2',
		'id' => $prefix . 'pricelabel2',
		'type' => 'text',
		'desc' => '',
		'default' => '',
		'class' => '',
		),
		array(
		'name' => 'Signature Item',
		'id' => $prefix . 'signature',
		'type' => 'checkbox',
		'desc' => '',
		'default' => '',
		'class' => '',
		),
		array(
		'name' => 'Menu Order',
		'id' => $prefix . 'order',
		'type' => 'text',
		'desc' => '',
		'default' => '1',
		'class' => '',
		),
    )
);

//Add meta boxes to post types
function lt_grille_add_box() {
    global $grille_meta_box;
    
    foreach($grille_meta_box as $post_type => $value) {
        add_meta_box($value['id'], $value['title'], 'lt_grille_format_box', $post_type, $value['context'], $value['priority']);
    }
}

//Format meta boxes
function lt_grille_format_box() {
  global $grille_meta_box, $post;

  // Use nonce for verification
  echo '<input type="hidden" name="lt_grille_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" />';

  echo '<table class="form-table">';

  foreach ($grille_meta_box[$post->post_type]['fields'] as $field) {
      // get current post meta data
      $meta = get_post_meta($post->ID, $field['id'], true);

      echo '<tr>'.
              '<th style="width:20%"><label for="'. $field['id'] .'">'. $field['name']. '</label></th>'.
              '<td>';
      switch ($field['type']) {
          case 'text':
              echo '<input type="text" name="'. $field['id']. '" id="'. $field['id'] .'" value="'. ($meta ? $meta : $field['default']) . '" size="30" style="width:97%" class= "' .$field['class']. '" />'. '<br />'. $field['desc'];
              break;
          case 'textarea':
              echo '<textarea name="'. $field['id']. '" id="'. $field['id']. '" cols="60" rows="4" style="width:97%">'. ($meta ? $meta : $field['default']) . '</textarea>'. '<br />'. $field['desc'];
              break;
          case 'select':
              echo '<select name="'. $field['id'] . '" id="'. $field['id'] . '">';
              foreach ($field['options'] as $option) {
                  echo '<option '. ( $meta == $option ? ' selected="selected"' : '' ) . '>'. $option . '</option>';
              }
              echo '</select>';
              break;
          case 'radio':
              foreach ($field['options'] as $option) {
                  echo '<input type="radio" name="' . $field['id'] . '" value="' . $option['value'] . '"' . ( $meta == $option['value'] ? ' checked="checked"' : '' ) . ' />' . $option['name'];
              }
              break;
          case 'checkbox':
              echo '<input type="checkbox" name="' . $field['id'] . '" id="' . $field['id'] . '"' . ( $meta ? ' checked="checked"' : '' ) . ' />';
              break;
      }
      echo     '<td>'.'</tr>';
  }

  echo '</table>';

}

// Save data from meta box
function lt_grille_save_data($post_id) {
    global $grille_meta_box,  $post;
    
    //Verify nonce
    if (!wp_verify_nonce($_POST['lt_grille_meta_box_nonce'], basename(__FILE__))) {
        return $post_id;
    }

    //Check autosave
    if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
        return $post_id;
    }

    //Don't update on Quick Edit save
    if (defined('DOING_AJAX') ) {
	return $post_id;
	}

    //Check permissions
    if ('page' == $_POST['post_type']) {
        if (!current_user_can('edit_page', $post_id)) {
            return $post_id;
        }
    } elseif (!current_user_can('edit_post', $post_id)) {
        return $post_id;
    }
    
    foreach ($grille_meta_box[$post->post_type]['fields'] as $field) {
        $old = get_post_meta($post_id, $field['id'], true);
        $new = $_POST[$field['id']];
        
        if ($new && $new != $old) {
            update_post_meta($post_id, $field['id'], $new);
        } elseif ('' == $new && $old) {
            delete_post_meta($post_id, $field['id'], $old);
        }
    }
}

add_action('save_post', 'lt_grille_save_data');

Now here’s the menu category display page. Create a page named “archive-grille_menu.php” and upload to your theme directory. Replace the loop with this code:

(I listed the categories in two columns.)

	$args2 = array(	'orderby' => 'name',	'order' => 'ASC',	'style' => 'none',	'taxonomy' => 'grille_categories',	'echo' => 0,'title_li'  =>'' );
	$cats = explode("<br />",wp_list_categories($args2));
	$cat_n = count($cats) - 1;
	$cat_left='';
	$cat_right= '';
	for ($i=0;$i<$cat_n;$i++):
		if ($i<$cat_n/2):
			$cat_left = $cat_left.'<li>'.$cats[$i].'</li>';
		elseif ($i>=$cat_n/2):
			$cat_right = $cat_right.'<li>'.$cats[$i].'</li>';
		endif;
	endfor;
	?>

 Next is the display page for each category:

Remember to change the divs and styling to match your page layout.

 $meta['grille_menu_price2'][0];
			$label2= $meta['grille_menu_pricelabel2'][0];
			$sig=$meta['grille_menu_signature'][0];
			?>
			<div class="menuitem<?php if($count %2 == 0) echo ' odd' ?>">
				<div class="itemname">
					<h3><?php if ($sig) { ?><img src="<?php bloginfo('template_directory') ?>/images/sig-icon.png" style="display:inline-block"> <?php } the_title(); ?></h3>
					<div class="itemdesc"><?php the_content(); ?></div>
				</div>
				<div class="prices">
				<div class="price1">
					<?php if (!empty($label1)) {
						echo  '<p>'.$label1. '</p>';
						}
						echo '<strong>'.$price1.'</strong>'; ?>
				</div>
				<div class="price2">
					<?php if( !empty($price2)) {
						if (!empty($label2)) {
							echo '<p>'.$label2. '</p>';
						}
						echo '<strong>'.$price2.'</strong>';
					}?>
				</div>
				</div>
			</div>
		<?php endwhile; endif; 
		wp_reset_query() ?>
		</div>
		</div>

	</div>

 You can see this plugin in action at: http://paradisegrille.net.

 

 

Social Share Buttons Without a Plugin

July 1, 2014 (6 years ago)
WordPress, PHP

Most sharing plugins are too loaded with options, and tend to slow down my sites.

I wrote this simple script to counter that.

Create this file and name it “sharebuttons.php”. Upload it to your theme directory.

<div id="sharethis">
<h3 class="sharethis">Share This:
<a style="margin-right:5px;margin-left:10px;" rel="nofollow" href="http://www.facebook.com/sharer.php?u=<?php the_permalink();?>&amp;t=<?php echo urlencode(get_the_title($id)); ?>" title="Share this post on Facebook" target="_blank"><img src="<?php echo bloginfo('stylesheet_directory') ?>/images/fbuser.png"></a>
<a style="margin-right:5px;" rel="nofollow" href="http://twitter.com/home?status=<?php echo urlencode("Currently reading: "); ?><?php the_permalink(); ?>" title="Share this with your Twitter followers" target="_blank"><img src="<?php echo bloginfo('stylesheet_directory') ?>/images/twuser.png"></a>
<a style="margin-right:5px;" rel="nofollow" href="http://www.linkedin.com/shareArticle?mini=true&url=<?php the_permalink(); ?>" target="_blank"><img src="<?php echo bloginfo('stylesheet_directory') ?>/images/liuser.png"></a>
<a style="margin-right:5px;" rel="nofollow" href="https://plus.google.com/share?url=<?php the_permalink(); ?>" target="_blank"><img src="<?php echo bloginfo('stylesheet_directory') ?>/images/gplususer.png"></a>
<a style="margin-right:5px;" href="javascript:void((function(){var%20e=document.createElement('script');e.setAttribute('type','text/javascript');e.setAttribute('charset','UTF-8');e.setAttribute('src','http://assets.pinterest.com/js/pinmarklet.js?r='+Math.random()*99999999);document.body.appendChild(e)})());"><img src="<?php echo bloginfo('stylesheet_directory') ?>/images/pinuser.png"></a>
</h3>
</div>

You will also need to create your images, and style the div as you like.

 Then, to add the div to pages or posts, just put this in your template file, immediately following (or just before) the_content() — or wherever you want the buttons to appear:

<?php
include('sharebuttons.php');
?>

Custom Admin Page

July 1, 2014 (6 years ago)
WordPress, PHP, Functions

I use these for those occasions when I need to store specialized information in non-WordPress tables. (Such as orders in a custom shopping cart I built.)

It’s also handy for adding informational or instructional pages to the Dashboard.

This adds the page to the WP admin menu (put in your functions.php file):

// admin page for orders
add_action( 'admin_menu', 'lt_orders' );

function lt_orders() {
    add_menu_page( 'Orders', 'Orders',  'manage_options',  'lt-orders',   'lt_render', '', '3'   );
}
function lt_render() {
    global $title;
    print '<div class="wrap">';
    print "<h2>$title</h2>";
    $file = plugin_dir_path( __FILE__ ) . "lt_orders.php";
    if ( file_exists( $file ) )
        require $file;
    print '</div>';
}

 The page itself ( lt_orders.php ) resides in the theme folder, and is a simple PHP page, with any functionality you like. It doesn’t need any header or footer calls because it is rendered inside the admin.

Front End Login Form

June 20, 2014 (6 years ago)
WordPress, PHP, Functions

So many times clients (and their members) want to login on the front end. Simple to add this in the header, or sidebar. Style as you wish.

Put this in your header template (or anywhere else you want the form to appear.)

<?php if (!is_user_logged_in()) { ?>
	<form action="<?php echo get_option('home'); ?>/wp-login.php" method="post">
	<input type="text" name="log" id="log" value="<?php if (isset($user_login)) echo esc_html(stripslashes($user_login), 1) ?>" size="20" />
	<input type="password" name="pwd" id="pwd" size="20" />
	<input type="submit" name="submit" value="Login" />
	<input name="rememberme" id="rememberme" type="hidden" checked="checked" value="forever" />
	<input type="hidden" name="redirect_to" value="<?php echo home_url(); ?>" />
	<a href="<?php echo wp_lostpassword_url( home_url() ); ?>">Forgot password or username?</a>
	</form>
<?php } else { 
	global $current_user;
	get_currentuserinfo(); ?>				
	<p>Welcome, <?php if($current_user->user_firstname) echo $current_user->user_firstname; else echo $current_user->display_name; ?>!</p>
	<a class="button" href="<?php echo wp_logout_url( home_url() ); ?>">Logout</a>
<?php } ?>

 

Upload and Rename a File

June 20, 2014 (6 years ago)
PHP, Functions

I have a couple of applications where users need to upload files regularly, and have them renamed and placed into a specific directory. (These applications run independently from WP, so this is just straight PHP.

The form:

<form action="testupload.php" method="post" enctype="multipart/form-data">
<input type=hidden name="filename" value="renamed.pdf">
<label for="file">Filename:</label>
<input type="file" name="file" id="file" />
<br />
<input type="submit" name="submit" value="Submit" />
</form>

 The processing page:

<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {

if ($_FILES["file"]["error"] > 0)
  {
  echo "Error: " . $_FILES["file"]["error"] . "<br />";
  }
else
  {
  echo "Upload: " . $_FILES["file"]["name"] . "<br />";
  echo "Type: " . $_FILES["file"]["type"] . "<br />";
  echo "Size: " . ($_FILES["file"]["size"] / 1024) . " Kb<br />";
  echo "Stored in: " . $_FILES["file"]["tmp_name"];
  }

      if (file_exists("scholarships/" . $_FILES["file"]["name"]))
      {
          unlink ("scholarships/" . $_FILES["file"]["name"]);
      }
      move_uploaded_file($_FILES["file"]["tmp_name"],"scholarships/" . $_POST["filename"]);
      echo "File uploaded and renamed" ;

    
     } else {
     echo "File not uploaded";
}
?>

 

Skip to toolbar