Archive for Wordpress

User Proof Repeater Images

So lets talk about proper image implementation.

We sometimes run into clients who would like slideshow galleries while uploading 2000-5000px wide images. And it’s important to understand that content managers are not going to KNOW what a proper image size is. So how do you maintain a nice easy consistent image query AND meet your client where they currently stand on knowledge of the web?

The set up for this image query is as follows:

I’ve seen a lot of queries that look like this.

<img src="<?= the_sub_field('image'); ?>" />

You would then set the height and the image in CSS

But lets challenge that. Does that offer the best quality for the end user? Those obviously allow for large images to be loaded and slow down your site, right?

Lets use a different query that will allow for faster loading.

<? $image = get_sub_field('image'); $image = wp_get_attachment_image($image, 'medium'); ?>
   <?php echo $image; print_r($image); ?>

So this should be the proper way to load fast images. You can change the size to whatever size you need.

This way when your site owners decide to load a large sized image, it won’t ruin your design or your load speed.

CSS Only Drop Down Menus for WordPress

So you want to create a menu with a drop-down for WordPress. The challenge in this is that the formatting needs to happen on the submenu when the parent item is selected. This is where the cascading part of stylesheets comes in. Assuming you know how to work with classes and set up menus (at least whatever part WordPress doesn’t do automatically for you.), there are two basic steps left.

1. You need to hide the <li> items in the dropdowns. Make sure you use the hierarchy and don’t assign them their own class. If you try working with a class rather than the hierarchy, you won’t be able to make them reappear with CSS only.

 

.nav ul.menu-class ul li {
display:none;
}

2.Once you have successfully hidden the navs, you’ll need to make them show up again when the hover property is activated.

.nav ul.menu-class:hover ul li {
display:block;
}

The rest of your formatting will vary, depending on whether you want it to show up horizontally or vertically, but the main thing is to target the parent

    and change the
  • of the sub menu using the hierarchy.

Creating Posts from Formidable Form requests.

Recently I have been wanting to generate user created posts from a project I have been working on in WordPress.

One functionality that I came across was using Formidable to create posts. I’m not sure if this is the BEST action for what I want specifically, but I can give you a run down of how this works. We will cover how to create a post, and how to query items from the posts, specifically custom fields created by a formidable form.

So what do we do first?

I had a lot of things going on with my idea which involved uploading photos, using image filters and posting to custom post types. We can get into that later. Lets start with the basics. And maybe an image uploader ;) .

1: Create a form for all the content. Lets use the following fields.

  • Title (single line text field)
  • Content (Rich Text Field)
  • Image (File Upload)
  • Any custom field you want! :D

2: Go to the settings section of your form.

3: Under settings you should see a “create posts” side-tab, go to that side tab and it should give you the instructions on how to create a post.

4: Specify the post variables

  • Post Type
  • Post Title (can be Title Field)
  • Post Content (Content Field)
  • ect.

5: To add custom fields, be sure to go to the bottom and click “Add” under the custom fields section.

6: Create a custom field that is your image field. Send that on to the post.

Now here is the kicker. You need to show your post image in your actual post.

So create a new post content file. something like content-imageuploads.php or something like that.

Now set the content up any way you want.

To call your image, here is your code.

$postMeta = get_post_custom(get_the_ID());
foreach ($postMeta['Image'] as $image => $value)
{
	echo '<img alt="" src="'. wp_get_attachment_url($value) .'" width="600" />';
 
}

WordPress Stylesheet Missing in Safari

This is an interesting situation. You might have migrated your blog lately or your hosting provider moved your database somewhere and all the sudden your WordPress blog is no longer showing up in Safari. It may work fine in Chrome and Firefox, but is irritatingly missing from Safari. A check in the code reveals that your stylesheet URL has an extra space added before the relative part of the link. For some reason, this space doesn’t seem to bother the other browsers, but only Safari.

The fix is even more simple than the diagnosis. In order to fix it, you will need to get into the database and change one of the lines of the wordpress options table, where the site URL is given. In my case, there was a hidden return character, but it could have just as easily been a space after the URL. Once this space is removed, you should be well on your way to a working stylesheet, if not already there.

If you don’t have access to the database or you would rather make a more simple fix, edit the wp-header page and instead of the bloginfo() function, type in the direct link (relative link is preferred here) to the stylesheet.

Limit Character Count in ACF Repeater Text Field

Limiting the characters in a given field is a good way to dummyproof your admin dashboard so content writers don’t write novel length entries for a field that should only be a few words. This could have consequences such as ruining the integrity of the design and brand the company wishes to achieve. So limiting the length of the content they can write is a good way to make sure things like that don’t happen.

However, this is not a feature supported by the ACF plugin at the moment. So there is a work around that can get the desired effect until they do. Just put this code in your functions.php file:

<?php function my_head_input() { ?>
<script type="text/javascript">
jQuery(function(){
    jQuery('.repeater textarea').css("min-height","5px");
    jQuery('.repeater textarea').on('keyup', function(){
    var characters = 30;
    if( jQuery(this).val().length > characters ){
      jQuery(this).val(jQuery(this).val().substr(0, characters));
      return false;
    }
  });
});
</script>
<?php }
add_action('acf/input/admin_head' , 'my_head_input' );
?>

this solution was tailored to the textarea fields of all repeater fields. You can play with the jQuery selector to affect the fields you desire
Source

Can’t Update in WordPress – Missing Archive File

Working on a lot of WordPress sites, I’ve never encountered this till this point. The first clue was that I couldn’t just install plugins from the plugin library, i had to install them manually. However, updating had the same problem. Noted, this was the first wordpress site we had installed on a windows server, so that probably messed with how plugins in WordPress work. Anyways, manually doing things is a bit time consuming so I looked into the error…

(-4) : Missing archive file ‘C:\Windows\TEMP/formidable-1.tmp’

The solution turned out to be pretty simple

  1. You need to ftp your server. Inside the wp content folder, create a new directory/folder called TEMP.
  2. open the wp-config.php in the root directory and enter the following code at the bottom (remember the semicolon ^_^)
define('WP_TEMP_DIR', ABSPATH . 'wp-content/TEMP');

That’s it! You can install and update plugins with no problems
[Source]

Ajax calls in WordPress.

Lets discuss ajax calls in WordPress.

I’ve seen some tutorials on this but many seem to have issues. Some seem to not even work.

Here I’m going to post my solution to hitting ajax in WordPress.

This is really important for large pages on sites that require mobile support. The main reason is that Mobile Safari has a 8mb memory cap. So other than the obvious ideas of enhancing performance, we also are able to make large pages mobile friendly without KAPOOING Mobile Safari.

Lets get to it.

We are going to write a JSON that returns html content to place inside of a div.

First things first, set up a site. Enable jQuery and lets make it the latest version of jQuery, because we want to use the “data” attribute and some older versions don’t really support it.

Now set up a page and set a wrapper where you want to put all your JSON html content. I’m going to assume you got that covered ;) .

Ok so now set up your JSON handler. What I did was created a page with a Template Name which i called JSON Handler.

The code I used was this.

$page = (isset($_GET['post_id'])) ? $_GET['post_id'] : 0;  
 
			$count = 0;
			$args = array(
			 'post_type'  => "Portfolio",
			 'showposts' => 99,
			 'p' => $page,
			 'posts_per_page' => 1
			);
			query_posts( $args );
			while ( have_posts() ) : the_post(); $count++; ?>
<div class="item<?= $post->ID;?> portfolioInfo">
            <div class="closeSlide right">x</div>
			<? if( get_field('screenshots') ): ?>
            	<div class="slider">
            	<div class="flexslider flexslider<?= $post->ID;?>"><ul class="slides">
					<?php $count = 1; while( has_sub_field('screenshots') ): ?>
							<li><img src="<?php the_sub_field('image'); ?>"/></li>
					<?php $count++; endwhile; ?>
                </ul></div>
                </div>
			<?php endif; ?>
 
			<div class="portfoliotitle"><? the_title()?></div>
            <? the_content();?>
            <?php endwhile; // end of the loop. ?>
            <? wp_reset_query(); ?>
</div>

Ok so thats the specific markup I needed to return what I wanted. Which was a slideshow with some content.

You can make whatever markup fits your needs.

Now make a page and set it’s template to be the template of JSON handler… maybe even call it JSON Handler.

Now comes the javascript.

My main caller function will look like this.

function callSliderInfo(postID) 
	{
 
		 $('html,body').animate({ scrollTop: $('#slideInfoMain').offset().top}, 500);
		 $(".slideInfo").append('<div class="loading"><div class="loadingImage"></div></div>');
		 var stringID = JSON.stringify(postID);
		 var loading = true;
		 var $window = $(window);
		 var $content = $('body.blog #content');
 
            $.ajax({  
                type       : "GET",  
                data       : {post_id: postID},  
                dataType   : "html",  
                url        : "/json-handler",  
                beforeSend : function(){  
                },  
                success    : function(data){  
					$(".slideInfo").html('');
					$(".slideInfo").append(data);
 
					var flexslider = ".flexslider"+parseInt($(this).attr('id'),10);
					initFlexSliders();
					$('.closeSlide').click(closeSlide);
                },  
                error     : function(jqXHR, textStatus, errorThrown) {  
                    alert(jqXHR + " :: " + textStatus + " :: " + errorThrown);  
                }  
        });
 
	}>

Notice how i have postID as my variable input. A few other things i have there are my flexslider function, and my close button.

Not you have your main function lets decide how you call it.

Have and divs or buttons you want with the data attribute “id” and make the id = the post id you want to return.

Now lets call our main ajax function.

$(document).ready(function(){  
 
$(".CallButton").click(function(){ callSliderInfo($(this).data("id")); });
 
});

Once you have that it will trigger the ajax call to your wordpress template and return whatever it is you told it to return.

Please let me know if you have any questions.

Best mobile plugins for WordPress?

Now we mainly go for responsive design and development around here. We use the Foundations Framework mainly. But every now and then a mobile design spec comes along that requires different page layouts and queries and completely different wireframes.

This is when we decide to branch off to new themes and let a little plugin called Any Mobile Theme. This theme is based around getting the users device type and changing the theme being used depending on what the user is using. It has everything from iPhone to Opera Mini and allows you to select specific themes depending on what device is being used.

Simply upload and install Any Mobile Theme. Activate it. Then go to “Settings : Any Mobile Theme” and select which theme you want to substitute for mobile.

All plugins and Database settings will be the same, but now you have have completely separate layouts as well as using fun protocol links like the fb:// i mention in my other posts.

Events Lists in WordPress.

So you want to make an events list in WordPress? There is a lot to do! First off lets define how this should work. Since I’m writing this blog I’ll tell you how mine works and then you decide if it’s how you want YOURS to work.

  1. It’s going to be a dynamic list.
  2. It’s going to pull events from an Event content type.
  3. It’s going to order them by date, newest on top.
  4. It’s going to display all the info for other people.

Ok so what do we need to set this up?

First find a way to create content types. I use the Custom Post Type UI plugin. This is a very good easy to use plugin that will do all that you need it to do.

Secondly, we need to be able to add specific fields into the post type. I strongly recommend using Advanced Custom Fields plugin. The main reason for this is that you are going to want to Repeater Fields and inside those store all your info, including a “date” input type.

Ok so create your custom field types inside your posts. Set a date as an Advanced Custom Field and remember where you put it.

Once you have a good list in the database it’s as simple as Querying.

 

<? if ( get_query_var('events') ) $paged = get_query_var('events');
$query = new WP_Query( array( 'post_type' => 'Events', 'paged' => $paged, 'orderby' => 'meta_value','meta_key' => 'date', 'order' => 'ASC', 'posts_per_page' => -1 ) );
$now = date("Ymd");
?>

Ok so you will notice a few things about this code.

  1. I use an orderby metavalue command.
    This is so that we can order by date. Advanced Custom Fields will have all it’s fields available as metadata so you can orderby          different things. In our case it’s a date.
  2.  I created a “date” variable called “now”.
    This is so I can filter out events that already happened from appearing to the user. It’s incredibly important to have the format be YMD so that you can do straight data comparisons.

So now that we have the query set up we are all but ready to start incorporating it into our theme. All we need to know is what to print from what is being queried.

 

<?php while ( $query->have_posts() ) : $query->the_post(); ?>
 
<? $date = DateTime::createFromFormat('Ymd', get_field('date')); ?>
<? if($now > $date->format("Ymd")) {  }else{ ?>

Ok so now you notice how we make the custom field “date” into an object named date and we check to see if “now” is greater than “date” who is also formatted as YMD.

This is going to call all events that are happening anytime farther that right at this very millisecond.

After this build your content any way you wish and watch the magic happen!

Put Templates in your Template so you can Theme while you Theme!

I heard you like templates!

We were making a site that called several different pages on one page. It also required that the markup be different for different types of pages.

We ran into an issue with both is_page_template(); and get_page_template();. The templates went from root which didn’t help our code for both a development server and a product server.

After a meeting where we talked over all our options the group came to a decision. They decided to make me do it.

I wanted to avoid includes and use mainly WordPress functions.

The defining function I used was

 
if (get_post_meta( get_the_ID(), '_wp_page_template', TRUE ) == "page-templates/full-width.php") {

This would get the page template from site root and not server root. Of course this helps when dealing with different servers and it’s always good to root from the site root.

After that I just insert all my markup and do and elseif for the next template. I will look into a way to reference page content from different template files and get back to you. It’s a work in progress at the moment.