To Do: Efficient, Future-Friendly Front End Strategy

Here’s a list of links of stuff I need to look into and implement.

Fluid layout, responsive design, grid layouts, efficient CSS, mobile first strategy, reusable jquery tools.

Object Oriented CSS

stubbornella.org
Object Oriented CSS on Github
http://net.tutsplus.com/tutorials/html-css-techniques/object-oriented-css-what-how-and-why/
https://github.com/stubbornella/oocss/wiki
CSS Lint
LESS and SASS

CSS Grids

http://www.1kbgrid.com/
http://cssgrid.net/
http://www.52framework.com/

Responsive Web Design

http://www.abookapart.com/products/mobile-first
http://www.abookapart.com/products/responsive-web-design
http://designmodo.com/responsive-design-examples/
http://www.alistapart.com/articles/responsive-web-design/

JQuery Tools Library

http://flowplayer.org/tools/
http://jquerymobile.com

Microformats

http://microformats.org/wiki

Posted in css, web design | Leave a comment

An Event Apart SF 2011 – Resources and Sound Bites – Part 2

all presentations: http://aneventapart.com/2011/sanfrancisco/slides/

Using Flexible Boxes – Eric Meyer, author, CSS: The Definitive Guide, 3rd Ed.

flexible boxes are sort of like tables, but behave much better and do cooler things.

starting with: a list with list items (boxes of content, should align side by side).
on ol:
using display:box on the parent element makes all of its child elements also have display:box;
box-orient:horizontal;
box-pack:center /* only supported in webkit */

on li:
set a background color, then all the elements will match in height.
box-flex:1; /* sets flexible boxes. */

each box will get the same amount added (or subtracted) to it to fit the containing space.

for flex to be applied: you take the amount of space left over, and divide by the total number of box flex numbers, and apply the designated amount to each box. (could have box-flex:2 etc. which would get that box 2 parts assigned.)

box-ordinal-group: 2. could make a bunch of boxes 2, then give another one say class “sticky” of box-ordinal-group: 1, then it will always stay at the beginning of the list of boxes.

You can turn your whole page into a flex box, and use ordinal groups to rearrange content for mobile, etc. (put nav at the bottom, for example).

what to do with browsers that don’t support flexible boxes?
float it. This doesn’t solve all the problems though, for example equal height is not possible, or ordinal groups.

2011 flexible box specification has lots of new stuff

Our Best Practices are Killing Us – Nicole Sullivan, co-author, Even Faster Websites

stubbornella.org
Object Oriented CSS on Github

use grep to find problems with css.
use CSS Lint to find errors and duplication

usecases

facebook css was 1.9MB. Facebook blue was declared 261 times. 548 unique colors (whaaa?). color: was declared 6498 times.

salesforce: over 5000 padding declarations.

Duplication is a serious problem esp. with font size, floating, padding

alexa top 1000 consumer site study –
worst examples: 518 !important
733 floated elements – look at a grid based layout system!
889 font-size declarations

Myths

Using px is bad

using px is ok. only ie6 doesn’t support page zoom, which is the only reason not to use px. Using em’s turns into a mess because of nesting. It is hard to predict results, so it causes bugs. If you don’t support ie6, there is really no reason not to use px font sizes. Only use em’s or percentages on body and leaf nodes (if you must use them at all), no where in between.

Less markup is good

Less markup is good, but don’t go so far that doing so causes bugs. Surrounding a list by a div is ok, if it solves problems.

Semantic Markup is essential

css is too tightly coupled with the content. can semantics be taken too far? classes and id’s are not read by anybody besides other developers. So let’s make them work for us. For CSS, more is not better. Do not repeat yourself!

CSS pattern abstraction: “the media block“. (image on the left, some content on the right)
what we know:
can be nested
optional right button
must clearfix

don’t know:
image width, decoration
right content is unknown
width is unknown

separate structure from chrome

Is performance the most important thing

No. More important is repetition, duplication, legacy code.

Choose semantic elements: headings, lists, paragraphs
Abstract the css as much as possible from style and content.
http://net.tutsplus.com/tutorials/html-css-techniques/object-oriented-css-what-how-and-why/
https://github.com/stubbornella/oocss/wiki

Too many classes is bad

Uses more classes is actually faster and avoids duplication than using descendent selectors only. Using a class is more specific than using elements.

Specificity grows over time. Difficult to tell which rules take precedence.

Over time – specificity and duplication grows.

Use semantically correct headings in html, add class names to each one in css so you can apply visual semantics. (h1, .h1 {blah}).

Avoid descendent selectors whenever you can. Because those elements might not always be in that same situation. Make “reusable lego pieces”. Add class directly to elements you want to change, not parent nodes.

There are two main principles [in object-oriented CSS]: the first is to separate the structure from the skin and the second is to separate the container from the content.

greg’s notes on this talk

Idea to Interface – Aarron Walter, author, Designing for Emotion

greg’s notes. i failed.

Smoke Gets In Your Eyes (css3 animations) – Andy Clarke, author, Hardboiled Web Design

css animation fits better with semantic meaningful markup than other ways of web animation.

css3 animation demo studiohttps://developer.mozilla.org/en-US/demos/tag/tech:css3/

http://animatable.com/
http://animatable.com/demos/madmanimation/

transitions are basic animations.

@keyframes create more advanced animation effects.

@keyframes fade {
0% {opacity:0;}
25% {opacity:.5;}
100% {opacity:1;}
}

.lamp {
animation-name: fade;
animation-duration: 6s;
animation-delay:1500ms;
animation-iteration-count: 1;
transform: rotate(5deg);
}

css3 transforms

apply transforms and combine with keyframe animations to create effects.
translate (move)
rotate
scale
skew

greg’s notes (have more code samples)

A Content Strategy Roadmap – Kristina Halvorson, author, Content Strategy for the Web

content strategy resources

Content First – we can all agree on that. Content Always

Content isn’t copy. Content first is not copy first.

What we need is “content strategy” in the project framework
Content strategy plans for the creation, delivery and governance of useful, usable content.

what,why,how,when, for whom, with what, where, how often, what next

content components: substance, structure
people components: workflow, governance

how will your content serve your business and your users?

get away from the “launch it and leave it” strategy

it should enter a content lifecycle that goes around and around until the content is DELETED: >strategy>plan>create>maintain>audit>

Discovery

content audit: what do you have, what is it, where is it, what is it for. Also a good chance to update your meta title, desc. and keywords. A good person to do this task is the copywriter or “content wrangler”.

content ROT (redundant, outdated, trivial). REMOVE IT.
content readability, stakeholder agendas, legal requirements, style guides, metadata integrity, workflow and timelines, content owners

Define

content requirements
pair our business objectives with what the user expects and desires
content wrangler works with UX to create a “core message” that should guide the content requirements. Bring the copywriter in at the beginning of the content strategy process!

short and simple styleguide to demonstrate the copy voice matches the personality of the “core message”. This can be one page long.

editorial calendar – start this early and make it realistic based on the facts of the resources available.

make “page tables” which are templates for people to deliver content. Templates would include: key message, objective, priority, maintenance, source material. This will make it easier for content creators to give you what you want, and keep with the content objectives at all times.

Develop

html, qa, content upload, seo implementation, authoring conventions, data model, system integration

content inventory, upload, styleguide, seo guidelines, error messages, metadata, training materials, content qa plan

After Deployment. Maintain and Care

Maintain and care for the content, audit it, revisit, revise, keeping it with your core message

responsive content

Structure content to be modular for use across different devices. Think of your content objective, not the form that it lives in. Always keep with your core message, prioritize the content.

The Secret Lives of Links – Jared Spool, Founding Principal, User Interface Engineering

oops I got tired.
links. make them go where people want, make them look good but still like links, use trigger words to help people go where they want (hint: a trigger word is what they would put in the search bar).
Avoid back button and pogosticking (back and forth between the information hierarchy)

Posted in Uncategorized, web design | Leave a comment

An Event Apart SF 2011 – Resources and Sound Bites – Part 1

All presentations: http://aneventapart.com/2011/sanfrancisco/slides/

Content First! – Jeffrey Zeldman, author, Designing With Web Standards, 3rd Ed.

Good Design Begins With Content
http://www.readability.com/

Progressive Enhancement – Add Layers of Experience
http://easy-readers.net/books/adaptive-web-design/

Responsive Web Design
http://www.abookapart.com/products/responsive-web-design
http://designmodo.com/responsive-design-examples/
http://www.alistapart.com/articles/responsive-web-design/
http://10k.aneventapart.com/
http://futurefriend.ly

“Mobile First” Approach – Design for mobile first, then go up. Do we need all that crap?

With Great Power Comes Great Responsibility – Elliot Jay Stocks, author, Sexy Web Design

nizoapp.com
benthebodyguard.com
http://www.nikebetterworld.com/

awesome design inspiration: http://siteinspire.com/

Distraction of the ‘Real’
Am I using an effect that makes something on the page look real. If so, why?
It’s about considering the context.

Typography is (Almost) Everything

More fonts is not better
Learn from print design
http://8faces.com/

http://www.alistapart.com/articles/settingtypeontheweb
http://baselinecss.com/
Tim Brown: More Perfect Typography
Typecastapp.com

Working from the typography outwards. Good typography and layout is important. All the fancy stuff can be added later (shadows, border radius, glossy), it’s not as important.

ilovetypography.com/sayonara-2010

Use your powerful tools wisely.

HTML5 Design Principles – Jeremy Keith, author, HTML5 For Web Designers

all his resources and principles: principles.adactio.com

design principles: how
design goals: why
design patterns: what

rough consensus and running code – get it out, iterate

degrade gracefully – HTML5 form inputs is good example of this
rewards the newer browsers without hurting the older ones
being able to push the web forward without hurting the existing web

dark patterns – user interfaces designed to trick people
http://wiki.darkpatterns.org/Home
http://www.alistapart.com/articles/dark-patterns-deception-vs.-honesty-in-ui-design/
http://www.slideshare.net/harrybr/ux-brighton-dark-patterns

Mobile Web Design Moves – Luke Wroblewski, author, Web Form Design

mobile growth story

There are more smart phones than pcs.
mobile web usage is surpassing pc web usage (esp. email, twitter, facebook, yelp)
mobile web usage is higher than native app usage
prediction: mobile phone will overtake pcs as the most common way to access the web by 2013

84% of people say they use smart phones at home
80% during misc. times
74% waiting in lines
64% at work

what are they doing?
micro-tasking
local
bored

what are the constraints?
battery life, intermittent connection, small screen, limited time

mobile web design moves

core mobile behaviors:
lookup/find
explore/play
check in/status
edit/create

focus your design on optimizing for the activity
content first, navigation second
put the most important stuff (most visited content) on your mobile site, get rid of the rest. Get rid of it period.

Put navigation at the bottom of a content page, for them to “pivot and explore”. Top nav is just an anchor link to shoot to bottom of page. Get rid of chunky nav at the top, let them get right to the content.

On mobile, the bottom part of the screen is easier to access and navigate.

Use HTML5 forms to make data input as easy and error proof as possible
use input masks (hinting), autocorrect/autovalidate
use as few input fields as possible (only one field for phone, not 3)

use other ways to navigate (swipe to paginate, pull down to reveal, tap to save, etc.)

NUI – natural user interface
the content IS the UI
enable direct manipulation of content and objects
reduce distance between user and content

http://www.abookapart.com/products/mobile-first
Touch Gesture Reference Guide: lukew.com/touch

The Dimensions of a Good Experience – Alexa Andrzejewski, founder, Foodspotting

Taking lessons from urban design

what makes a user experience good?
does it leave an impression on the senses? Is it memorable?
How is the form a reflection of the values?
Use the language of design to tell the story you want to tell.
Have a clear sense of structure to orient the user

What is the #1 thing you want people to do on their first visit, (second, third). Reveal (unfold) experience based on what the user needs to do. this also helps people understand the purpose of the site.

Fit – design anticipates and assists user behaviors

What kinds of decisions are you asking users to make? Is it too many? too few? Are people paralyzed by choices?

Certainty – Give users feedback throughout their interaction. Make people feel safe and know what is happening, especially when they are giving out sensitive information.

The Responsive Designer’s Workflow – Ethan Marcotte, co-author, Designing With Web Standards 3rd Edition

http://www.ethanmarcotte.com/

What makes a design responsive?

Flexible/fluid grids
Flexible images and media
CSS media queries
Only valuable content – content first
Design across a set of user experiences
Make a comittment to your content and make it accessible regardless of context

Boston Globe – new responsive web site (he worked on it) bostonglobe.com

design is the method of putting form and content together. Design is a process, not the end result.

design and development have to work more together, for responsive web design. Ask more questions. Interactive design review (verify your work live, get prototyping early). Vet your assumptions of the static design. How well does the layout adapt? Does it still feel usable? Do any elements need additional design direction? (this is a process of moving back and forth between css/html and photoshop).

building for mobile first allows you to build a consensus early on about what content is really important.

fluid grid method:
target px / context px = result %
target is the pixel width of the column
context is the total value of the grid

633px / 960px = .659375%
.column {float:left;width:.659375%}

flexible image
img {max-width:100%}

screen size break points for media queries (there are a lot more than this, but these are common):
320px
480px
768px
900px

Since we can’t keep up with all the screen sizes, we should use responsive designs – flexible grid is the doing the heavy lifting. Media queries does fine tuning.

Posted in web design | Leave a comment

Dynamic Height Cross Domain Iframe postMessage Javascript

The task at hand was to embed a 3 page form from another domain as an iframe onto my domain. It is possible to do cross domain communication using the javascript method postMessage (not supported below ie8). The challenge was that each page of the form was a different height, so the iframe had to adjust height each time the new page of the form loaded into the iframe. I tried several different solutions and had trouble with all of them. They were either buggy or didn’t work at all. I finally came across a simple solution that worked, and adjusted it to my needs.

Here’s the original example I found Setting the height of a cross-domain iframe using postMessage:

This code goes on the page that will be in the iframe:


function postSize(e){
  var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);
  if (typeof target != "undefined" && document.body.scrollHeight)
    target.postMessage(document.getElementById("foo").scrollHeight, "*");
}
window.addEventListener("load", postSize, false);

The id “foo” should be a div that is wrapped around the content for which you want to measure the height. In my example I used mainCol, which was the div that contained the form.

This code goes on the parent page (your domain), that will have the iframe embedded.


function receiveSize(e){
  if (e.origin === "http://www.example.com") // for security: set this to the domain of the iframe - use e.uri if you need more specificity
    document.getElementById("bar").style.height = e.data + "px";
}
window.addEventListener("message", receiveSize, false);

In this example the id “bar” should be the id you give you your iframe.

I changed a few things. First of all, addEventListener throws an error in ie, so you have to use attachEvent instead:

 if (window.addEventListener){
					window.addEventListener("load", postSize, false);
				} else {
					window.attachEvent("load", postSize);//for ie
				}

I also attached the height by setting the height attribute, rather than the style attribute. Additionally, I added 20px onto the calculated height to add some buffer, because I found the iframe to cut off the content a bit at the bottom.

  $("#iframe").attr('height', e.data);//receive and set the height sent from the postMessage
				   var b = $("#iframe").height() + 20; //adds a bit of height so the iframe doesn't get cut off
				   $("#iframe").attr('height', b); //set the height

Here was my final code. This went on the 2nd and 3rd pages of the form (on another domain, embedded in the iframe on my domain).

			function postSize(e){
			  var target = parent.postMessage ? parent : (parent.document.postMessage ? parent.document : undefined);
			  if (typeof target != "undefined" && document.body.offsetHeight)
				target.postMessage(document.getElementById("mainCol").offsetHeight, "*");  //change this star to your domain for more security
			}
			 if (window.addEventListener){
					window.addEventListener("load", postSize, false);
				} else {
					window.attachEvent("load", postSize);//for ie
				}

This went on the page with the iframe, on my domain:

          $(function() {
	  	 var ua = $.browser;
		  if ( ua.msie && ua.version.slice(0,3) == ("7.0") || ua.msie && ua.version.slice(0,3) == ("6.0")) {
			  var b = $("#iframe").remove().empty();//remove iframe for ie6/7 users and replace with a new iframe with scrolling=yes so they can see all the content
				 var c = ''
				 $('#iframe_holder').append(c);
		  }//postMessage doesn't work below ie8

  })

			function receiveSize(e){
				  if (e.origin === "http://www.theotherdomain.com") // for security: set this to the domain of the iframe - use e.uri if you need more specificity
				   $("#iframe").attr('height', e.data);//receive and set the height sent from the postMessage
				   var b = $("#iframe").height() + 20; //adds a bit of height so the iframe doesn't get cut off
				   $("#iframe").attr('height', b); //set the height

				}

			 if (window.addEventListener){
					window.addEventListener("message", receiveSize,false);
				} else {
					window.attachEvent("onmessage", receiveSize);//for ie
				}

And here was my iframe:

	 
Posted in Javascript | Leave a comment

Exclude custom post types from wordpress search – do not use exclude_from_search

I recently started using custom post types to create different types of articles I wanted to display on another site (not my main blog) via a feed. I created a custom post type called “articles”. These post types should not show up on my blog, nor should they be searchable via the wordpress search. According to the spec of registering and defining a custom post type, I should use ‘exclude_from_search’ => true, like so:

/*custom post type */
add_action('init', 'article_register');

function article_register() {
    $args = array(
        'label' => __('Credit.com Articles'),
        'singular_label' => __('Credit.com Article'),
        'new_item' => __('New Article'),
        'add_new_item' => __('Add New Article'),
        'edit_item' => __('Edit Article'),
        'taxonomies' => array('product'),
        'public' => true,
        'show_ui' => true,
        'capability_type' => 'post',
        'rewrite' => array( 'slug' => 'articles', 'with_front' => false),
        'hierarchical' => false,
        'exclude_from_search' => true,
        'menu_position' => 5,
        'supports' => array('title', 'editor','revisions')
       );  

    register_post_type( 'articles' , $args );
}

This worked fine and dandy on my wordpress blog, hiding the custom post types as it should. But I wanted to access these posts via a feed, and suddenly all the posts disappeared after I added the ‘exclude_from_search’ => true. I think this is a bug in wordpress.

So to get around this I removed ‘exclude_from_search’ => true. Instead I made a search loop function that excludes the custom post types. That way, the posts are excluded from the search, but are still available for me to pull in a feed.

If you don’t use thesis theme, all you have to do is slightly modify your search.php by adding this code after the start of your loop (replace ‘post’ with the name of your custom post type)



With thesis there is no search.php, so I instead started with a function written by Thesis expert godhammer:

/*
Custom Search API Loop
*/

$godhammer_search_and_destroy = new godhammer_api_loop;
	class godhammer_api_loop extends thesis_custom_loop {
		function search() {
			if(is_search()) 	{
	thesis_archive_intro();
			$paged = $this->get_paged_param();
			while (have_posts()) {
            the_post();
            thesis_hook_before_post_box();
            echo "\t\t\t
\n"; thesis_hook_post_box_top(); thesis_headline_area(); echo "\t\t\t\t
\n"; // thesis_post_content(); echo get_the_excerpt(); echo "\t\t\t\t
\n"; thesis_hook_post_box_bottom(); echo "\t\t\t
\n"; thesis_hook_after_post_box(); } wp_reset_query(); } else { thesis_loop::search(); } } // PAGINATION RELATED private function preserve_query_params($new_params = array()) { global $wp_query; return(array_merge($wp_query->query, $new_params)); } private function get_paged_param() { if(is_front_page()) { $paged = (get_query_var('page') ? get_query_var('page') : 1); } else { $paged = (get_query_var('paged') ? get_query_var('paged') : 1); } return($paged); } // END PRIVATE FUNCTIONS } // END SEARCH LOOP API

I then modified this for my purposes by adding the exclude custom post type bit, plus some styling stuff for the search results to make it look like my current search results page. My final result was:

/*
Custom Search API Loop
*/
$godhammer_search_and_destroy = new godhammer_api_loop;
	class godhammer_api_loop extends thesis_custom_loop {
		function search() {
			if(is_search()) 	{
	thesis_archive_intro();
			$paged = $this->get_paged_param();
			while (have_posts()) {
            the_post();

			if (get_post_type() == 'content' || get_post_type() == 'articles') continue;
            thesis_hook_before_post_box();
            echo "\t\t\t
\n"; thesis_hook_post_box_top(); //thesis_headline_area();?>

\n";?>
\n"; thesis_hook_after_post_box(); } wp_reset_query(); } else { thesis_loop::search(); } } // PAGINATION RELATED private function preserve_query_params($new_params = array()) { global $wp_query; return(array_merge($wp_query->query, $new_params)); } private function get_paged_param() { if(is_front_page()) { $paged = (get_query_var('page') ? get_query_var('page') : 1); } else { $paged = (get_query_var('paged') ? get_query_var('paged') : 1); } return($paged); } // END PRIVATE FUNCTIONS } // END SEARCH LOOP API
Posted in Thesis, wordpress | Leave a comment

CSS Resources from Wordcamp SF 2011

A couple weeks ago I attended wordcamp sf, and got to hear some css heavy weights like Estelle Weyl and Chris Coyier present. Here’s a link dump of some their presentations as well as some resources they recommended:

http://css-tricks.com/conferences/ConvergeSE2011Pseudos.pdf (Chris Coyier’s hilarious presentation on :after and :before)

http://iestelle.com/wordcampsf
(Estelle’s super awesome presentation, great overview and demo of almost everything css3 can do)

http://jsbin.com/super-css-super-challenge/

http://css-tricks.com/9516-pseudo-element-roundup/

http://westciv.com/tools

http://www.standardista.com/css3/css3-transform-property-and-the-various-transform-functions

http://css-tricks.com/examples/ShapesOfCSS/

http://nicolasgallagher.com/pure-css-gui-icons/

http://www.slideshare.net/saracannon/responsive-web-design-wordcamp-san-francisco

Posted in css, css3 | Leave a comment

Color Numbers in Ordered List with CSS Counter() and :Before Pseudo-Element

I’m going to show you how to make an ordered list where the numbers are a different color than the text. This is commonly done with background images. But there is a way better way to do it, assuming you don’t have to support browsers older than ie8. What we are going to do is create an ordered list with list-style-type:none. This will remove the numbers. Then we are going to replace the numbers with the css property, counter, and the :before pseudo element. The counter property is super awesome and under-utilized. Here is a great tutorial on it. I recommend looking at that first if you are not familiar with counter.

So we are adding numbers before the list items using :before. Since this is a pseudo element, we can actually apply a color style to it (or any other style for that matter), which is separate from the color style applied to the li element itself.

 ol {
		list-style-type:none;
		counter-reset:list;
	}

li {
		color:#333;
	}

li:before {
		counter-increment: list 1;
		content:counter(list) ".";
		color:#9dce32;
		padding-right:10px;
	}
  1. hello this is the first thing in the list
  2. this is the second thing on the list
  3. and one more just for fun
Posted in css | Tagged , , | Leave a comment

How To Show The Full Content of Multi-Page/Paginated Posts in the Feed WordPress (content after nextpage tag)

When you are using the full content feed option in wordpress, if your posts are paginated using the nextpage tag, only the first part of the content before the nextpage tag shows up in the feed. In order to force the full content of the post to show up in the feed, place this code in your functions.php or custom_functions.php (or as a plugin in your plugins in directory):


post_content;
	return $content;
}

add_filter( 'the_content', 'ftf_full_text_for_feeds', -100 );

?>
Posted in wordpress | Tagged , , | Leave a comment

How To Make An American Flag with CSS3 Gradients

I recently came across Lea Verou’s CSS3 gradient pattern gallery, and was inspired to try my hand at making a css3 gradient pattern. I decided to make an American flag. This is not strictly a background pattern, since it requires two elements. Rather than mess around with a bunch of different vendor specific declarations, mine only works in firefox. I’ve tested it in firefox 5.0.1.

The first element is the flag, which creates the 13 horizontal red and white stripes:

#flag {
				margin:0;
				padding:0;
				width:2000px;
				height:840px;
				background-color: #ffffff;
				background-image:-moz-linear-gradient(-90deg, #e0162b 50%, transparent 50%);
				background-size:310px;
				}

The next element is the blue square with 50 white stars. I must admit the stars were gnarly to make so I copied NIcolas Gallagher’s stars and adjusted accordingly.

	#stars {
			margin:0 0 0 -1px;
			padding:0;
			width:560px;
			height:456px;
			background:
		    -moz-linear-gradient(126deg, #0052a5 4%,   transparent 4%) -70px 48px,
		     -moz-linear-gradient( 54deg, #0052a5 4%,   transparent 4%) 30px 48px,
		     -moz-linear-gradient( 18deg, #ffffff 8.5%, transparent 8.5%) 30px 48px,
		     -moz-linear-gradient(162deg, #ffffff 8.5%, transparent 8.5%) -70px 48px,
		     -moz-linear-gradient(234deg, #ffffff 7.5%, transparent 7.5%) -70px 28px,
		     -moz-linear-gradient(-54deg, #ffffff 7.5%, transparent 7.5%) 30px 28px,
			 -moz-linear-gradient(126deg, #0052a5 4%,   transparent 4%) -20px 98px,
		     -moz-linear-gradient( 54deg, #0052a5 4%,   transparent 4%) 80px 98px,
		     -moz-linear-gradient( 18deg, #ffffff 8.5%, transparent 8.5%) 80px 98px,
		    -moz-linear-gradient(162deg, #ffffff 8.5%, transparent 8.5%) -20px 98px,
		     -moz-linear-gradient(234deg, #ffffff 7.5%, transparent 7.5%) -20px 78px,
		     -moz-linear-gradient(-54deg, #ffffff 7.5%, transparent 7.5%) 80px 78px;
			background-color:#0052a5;
			background-size:100px 100px;
		}


Here’s my demo of the American flag

Posted in Uncategorized, css3, gradients | Leave a comment

How To Automatically Add Categories to Posts in WordPress

I had a need to create a category feed that included almost every post, except for a few exceptions. Rather than having to manually check a category each time you post, why not have that category automatically get checked?

I used wp_set_object_terms, which creates the term and taxonomy relationship if it doesn’t already exist. This is used to assign the category to the post. I used the parameter “true” to keep any other categories that were there in tact.

I also use wpdb to interface with the database. The $wpdb object can be used to read data from any table in the WordPress database.

My first task was to assign category with ID 9547 to all posts UNLESS the post was also in the category with slug ‘bundle’. This was accomplished like so:

function add_category_automatically1($post_ID) {
	global $wpdb;
		if(!in_category('bundle')){
			$cat = array(9547);
			wp_set_object_terms($post_ID, $cat, 'category', true);
		}
}
add_action('publish_post', 'add_category_automatically1');

This was simple enough. Using the action ‘publish_post’, the category is automatically assigned when I publish the post. I also wanted to prevent posts from getting category 9547 if they were by 2 specific authors, with author ID’s 29 and 30. This was a bit more difficult. In order to access the author of the post, I had to pull the author ID (post_author) for the current post from the posts table in the database. Using $wpdb->get_results, ‘Generic, mulitple row results can be pulled from the database with get_results. The function returns the entire query result as an array.’ Based on this example from the codex:

$fivesdrafts = $wpdb->get_results("SELECT ID, post_title FROM $wpdb->posts
	WHERE post_status = 'draft' AND post_author = 5");

foreach ($fivesdrafts as $fivesdraft) {
	echo $fivesdraft->post_title;
}

I created my own that got the post_author for the posts, looped through them, and then assigned the category 9547 to each post except those by author 29 or 30, like so:

function add_category_automatically2($post_ID) {
	global $wpdb;
	$postsWeWants = $wpdb->get_results("SELECT ID, post_author FROM $wpdb->posts where ID = $post_ID");
	foreach ($postsWeWants as $postsWeWant) {
		if(($postsWeWant->post_author != 30) && ($postsWeWant->post_author != 29)){
			$cat = array(9547);
			wp_set_object_terms($post_ID, $cat, 'category', true);
		}
	}
}
add_action('publish_post', 'add_category_automatically2');

Then I put them both together, to get one function that would assign category 9547 to every post UNLESS it was also in category slug ‘bundle’, or by authors 29 or 30. Here is the final function:

function add_category_automatically($post_ID) {
	global $wpdb;
	$postsWeWants = $wpdb->get_results("SELECT ID, post_author FROM $wpdb->posts where ID = $post_ID");
	foreach ($postsWeWants as $postsWeWant) {
		if(($postsWeWant->post_author != 30) && ($postsWeWant->post_author != 29) && !in_category('bundle')){
			$cat = array(9547,9742);
			wp_set_object_terms($post_ID, $cat, 'category', true);
		}
	}
}
add_action('publish_post', 'add_category_automatically');
Posted in Uncategorized, php, wordpress | Tagged , , , | Leave a comment

Add a custom link dropdown menu with custom links in WordPress Thesis

Thesis theme for WordPress has a built in feature that supports dropdown menus. All you have to do to create dropdown menu items in Thesis is create pages that are child pages (the dropdown list) of the the parent page (the main nav item). In order for this to work you have to use the Thesis menu, not the WP menu (you can toggle between the two in Thesis>Site Options>Navigation Menu.

Well, let’s say you dont’ want to add pages from your wordpress site into the menu, let’s say you want to add other external links. Thesis also has a way to do this, but it has limitations. If you add a new Link (where you add links to your blogroll), you can assign it a new category – called nav for example. Then back in your Thesis>Site Options>Navigation Menu, you can select “add more links” and choose the nav category. Any links you’ve created in that category will show up in your navigation menu. The limitation is that you can’t control their order, they are just alphabetical. Another limitation is that you cannot then create a dropdown of this custom link menu item, because it is not an actual page.

There is another way you can achieve this, using the thesis hook thesis_hook_last_nav_item or thesis_hook_first_nav_item. This allows you to add custom link menu items either before or after the rest of your regular wordpress page menu items. If you want to add custom links in between your regular wordpress page links, you’d have to finagle it with css absolute positioning, but hopefully you won’t have to resort to that.

Even if you aren’t using the parent/child pages to automatically create a dropdown, the basic css of the thesis theme is already in place for you to create a custom link dropdown menu, just by adding a nested list. You can customized the css further from there.

Here is my example of custom link menu item with custom link dropdown list:

/* drop down menu*/
function posts_nav() {
	echo '
  • Credit.com
  • '; } add_action('thesis_hook_last_nav_item','posts_nav'); /*end drop down menu */
    Posted in Thesis, wordpress | Comments Off

    Best Search Plugin for WordPress – Relevanssi

    The default search engine for wordpress is notoriously bad. It does not list your most relevant/best results first, but rather shows more recent posts first. It has no options for customizing and improving the search functionality. There are several plugins that attempt to solve this problem, most of them are difficult to install, buggy, have security risks or do not work at all. After trying about 4-5 different ones with little success, I installed Relevanssi. It was super easy to install and worked with no problems and yielded highly relevant results. It has a bunch of settings you can change to improve the functionality even further.

    Posted in wordpress | Tagged | Leave a comment

    Basic MySQL Commands

    Here’s a good resource for basic MySQL commands like logging in, looking at tables, deleting/modifying tables and rows.

    http://www.pantz.org/software/mysql/mysqlcommands.html

    Posted in MySQL | Leave a comment

    How to wrap element in CDATA for rss feed using XSLT

    I was trying to create a new rss feed using XSLT, from an existing wordpress feed, processed by Java and displayed as a JSP. It seemed to work ok, but when I tried to put it into feedburner, the XML didn’t validate. It was having trouble with html entities like ndash. I tried to replace them but it didn’t work. I then noticed that my ‘description’ element was not wrapped in CDATA, whereas the original feed from wordpress was. I then tried to add CDATA by defining cdata-section-elements in the xsl:output:

    
    

    But for some reason it wasn’t working. I finally was able to add the CDATA by wrapping it around the element using xsl:text like so:

    
    		<![CDATA[]]>
    	
    

    Here is my final result. I also added some other character replacement stuff, because the feed was printing the decimal entities, when I needed the hex entities.

    
    
    
    
    
    	
    		
    	
    
    
    
    		
    			2.0
    			
    				
    				
    				
    				
    			
    		
    
    
    
    	
    	
    	
    	
    	
    	
     
    
    
    	
    		
    	
    
    
    
    	
    		<![CDATA[
    		
    		]]>
    	
    
    
    
    	
    		
    	
    
    
    
    	
    		
    	
    
    
    
    
    Posted in Uncategorized, wordpress, xsl | Tagged , , , | Leave a comment

    Position Fixed in ie6 – Div That Stays on the Bottom of the Browser Window

    If you want to create a div that stays fixed on the bottom of the browser window, even when you scroll up and down, you can use position:fixed. The only problem is that ie6 doesn’t recognize position:fixed. A search for ie6 position:fixed will tell you that you can use position:absolute instead, because ie6 renders position:absolute as position:fixed.

    In my case, this didn’t completely solve the problem. The div was fixed to the bottom of the page, but not to the bottom of the browser window as I scrolled up and down. I found an additional technique on csscreator.com to add to position:absolute that gave the desired result. The additional line is a css expression, which is generally considered a no-no because it slows down page load time, but because we are dealing with ie6 anyway…we’ll let it slide because it does the trick.

    #myDiv {
      position:fixed;
    /*stuff for ie6 */
      _position: absolute;
      _top: expression(eval(document.compatMode && document.compatMode=='CSS1Compat') ? documentElement.scrollTop +(documentElement.clientHeight-this.clientHeight) : document.body.scrollTop +(document.body.clientHeight-this.clientHeight));
    }
    
    Posted in ie6 | Leave a comment

    How to print literal text and HTML entities in XSL

    Use xsl: text disable-output-escaping=”yes”, with a CDATA element inside. Inside that you can put whatever you want.

    The code snippet plugin messes this up a little, but you get the point.

    Posted in Uncategorized, xsl | Leave a comment

    How to use gravatar to show the author image on author archive pages in wordpress

    echo get_avatar(get_the_author_email(), '72' );

    72 is the size you want the image to appear, you can change it to any size you want.

    Add this code to your author archive file. In Thesis theme, add it to your custom_functions.php file using is_author() to target author archive pages.

    Read more on the wordpress codex

    Posted in wordpress | Leave a comment

    AJAX Load for Carousel Template – NextGen Gallery WordPress Plugin

    The carousel template in NextGen Gallery by default uses a page load to navigate between each gallery image:

    http://nextgen-gallery.com/templates/carousel/

    The post says “his could be optimized via a Ajax call, maybe someone pick up the idea.” But I haven’t been able to find any examples of this. The best solution that avoids a new page load I found uses jquery only. It uses a custom template, and a modified ngg.slideshow.min.js, that’s it.

    Here: http://code.google.com/p/nextgen-gallery/issues/detail?id=316

    I used this example as a starting point, then I modified it further. Besides using jquery to go from slide to slide, I also added ‘previous’ and ‘next’ buttons that actually go from slide to slide, rather than only control pagination, as the nextgen default. I actually hide the default pagination, then steal it’s href and apply it to the “prev” and “next” buttons as needed (assumes 6 thumbnails per page):

    if(jQuery(prev).length == 0 || jQuery('.ngg-gallery-list li:eq(6)').is('.selected')) {
    		var prevPage = jQuery('.ngg-prev').find('a').attr('href');
    		jQuery('.prev-slide').attr('href', prevPage);
    		return true;
    		}
    
    ////
    ////
    if(jQuery(next).length == 0 || jQuery('.ngg-gallery-list li:eq(5)').is('.selected')) {
    		var nextPage = jQuery('.ngg-next').find('a').attr('href');
    		jQuery('.next-slide').attr('href', nextPage);
    		return true;
    		}
    

    Here’s mine:

    View Demo

    modified ngg.slideshow.min.js:

    jQuery.fn.nggSlideshow=function(args){var defaults={id:1,width:320,height:240,fx:'fade',domain:'',timeout:5000};var s=jQuery.extend({},defaults,args);var obj=this.selector;var stack=[];var url=s.domain+'index.php?callback=json&api_key=true&format=json&method=gallery&id='+s.id;var stackLength=0;jQuery.getJSON(url,function(r){if(r.stat=="ok"){for(img in r.images){var photo=r.images[img];stack.push(decodeURI(photo['imageURL']));}
    stackLength=stack.length;loadImage(1);}});function loadImage(num){if(stackLength>0&&num<=3){var img=new Image();img.src=stack.shift();stackLength--;jQuery(img).bind('load',function(){appendImage(img,num);});}} function appendImage(img,num){jQuery(img).hide();jQuery(obj).append(imageResize(img,s.width,s.height));if(num==3||stackLength==0){startSlideshow();}else{loadImage(++num);}} function startSlideshow(){jQuery(obj+'-loader').empty().remove();jQuery(obj+' img:first').fadeIn(1000,function(){jQuery(obj).cycle({fx:s.fx,containerResize:1,fit:1,timeout:s.timeout,next:obj,before:jCycle_onBefore});});} function imageResize(img,maxWidth,maxHeight){if(!img.complete) jQuery(img).bind('load',function(){imageResize(img,maxWidth,maxHeight)});if(img.height==0||img.width==0) return img;var width,height;if(img.width*maxHeight>img.height*maxWidth){if(img.width>maxWidth){width=maxWidth;height=Math.round(img.height/img.width*maxWidth);}}else{if(img.height>maxHeight){height=maxHeight;width=Math.round(img.width/img.height*maxHeight);}}
    jQuery(img).css({'height':height,'width':width});return img;};function jCycle_onBefore(curr,next,opts){if(opts.addSlide)
    if(stackLength>0){var img=new Image();img.src=stack.shift();stackLength--;jQuery(img).bind('load',function(){opts.addSlide(imageResize(this,s.width,s.height));});}};}
    
    jQuery(document).ready(function() {
    	//Click and Hover events for thumbnail list
    	jQuery("li.ngg-thumbnail-list:first").addClass('selected');
    	jQuery("li.ngg-thumbnail-list").click(function(){
    		//Set Variables
    		var imgAlt = jQuery(this).find('img').attr("alt"); //Get Alt Tag of Image
    		var imgTitle = jQuery(this).find('a').attr("href"); //Get Main Image URL
    		var description = jQuery(this).find('a').attr("title"); //Get Alt Tag of Image
    
    		if (jQuery(this).is(".selected")) {  //If it's already active, then...
    			return false; // Don't click through
    		} else {
    			//The Main Image change
    				jQuery(".picHolder img").attr({ src: imgTitle , alt: imgAlt});
    				jQuery(".gallery_description").html(description);
    				jQuery(".picCaption").html(imgAlt);
    
    		}
    
    		jQuery("li.ngg-thumbnail-list").removeClass('selected'); //Remove class of 'active' on all lists
    		jQuery(this).addClass('selected');  //add class of 'active' on this list only
    		return false;
    
    		});
    
    jQuery("a.next-slide").click(function(){ 
    
    		var next = jQuery('.ngg-gallery-list').find('li.selected').next();
    
    		//Set Variables
    		var imgAlt = jQuery(next).find('img').attr("alt"); //Get Alt Tag of Image
    		var imgTitle = jQuery(next).find('a').attr("href"); //Get Main Image URL
    		var description = jQuery(next).find('a').attr("title"); //Get Alt Tag of Image
    		var idVar = jQuery(next).find('a').attr("onclick"); //Get onclick value of image for tracking
    
    			//The Main Image change
    				jQuery(".picHolder img").attr({ src: imgTitle , alt: imgAlt});
    				jQuery(".gallery_description").html(description);
    				jQuery(".picCaption").html(imgAlt);
    
    	jQuery(this).attr('onclick', idVar);	//applies onclick value to next button for tracking	
    
    	if(jQuery('.bundle-next').length > 0 && jQuery(next).length == 0)  {
    		var bundleNext = jQuery('.bundle-next').attr('href');
    		jQuery('.next-slide').attr('href', bundleNext);
    		return true;
    	}
    
    	else if(jQuery(next).length == 0 || jQuery('.ngg-gallery-list li:eq(5)').is('.selected')) {
    		var nextPage = jQuery('.ngg-next').find('a').attr('href');
    		jQuery('.next-slide').attr('href', nextPage);
    		return true;
    		}
    	else {	
    
    		jQuery(next).addClass('selected');  //add class of 'active' on this list only
    		jQuery("li.ngg-thumbnail-list").not('.selected:eq(1)').removeClass('selected'); //Remove class of 'active' on all lists
            return false;
    		}
    	});
    
    jQuery("a.prev-slide").click(function(){ 
    
    		var prev = jQuery('.ngg-gallery-list').find('li.selected').prev();
    
    		//Set Variables
    		var imgAlt = jQuery(prev).find('img').attr("alt"); //Get Alt Tag of Image
    		var imgTitle = jQuery(prev).find('a').attr("href"); //Get Main Image URL
    		var description = jQuery(prev).find('a').attr("title"); //Get Alt Tag of Image
    		var idVar = jQuery(prev).find('a').attr("onclick"); //Get onclick value of Image for tracking
    
    			//The Main Image change
    				jQuery(".picHolder img").attr({ src: imgTitle , alt: imgAlt});
    				jQuery(".gallery_description").html(description);
    				jQuery(".picCaption").html(imgAlt);
    
    	jQuery(this).attr('onclick', idVar); //applies onclick value to prev button for tracking
    
    	if(jQuery(prev).length == 0 || jQuery('.ngg-gallery-list li:eq(6)').is('.selected')) {
    		var prevPage = jQuery('.ngg-prev').find('a').attr('href');
    		jQuery('.prev-slide').attr('href', prevPage);
    		return true;
    		}
    	else {	
    
    		jQuery(prev).addClass('selected');  //add class of 'active' on this list only
    		jQuery("li.ngg-thumbnail-list").not('.selected:eq(0)').removeClass('selected'); //Remove class of 'active' on all lists
    		return false;
    		}
    
    		});
    
    });//Close Function

    Here’s my carousel template:

     If you would like to show the timestamp of the image ,you can use
    **/
    ?>
    
    <?php echo $current->alttext ?> alttext) ?>
    hidden ) continue; ?>

    A couple of special things I’m doing:
    idVar is used to create unique URLs to send to Google Analytics each time a new slide is viewed. This creates the illusion of new page loads, even though you don’t have to load the page again to view each slide.

    
    
    Posted in Uncategorized, jQuery, php, wordpress | Leave a comment

    How to increase the max upload size in wordpress

    .htaccess method – add this line to top of .htaccess file

    php_value upload_max_filesize 50M

    change 50 to anything you want

    If the .htaccess method doesn’t work, you’ll have to edit your php.ini file.

    php.ini can be located in one of these places – or someplace similar:

    /etc/
    /usr/bin/php/
    /wwwroot/php/php.ini
    /opt/local/etc/php5
    /private/etc

    In the php.ini file, add this line or change this line

    upload_max_filesize = 50M ;

    AND

    post_max_size = 60M ;

    upload_max_filesize controls the maximum size of each uploaded file.
    http://php.net/ini.core#ini.upload-max-filesize

    post_max_size controls the maximum amount of data that can be
    transferred by the post method.
    http://php.net/ini.core#ini.post-max-size

    As the manual for post_max_size says:
    “This setting also affects file upload. To upload large files, this
    value must be larger than upload_max_filesize.”

    Posted in php, wordpress | Leave a comment