Category: WordPress

Combo image function

I created this to stack two images horizontally together, to make before and after images into one image. Designed for WordPress, but could be tweaked for other systems.

/**
 * use two images to create one image
 */
function msdlab_combine_images($params){
	extract(
		array_merge(
			array(
				'images' => array(),
				'orientation' => 'horizontal',
				'output_format' => 'jpg'
			)
		,$params)
	);
	//get info on each image
	foreach($images AS $key => $url){
		$imgs[$key]['url'] = $url;
		$imgs[$key]['path'] = $path = realpath(preg_replace('@'.site_url().'@i','.',$url));
		$imgs[$key]['file'] = $file = basename($path);
		$imgs[$key]['filename'] = $filename = preg_replace('/\.(?:jpg|jpeg|bmp|png|gif)/i','',$file);
		$imgs[$key]['info'] = $info = getimagesize($path);
		$comboname .= $filename;
		switch($orientation){
			case 'horizontal':
				$combowidth = $combowidth + $info[0];
				$comboheight = $info[1]>$comboheight?$info[1]:$comboheight;
				break;
			case 'vertical':
				$combowidth = $info[0]>$combowidth?$info[0]:$combowidth;
				$comboheight = $comboheight + $info[1];
				break;
		}
	}
	$comboname .= '.'.$output_format;
	$upload_dir = wp_upload_dir();
	//check if it exists
	if(file_exists($upload_dir['basedir'].'/'.$comboname)){
		return $upload_dir['baseurl'].'/'.$comboname;
	}
	//create a holding image
	$newimg = @imagecreatetruecolor($combowidth, $comboheight);
	foreach($imgs AS $key => $img){
		switch($img['info']['mime']){
			case 'image/jpeg':
				$src = @imagecreatefromjpeg($img['path']);
				break;
			case 'image/png':
				$src = @imagecreatefrompng($img['path']);
				break;
			case 'image/gif':
				$src = @imagecreatefromgif($img['path']);
				break;
			default:
				return 'unsupported file type';
		}
		//copy things
		switch($orientation){
			case 'horizontal':
				imagecopy($newimg, $src, $imgs[$key-1]['info'][0], 0, 0, 0, $img['info'][0], $img['info'][1]);
				break;
			case 'vertical':
				imagecopy($newimg, $src, 0, $imgs[$key-1]['info'][1], 0, 0, $img['info'][0], $img['info'][1]);
				break;
		}
		// free up memory
		imagedestroy($src);
	}
	// Save the image
	imagejpeg($newimg, $upload_dir['basedir'].'/'.$comboname);

	// Free up memory
	imagedestroy($newimg);

	//return the image
	return $upload_dir['baseurl'].'/'.$comboname;
}

Allow all Embeds

add_action('init','msd_allow_all_embeds');
function msd_allow_all_embeds(){
	global $allowedposttags;
	$allowedposttags["iframe"] = array(
			"src" => array(),
			"height" => array(),
			"width" => array()
	);
	$allowedposttags["object"] = array(
			"height" => array(),
			"width" => array()
	);

	$allowedposttags["param"] = array(
			"name" => array(),
			"value" => array()
	);

	$allowedposttags["embed"] = array(
			"src" => array(),
			"type" => array(),
			"allowfullscreen" => array(),
			"allowscriptaccess" => array(),
			"height" => array(),
			"width" => array()
	);
}

Move meta box above editor

add_action('admin_footer','subtitle_footer_hook');
function subtitle_footer_hook()
{
	?><script type="text/javascript">
	jQuery('#titlediv').after(jQuery('#_speaker_title_metabox'));
	jQuery('#_speaker_title_metabox').after(jQuery('#_speakers_metabox'));
	</script><?php
}

Remove MS Word Formatting

I recently noticed that this can cause issues with embeds, if they aren’t previously defined as allowed.

add_filter( 'the_content', 'msd_remove_msword_formatting' );
function msd_remove_msword_formatting($content){
	global $allowedposttags;
	$allowedposttags['span']['style'] = false;
	$content = wp_kses($content,$allowedposttags);
	return $content;
}

Flawless integration of Gravity Forms with Salesforce

This is trickier than using a plugin, but more flexible and allows for specificity that it’s available otherwise, as far as I can tell.

The original article is at http://www.seobywebmechanix.com/wordpress-salesforce-integration-gravity-forms-web-to-lead

I’m re-blogging the pertinent bits in case something happens to it.

Let’s Get Fancy (In a Sophisticated Way)

Hop into your SalesForce and click “Settings” from the menu that drops down when you click your name from the upper right of the screen.

In the settings menu, under “App Setup” on the left hand side, click “Leads” to drop down another list, and then choose “Web-To-Lead” from there.

You should have a screen that looks like this:

Web To Lead SalesForce CRM Integration

Click “Create Web-To-Lead Form” to get started.  The next screen will ask you which data fields you want to capture.  Choose wisely.

Web To Lead Fields To Capture

The “Return URL” is equivalent to your “Thank You Page” – the page you’d like the user to see after they’ve submitted the form.  Don’t forget to set up a Google Analytics goal for that thank you page.

When you click “Generate”, SalesForce is going to give you some HTML code.  This code generates a contact form on your website that sends its data to SalesForce.

SalesForce Web To Lead Form HTML

I know what you’re thinking: “Wait, I use Gravity Forms to create contact forms on my website but how do I sync or integrate Gravity Forms with SalesForce Web-To-Lead?”

That is a good question; keep reading for the answer.

………

Step 4: Sync Gravity Forms To SalesForce

To do this, click the Gravity Form’s name and find the “Confirmation” tab.  Click into that tab, and then change the “Confirmation Message” to “Redirect”.

After that, click “Pass Field Data Via Query String” – Your screen should look something like this:

Gravity Forms Confirmation Tab

Here’s the hard part… do you still have your SalesForce Web-To-Lead HTML handy?  You need it now.

Let’s dissect the SalesForce HTML:

SalesForce Web-To-Lead Gravity Form Configuration

Note: I removed all the commented HTML code (anything wrapped with <!– –>)

You want to fill out your Gravity Forms as follows:

1 – The URL to “Redirect” your Gravity Forms data to

2 – Hidden field that is your SalesForce company ID (I changed ours to all zeros to prevent spam)

3 – Hidden Field that is the “Return URL” or “Thank you page” that the user will see after filling out the form (remember putting this in when you were creating your Web-To-Lead form?)

4 through 9 – These are the fields you want to pass over to SalesForce.

Put the URL (#1) in the single field directly under the “Redirect” radio button you choose earlier.

Here is where most people make a mistake, so be careful.

Step 5: Build Your “Query String”

IMPORTANT: From the action URL (#1 in picture above) – you must remove “?encoding=UTF-8” and put it as the first variable in your query string (see images below).

There must NOT be a “?” in the REDIRECT URL (because Gravity Forms will automatically append one to the start of the query string).

Starting with oid and retURL (#2 & #3) – let’s start building our “query string” which passes the contact form’s data to SalesForce.

Building Query String to send data to SalesFoce

Here is the general format for building the query string:

field_name=field_value&2nd_field_name=2nd_field_value

field_name – just as it sounds; the name of the data field (ie. “company”)

field_value – again, just like it sounds; this is the value (ie. “WebMechanix”)

Important note: Did you notice that ampersand (&) between field_value and 2nd_field_name? – That “&” separates each field name and value combination.

Now, for the rest of the fields (#4 through #9), use the “Insert Form Field” drop down that Gravity Forms provides.

For the field_name portion of the query string, use the bolded “name” field from the SalesForce Web-To-Lead HTML (ie. #4 would be first_name, #6 would be email, and #9 could be state).

 

Gavity Forms Field Picker Drop Down
Final Query String within Gravity Forms

Here is our final query string:

encoding=UTF-8&oid=0000000000000000&retURL=http://www.seobywebmechanix.com/thank-you&first_name={Name (First):2.3}&last_name={Name (Last):2.6}&email{Email:4}&company={Company:5}&city={Address (City):1.3}&state={Address (State / Province):1.4}

Few things to note:

  1. MAKE SURE you remove the encoding=UTF-8 out of the redirect URL
  2. You have to type the field_name yourself (those that are bolded), which you get by looking at the SalesForce form.
  3. When you use the Gravity Forms “Insert Form Field” picker, it puts {curly brackets} around where the field value is going to be dynamically inserted.
  4. Don’t forget the “&” between field name and value combination, but don’t put one at the very end

Step 6: Save It & TEST!

……..

Changing post restrictions in the DB.

$s2data = get_option('ws_plugin__s2member_options');
if($s2data['level1_posts']==''){
	$recipes = get_posts(array('numberposts' => -1,'post_type' => 'msd_recipe'));
	foreach($recipes AS $r){
		$protected[] = $r->ID;
	}
	$s2data['level1_posts'] = implode(',', $protected);
	update_option('ws_plugin__s2member_options', $s2data);
	print 'recipes protected';
}

Video Wall Page Template

This goes into the top of the template. You could put it in a plugin, but then it loads everywhere, so…

<?php
/*
Template Name: Video Wall Page
*/
global $slug;
global $content_width;
$content_width = 468; //edit to correct width for your template
/**
 * @desc use any youtube embed param as an att. https://developers.google.com/youtube/player_parameters
 * @param array $atts
 * @return string
 */
function add_video_wrapper($atts){
	extract( shortcode_atts( array(
	'title' => ' ',
	'url' => '',
	'class' => '',
	), $atts ) );
	unset($atts['title']);
	unset($atts['url']);
	unset($atts['class']);
	return '<div class="video '.strtolower($class).'">'.wp_oembed_get($url, $atts).'<h5>'.$title.'</h5></div>';
}
add_shortcode('video','add_video_wrapper');

/**
 * @desc Add additional parameters to oembed returns
 * @param string $html
 * @param string $url
 * @param string $args
 * @return mixed
 */
function videowall_add_params($html,$url,$args){
	foreach($args AS $k=>$v){
		$argstr .= '&'.$k.'='.$v;
	}
	$html = preg_replace('/&feature=oembed/i',$argstr.'&feature=oembed',$html);
	return $html;
}
add_filter('oembed_result','videowall_add_params',10,3);
remove_filter( 'the_content', 'wpautop' );
wp_enqueue_style('videowall-css',get_stylesheet_directory_uri().'/css/videowall.css');

And the LESS:

.page-template-page-videowall-php{
	.hentry {
		margin-bottom: 10px;
		.entry-title {
			margin-bottom: 1em;
			}
		iframe { display: block; }
		.video {
			border: 1px solid #EDEDED;
		    float: left;
		    margin: 0 12px 24px;
		    width: 450px;
		    }
		.video h5 {
			padding: 4px 12px;
			margin: 0;
			}
		.entry-utility {clear: both;}
		}
}

Loopy Post Navigation

Make posts loop back around to the other end:

<?php
function apple_post_navigation()
{
	global $post;

		$categories = get_the_category( $post->ID );
		$category = $categories[0]->cat_name;
		$last_post = get_boundary_post( TRUE, '', FALSE );
		$first_post = get_boundary_post( TRUE, '', TRUE );
		?>
    <div class="prev_next">
        <div class="nav_left">
            <span class="prev">
            <?php 
            if(get_adjacent_post(TRUE, NULL, TRUE)){
				previous_post_link('%link', '< Previous '.$category , TRUE);
			} else {
				print $last_post->ID;
				print '<a rel="last" href="'.get_permalink($last_post[0]->ID).'">< Previous '.$category.'</a>';
			}
			 ?>
            </span>
         </div><div class="nav_right">
            <span class="next">
            <?php 
            if(get_adjacent_post(TRUE, NULL, FALSE)){
				next_post_link('%link', 'Next '.$category.' >' , TRUE);
			} else {
				print $first_post->ID;
				print '<a rel="first" href="'.get_permalink($first_post[0]->ID).'">Next '.$category.' ></a>';			
			}
			 ?>
			 </span>
        </div>
    </div>
<?php

}
?>

WPAlchemy Data Storage Modes

Be careful to do this to make data searchable. Out of the box WPAlchemy uses WPALCHEMY_MODE_ARRAY which is not very useful for meta searches!

$custom_metabox = new WPAlchemy_MetaBox(array
(
    'id' => '_custom_meta',
    'title' => 'My Custom Meta',
    'template' => TEMPLATEPATH . '/custom/meta.php',
    'mode' => WPALCHEMY_MODE_EXTRACT,
    'prefix' => '_my_'
));

If you forget, use this:

    if ( ! function_exists( 'msd_convert_storage' ) ) :
            function msd_convert_storage($key,$prefix,$posttype) {
                    $args = array(
                        'numberposts'     => -1,
                        'post_type'       => $posttype,
                    );
                    $items = get_posts($args);
                    foreach($items AS $item){
                            $the_meta = get_post_meta($item->ID,$key);
                            $fields = array();
                            foreach($the_meta[0] AS $meta_key => $meta_value){
                                    $meta_key = $prefix.$meta_key;
                                    update_post_meta($item->ID, $meta_key, $meta_value);
                                    $fields[] = $meta_key;
                            }
                            update_post_meta($item->ID,$key.'_fields',$fields);
                            delete_post_meta($item->ID,$key);
                    }
            }
    endif;