Friday 29 March 2013
Facebook StumbleUpon Twitter Google+ Pin It

Custom Controls in WP Admin

Introduction



WordPress 3.4 has a fucking cool new feature on the themes page. Next to each theme theres a preview or a customize link that pops up a new overlay that lets the user live edit their themes. Adding extra theme options has been constant a pain the arse since I started developing themes all those few years ago. To make things easier for myself I even created a theme admin plugin. I was never that happy with the plugin however and always too busy to make it work so the new theme customizer seems like a good timesaver for me and I decided to take a look at how to implement it.



The first thing I found was that as with all new WP features no-one has written any documentation for customising (Hey WP core developers, customise is spelled with a damn s!) it yet. All I could find was this description of the beta version. Also there doesn’t seem to be an API yet, it must be coming in a future release. However, there is an object called $wp_customize that you can add your custom theme settings to.

Getting Started



On loading up my starter theme in the preview I was suprised in seeing a half built menu already there. This is because WordPress is pulling the options for custom headers, backgrounds that you’ve added using the add_theme_support() function. It also pulls some core options like site title and displays them there.

Custom Options



Time for custom options. Going through the blog post I found I saw that the first thing you need to do is hook a function to the customize_register action like this:













1


2


3


4




function themename_customize_register($wp_customize){


    //STUFF IN HERE


}


add_action('customize_register', 'themename_customize_register');

All your custom options go into there.

Adding a Section

This is simple enough as far as I can tell. You add one using the following:


1


2


3


4




$wp_customize->add_section('themename_color_scheme', array(


    'title' => __('Color Scheme', 'themename'),


    'priority' => 120,


));


So you pass through a unique slug and an array of arguments to the add_section method. I’m not 100% sure of all the arguments to pass through in the array, all I passed was the title and the priority. The priority is where you want the section to appear in the menu order. 1 is on the top and 120 seems to be the bottom.

Adding options

There are two methods you need to call to add an option. One to tell WordPress that an option exists and one to display whatever input box it needs. This is similar how the add_option()/update_option()/get_option() API works and it should be because it uses those functions to save the settings as far as I can tell/be bothered to check.


The first option type I’m going to show you is a standard text input box then I’ll breeze through the other types. You need to first call the add_setting() method to tell WP that you wish to save some new data. You do that like this:



1


2


3


4


5




$wp_customize->add_setting('themename_theme_options[text_test]', array(


    'default'        => 'Arse!',


    'capability'     => 'edit_theme_options',


    'type'           => 'option',


));


Similar to the add_section() method you pass through a slug and an array of args. You need to pass through a unique slug to this as the first parameter and it also allows you to pass the slug as an array index. The advantages of this is all your options are then available in the template in the one array keeping things nice and neat. The args I’ve found are:
  • Default: The default value for the input.

  • Capability: This is the user role that is capable of editing these settings, I assume you would always set it to ‘edit_theme_options’.

  • Type: The way you want to store the data in WordPress, you can set it to ‘option’ or ‘theme_mod’. I’ve always used option for saving theme preferences but if you prefer using theme mod then you can set it to save those here.
Next you want to display your option in your custom section:


1


2


3


4


5




$wp_customize->add_control('themename_text_test', array(


    'label'      => __('Text Test', 'themename'),


    'section'    => 'themename_color_scheme',


    'settings'   => 'themename_theme_options[text_test]',


));


Again this works similarly to add_setting() and add_section() you pass a unique slug (Don’t really know why here as it’s only used as the list item css id) and an array of args. Some of the args are used for every input and some differ depending on the input element you want to display. The universal ones are:
  • label: The form items label.

  • section: The section in which you want the form item to appear.

  • type: The type of form item you want. These are text, radio, checkbox and select. And are standard form elements. Textareas and HTML5 input types aren’t supported.

  • settings: This is the setting you want to use to save the values from the file input. You put in the unique slug of of the setting you want to use.

  • choices: These are only needed for radio buttons and dropdowns and contain the different options you want to display.
You can also add options to the sections created by the WordPress core by passing their slug in the section arg. The ones I found are:
  • Colors: colors

  • Header Image: header_image

  • Background Image: background_image

  • Static Front Page: static_front_page

  • Site Title & Tagline: title_tagline

  • Navigation: nav

Standard Input Types


These are just standard form items.

Radio



01


02


03


04


05


06


07


08


09


10


11


12


13


14


15


16


17




$wp_customize->add_setting('themename_theme_options[color_scheme]', array(


    'default'        => 'value2',


    'capability'     => 'edit_theme_options',


    'type'           => 'option',


));




$wp_customize->add_control('themename_color_scheme', array(


    'label'      => __('Color Scheme', 'themename'),


    'section'    => 'themename_color_scheme',


    'settings'   => 'themename_theme_options[color_scheme]',


    'type'       => 'radio',


    'choices'    => array(


        'value1' => 'Choice 1',


        'value2' => 'Choice 2',


        'value3' => 'Choice 3',


    ),


));


Checkbox

To be honest, I think I’m missing something here. It’s acting a bit wonkey. Maybe it’s broken?


01


02


03


04


05


06


07


08


09


10


11




$wp_customize->add_setting('themename_theme_options[checkbox_test]', array(


    'capability' => 'edit_theme_options',


    'type'       => 'option',


));




$wp_customize->add_control('display_header_text', array(


    'settings' => 'themename_theme_options[checkbox_test]',


    'label'    => __('Display Header Text'),


    'section'  => 'themename_color_scheme',


    'type'     => 'checkbox',


));

Select Box



01


02


03


04


05


06


07


08


09


10


11


12


13


14


15


16


17




$wp_customize->add_setting('themename_theme_options[header_select]', array(


    'default'        => 'value2',


    'capability'     => 'edit_theme_options',


    'type'           => 'option',




));


$wp_customize->add_control( 'example_select_box', array(


    'settings' => 'themename_theme_options[header_select]',


    'label'   => 'Select Something:',


    'section' => 'themename_color_scheme',


    'type'    => 'select',


    'choices'    => array(


        'value1' => 'Choice 1',


        'value2' => 'Choice 2',


        'value3' => 'Choice 3',


    ),


));



Page Dropdown

This displays a list of your pages. I guess you could allow the user to set pages for something custom. It’s weird that this is in there but not a category dropdown option.


01


02


03


04


05


06


07


08


09


10


11


12




$wp_customize->add_setting('themename_theme_options[page_test]', array(


    'capability'     => 'edit_theme_options',


    'type'           => 'option',




));




$wp_customize->add_control('themename_page_test', array(


    'label'      => __('Page Test', 'themename'),


    'section'    => 'themename_color_scheme',


    'type'    => 'dropdown-pages',


    'settings'   => 'themename_theme_options[page_test]',


));



You can hack in a category dropdown like this however:


01


02


03


04


05


06


07


08


09


10


11


12


13


14


15


16


17


18


19


20


21


22


23


24




$categories = get_categories();


$cats = array();


$i = 0;


foreach($categories as $category){


    if($i==0){


        $default = $category->slug;


        $i++;


    }


    $cats[$category->slug] = $category->name;


}




$wp_customize->add_setting('themename_theme_options[header_select]', array(


    'default'        => $default,


    'capability'     => 'edit_theme_options',


    'type'           => 'option',




));


$wp_customize->add_control( 'example_select_box', array(


    'settings' => 'themename_theme_options[header_select]',


    'label'   => 'Select Something:',


    'section' => 'themename_site_options',


    'type'    => 'select',


    'choices' => $cats,


));


Fancy Input Types


These are custom input types and use javascript to work. They also all vary slightly from the others in that a new object needs to be created for each control.

Image Upload



Image upload is a file input type and allows users to upload an image. Handy for letting them set their logo.



01


02


03


04


05


06


07


08


09


10


11




$wp_customize->add_setting('themename_theme_options[image_upload_test]', array(


    'default'           => 'image.jpg',


    'capability'        => 'edit_theme_options',


    'type'           => 'option',


));




$wp_customize->add_control( new WP_Customize_Image_Control($wp_customize, 'image_upload_test', array(


    'label'    => __('Image Upload Test', 'themename'),


    'section'  => 'themename_color_scheme',


    'settings' => 'themename_theme_options[image_upload_test]',


)));

File Upload

Adds a custom file input. Good for allowing the end user to upload files I guess. Maybe a custom favicon would use this?


01


02


03


04


05


06


07


08


09


10


11


12




$wp_customize->add_setting('themename_theme_options[upload_test]', array(


    'default'           => 'arse',


    'capability'        => 'edit_theme_options',


    'type'           => 'option',




));




$wp_customize->add_control( new WP_Customize_Upload_Control($wp_customize, 'upload_test', array(


    'label'    => __('Upload Test', 'themename'),


    'section'  => 'themename_color_scheme',


    'settings' => 'themename_theme_options[upload_test]',


)));


Color Picker

Displays a colour picker. Gives the user the option to destroy your theme with their bad taste. This input seems to have a hex colour callback for sanitizing the value.


01


02


03


04


05


06


07


08


09


10


11


12


13




$wp_customize->add_setting('themename_theme_options[link_color]', array(


    'default'           => '000',


    'sanitize_callback' => 'sanitize_hex_color',


    'capability'        => 'edit_theme_options',


    'type'           => 'option',




));




$wp_customize->add_control( new WP_Customize_Color_Control($wp_customize, 'link_color', array(


    'label'    => __('Link Color', 'themename'),


    'section'  => 'themename_color_scheme',


    'settings' => 'themename_theme_options[link_color]',


)));



Displaying these options in your theme.

Displaying this stuff is easy. Depending on if you set your setting_type() to option or theme_mod you can display it in the two following ways:


Option:



1




<?php $options = get_option('themename_theme_options'); echo $options['input_name']; ?>


Theme Mod:


1




<?php $options =  get_theme_mod('themename_theme_options'); echo $options['input_name']; ?>

-By Parthiv Patel




Adding a logo uploader to your WordPress theme with the Theme Customizer

Let’s create a logo uploader using the new Theme Customizer, which was released with WordPress 3.4. This will allow users to place an image in our theme’s header; if no logo has been uploaded, we’ll fall back to displaying the site title and description instead.

For a more in-depth description of the Theme Customizer, including practical examples, code and more, see Otto’s excellent tutorials. If you are completely new to the Theme Customizer, I highly recommend at least scanning through them, to better understand the methods we’ll be calling in our code.

When working with the Theme Customizer, we should be creating sections, settings and controls within a function being fired on the customize_register hook. Create this function in your theme’s functions.php. The next three code blocks will go within this function.

1

2

3

4


function themeslug_theme_customizer( $wp_customize ) {

    // Fun code will go here

}

add_action('customize_register', 'themeslug_theme_customizer');




First, we’ll create a new section for our logo upload. Note that the description will not be displayed when using the Theme Customizer; it is simply used for the section heading’s title attribute.

1

2

3

4

5


$wp_customize->add_section( 'themeslug_logo_section' , array(

    'title'       => __( 'Logo', 'themeslug' ),

    'priority'    => 30,

    'description' => 'Upload a logo to replace the default site name and description in the header',

) );




Next, we register our new setting. It doesn’t get any easier than this:

1


$wp_customize->add_setting( 'themeslug_logo' );



Lastly, we tell the Theme Customizer to let us use an image uploader for setting our logo:

1

2

3

4

5


$wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'themeslug_logo', array(

    'label'    => __( 'Logo', 'themeslug' ),

    'section'  => 'themeslug_logo_section',

    'settings' => 'themeslug_logo',

) ) );



That wraps up our work in functions.php.

To output our new logo to the screen, we’ll need to call our setting with get_theme_mod somewhere in our theme’s header (I’ll be working in my theme’s header.php template file). However, if the user hasn’t set a logo, we’ll want to output the site title and description instead.

1

2

3

4

5

6

7

8

9

10


<?php if ( get_theme_mod( 'themeslug_logo' ) ) : ?>

    <div class="site-logo">

        <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><img src="<?php echo get_theme_mod( 'themeslug_logo' ); ?>" alt="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>"></a>

    </div>

<?php else : ?>

    <hgroup>

        <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1>

        <h2 class="site-description"><?php bloginfo( 'description' ); ?></h2>

    </hgroup>

<?php endif; ?>



Style your logo container as desired, and you’re done! For an example of the above code in action, check out my Debut starter theme on GitHub.

Courtesy /Source:- http://kwight.ca/blog/adding-a-logo-uploader-to-your-wordpress-site-with-the-theme-customizer/

-By Parthiv Patel

Fridaygram: high school computer science, desert termites, YouTube sleuthing

Author Photo
By Scott Knaster, Google Developers Blog Editor

Computer Science for High School (CS4HS) is a Google-sponsored program to enable professional development for high school and middle school students around the world interested in computer science. CS4HS holds workshops for teachers and provides funding to develop the workshops, along with help from local Googlers.


woman pointing at map on large monitor

Earlier this week, we announced the recipients of this year’s grants, which will be the fifth year of the program (and you can see a list of previous years’ programs here). Computer science education isn’t just for university students any more.

Education leads to the scientific method, which is how researchers discovered that mysterious circles in the Namib Desert are probably not fairy circles or the work of an underground dragon, but are actually caused by termites in the sand. Norbert Jürgens of the University of Hamburg learned that sand termites eat the roots of grasses, creating the circles in the sand. That’s not nearly as cool as an underground dragon, but it seems more plausible.

Finally, you probably remember that astonishing meteor that lit up the sky over Russia last month, and you might have seen some of the many videos that recorded the event. So did Swedish blogger Stefan Geens, who figured out that he could learn more about the meteor from the videos in non-obvious ways. Geens used a video showing shadows cast by the meteor, along with Google Earth and Photoshop, to roughly calculate the meteor’s trajectory and landing place. From there, scientists figured out more about the meteor, including its size, track, and point of explosion. So this weekend, if you get inspired, you too can use YouTube to figure out something new.


Yes, meteor videos and sand termites are just part of the usual fun here on Fridaygram, where we eschew our usual developer fare and present just cool stuff instead, even if it doesn’t involve coding.

Wednesday 27 March 2013
Facebook StumbleUpon Twitter Google+ Pin It

Education Awards on Google App Engine

Author PhotoBy Andrea Held, Google University Relations

Cross-posted from the Google Research Blog

Last year we invited proposals for innovative projects built on Google’s infrastructure. Today we are pleased to announce the 11 recipients of a Google App Engine Education Award. Professors and their students are using the award in cloud computing courses to study databases, distributed systems, web mashups and to build educational applications. Each selected project received $1000 in Google App Engine credits.

Awarding computational resources to classroom projects is always gratifying. It is impressive to see the creative ideas students and educators bring to these programs.
Below is a brief introduction to each project. Congratulations to the recipients!

John David N. Dionisio, Loyola Marymount University
Project description: The objective of this undergraduate database systems course is for students to implement one database application in two technology stacks, a traditional relational database and on Google App Engine. Students are asked to study both models and provide concrete comparison points.

Xiaohui (Helen) Gu, North Carolina State University
Project description: Advanced Distributed Systems Class
The goal of the project is to allow the students to learn distributed system concepts by developing real distributed system management systems and testing them on real world cloud computing infrastructures such as Google App Engine.

Shriram Krishnamurthi, Brown University
Project description: WeScheme is a programming environment that runs in the Web browser and supports interactive development. WeScheme uses App Engine to handle user accounts, serverside compilation, and file management.

Feifei Li, University of Utah
Project description: A graduate-level course that will be offered in Fall 2013 on the design and implementation of large data management system kernels. The objective is to integrate features from a relational database engine with some of the new features from NoSQL systems to enable efficient and scalable data management over a cluster of commodity machines.

Mark Liffiton, Illinois Wesleyan University
Project description: TeacherTap is a free, simple classroom-response system built on Google App Engine. It lets students give instant, anonymous feedback to teachers about a lecture or discussion from any computer or mobile device with a web browser, facilitating more adaptive class sessions.

Eni Mustafaraj, Wellesley College
Project description: Topics in Computer Science: Web Mashups. A CS2 course that combines Google App Engine and MIT App Inventor. Students will learn to build apps with App Inventor to collect data about their life on campus. They will use Google App Engine to build web services and apps to host the data and remix it to create web mashups. Offered in the 2013 Spring semester.

Manish Parashar, Rutgers University
Project description: Cloud Computing for Scientific Applications -- Autonomic Cloud Computing teaches students how a hybrid HPC/Grid + Cloud cyber infrastructure can be effectively used to support real-world science and engineering applications. The goal of our efforts is to explore application formulations, Cloud and hybrid HPC/Grid + Cloud infrastructure usage modes that are meaningful for various classes of science and engineering application workflows.

Orit Shaer, Wellesley College
Project description: GreenTouch
GreenTouch is a collaborative environment that enables novice users to engage in authentic scientific inquiry. It consists of a mobile user interface for capturing data in the field, a web application for data curation in the cloud, and a tabletop user interface for exploratory analysis of heterogeneous data.

Elliot Soloway, University of Michigan
Project description: WeLearn Mobile Platform: Making Mobile Devices Effective Tools for K-12. The platform makes mobile devices (Android, iOS, WP8) effective, essential tools for all-the-time, everywhere learning. WeLearn’s suite of productivity and communication apps enable learners to work collaboratively; WeLearn’s portal, hosted on Google App Engine, enables teachers to send assignments, review, and grade student artifacts. WeLearn is available to educators at no charge.


Jonathan White, Harding University
Project description: Teaching Cloud Computing in an Introduction to Engineering class for freshmen. We explore how well-designed systems are built to withstand unpredictable stresses, whether that system is a building, a piece of software or even the human body. The grant from Google is allowing us to add an overview of cloud computing as a platform that is robust under diverse loads.



Dr. Jiaofei Zhong, University of Central Missouri
Project description: By building an online Course Management System, students will be able to work on their team projects in the cloud. The system allows instructors and students to manage the course materials, including course syllabus, slides, assignments and tests in the cloud; the tool can be shared with educational institutions worldwide.


Andrea Held is a Program Manager on the University Relations team at Google. She grew up in Germany and has lived in California for almost 30 years.

Posted by Scott Knaster, Editor

Friday 22 March 2013
Facebook StumbleUpon Twitter Google+ Pin It

Fridaygram: art project expands, tweeting in tongues, speaking to movies

Author PhotoBy Scott Knaster, Google Developers Blog Editor

We posted once before about the Google Art Project, a very cool endeavor to make museum art available online to people around the world. We’re writing about it again today because the project has just expanded to include a bunch of great new stuff, including ancient works, contemporary art, and even urban art.



Highlights of the newly added works include hundreds of photos from highly regarded photographers, centuries-old maps, and historical documents. You can spend hours exploring museums from more than 40 countries while you sit in the park with your laptop.

Speaking of traveling without actually moving, a researcher has used public Twitter data to study the use of human languages in various places around the world. Researcher Delia Mocanu and her team studied languages from tweets sent in New York City and used the data to map neighborhoods by language use. In some cases, the secondary language used in a neighborhood matched the language spoken by original residents decades or even hundreds of years earlier. That’s even before Twitter existed.

Finally, when you’re done looking at art and learning about world language use, you can spend some time this weekend with Chrome’s new Peanut Gallery. This project uses Chrome’s voice recognition technology to let you add title cards to old silent films. It’s completely for fun – enjoy!


Get your API info and meaty technical details earlier in the week, because on Friday it’s all for fun: science, the humanities, and just general nerdiness.

Thursday 21 March 2013
Facebook StumbleUpon Twitter Google+ Pin It

SiteGround, IISpeed and Google Chrome make the web faster with PageSpeed

Author PhotoBy Ilya Grigorik, Developer Advocate and Web Performance Engineer

At Google we want the whole web to be faster, and there is no better way to achieve this goal than through helping our partners, both commercial and open-source, to deliver web optimization products to their users and clients. The PageSpeed Optimization Libraries, which are developed as part of our Make the Web Faster initiative, are a cornerstone of this strategy, enabling a growing list of products and integrations, developed both inside and outside Google.

SiteGround, a popular web hosting provider, announced mod_pagespeed support to their customers: "SuperCacher plugin is the first and only plugin that fully integrates Google’s mod_pagespeed with cPanel. Simply put, mod_pagespeed speeds up your site and reduces page load time automatically, with no additional knowledge required on the users’ side. It also optimizes your website for mobile view and for better browser rendering."

SiteGround PageSpeed control panel

With SiteGround, you can enable PageSpeed optimizations on your site with one click. Then, you can hand-tune and configure your site to match your specific needs through advanced customizations provided by mod_pagespeed.

However, that’s not all. The portfolio of PageSpeed integrations continues to expand:
  • The We-AMP team has announced a beta release of IISpeed, which enables PageSpeed web content optimization within the Microsoft IIS web server. "IIS and ASP.NET are very popular technologies on the web, powering millions of websites, and we are excited to bring the full power of PageSpeed optimization to the Windows platform," said Otto van der Schaaf and Kees Spoelstra.
  • Thanks to open-source contributions, mod_pagespeed is now integrated with CPanel and WHM, an easy-to-use server control and management panel for web hosts and website owners.
  • Google Chrome has adapted PageSpeed to power the recently announced Chrome data compression proxy, which significantly reduces data usage and speeds up page load times on cellular networks.
To find out how to leverage PageSpeed on your site or service, or how to integrate the open source PageSpeed Optimization Libraries into your own product, visit the PageSpeed site.


Ilya Grigorik is a Developer Advocate and Web Performance Engineer at Make the Web Faster.

Posted by Scott Knaster, Editor