WordPress Structure and Best Practices


Published on

a short slide-show overviewing

Published in: Technology
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

WordPress Structure and Best Practices

  1. 1. WordPress Structureand Best Practices<br />Mark Parolisi<br />04-05-2010<br />
  2. 2. Directory Structure<br />Application Directory<br />core files (wp-settings.php, wp-config.php, etc)<br />/wp-admin<br />Operates as a micro-site to control the app with its own css, js, includes directories<br />/wp-includes<br />classes, libraries, scripts for entire app, JS libraries, images<br />/wp-content<br />/plugins<br />Can either be directories for large plugins, or just single files<br />/themes<br />Directories of themes<br />/uploads<br />Typically organized by year/month of upload<br />/upgrade<br />
  3. 3. Core<br />The only files that need to be edited are:<br />wp-config.php<br />database connection<br />define constants to override DB values<br />wp-settings.php<br />memory limit (32M default)<br />debug mode<br />DO NOT EDIT OTHER FILES!<br />When we do core updates, these files may be overwritten and your changes would be lost.<br />I have yet to find a ‘core-hack’ that I cannot reproduce through acceptable WordPressplugin conventions.<br />
  4. 4. Database Structure<br />wp_comments<br />wp_commentmeta<br />wp_links<br />Not what you think. It’s just a place for WP to store the links defined by the user in the admin panel<br />wp_options<br />Kitchen sink table that holds everything from site-url to date/time formats, to timestamps for app core/plugin updates<br />Gets very abused bloated with plugin settings due to the ease of CRUD operatios on this table<br />wp_postmeta<br />Holds all extra (custom) data about a post/page. <br />wp_posts<br />Holds all necessary* data about a post/page<br />wp_terms<br />Defines categories, tags, link categories and custom taxonomies. Depends on terms_relationships and term_taxonomy.<br />wp_term_relationships<br />wp_term_taxonomy<br />Defines type of taxonomy and contains data about the term(post count, description, etc)<br />wp_usermeta<br />wp_users<br />
  5. 5.
  6. 6. Credit to @xentek<br />
  7. 7. Anatomy of a Plugin<br />Files in the /wp-content/plugins directory are scanned for this comment at the start of the document:<br />/*<br />Plugin Name: GMaps Widget<br />Plugin URI: http://wordpress.org/extend/plugins/<br />Description: Adds a static Google map with text and a link to full Google Map.<br />Version: 1.0<br />*/<br />Plugins work by creating our custom functions to do the work, then calling them to fire through native WP functions.<br />We can make a new DB table when the plugin is activated in the admin menu<br />register_activation_hook(__FILE__, ‘myplugin_activation');<br />function myplugin_activation() {<br />global $wpdb;<br /> $table_name = 'wp_myplguin_table';<br /> if($wpdb->get_var("SHOW TABLES LIKE '$table_name'") != $table_name) {<br /> $sql = "CREATE TABLE " . $table_name . " (<br />alt_title VARCHAR(255) NULL,<br />alt_text TEXT NULL<br /> );";<br /> require(ABSPATH . 'wp-admin/includes/upgrade.php');<br />dbDelta($sql);<br /> }<br />}<br />
  8. 8. Actionsadd_action(‘wp_footer’, ‘our_custom_function’)<br />When WP loads pages (client or admin), it sets action hooks which we can use to load our scripts. Currently 30 for front-end, 11 for admin.<br />set_current_user<br />template_redirect<br />wp_head<br />loop_start<br />Use these hooks to prevent conflicts and set dependencies.<br />By calling the wp_enqueue_script method (for JS) at the wp_enqueue_scripts action, we make sure that we aren’t loading scripts twice and the script is loaded in the right order (very important for JS) <br />WordPress also allows us to create our own actions hooks. <br />http://codex.wordpress.org/Plugin_API/Action_Reference<br />
  9. 9. Filtersadd_filter(‘the_content’,‘our_function_name’)<br />Filters are very similar to actions in that WP sets them for various elements in the application. But rather than just setting hooks for our functions, they allow us to alter (filter) the original data.<br />the_content<br />wp_list_pages<br />Example: Adding to original post content<br /> functionaddContent($content = ''){ $content .= "<p>My plugin text</p>";    return $content;}<br />add_filter(‘the_content’, ‘addContent’);<br />Filters can be used not only to append content but also remove, organize and modify it (parental-filters, custom sort for navigation menus, etc)<br />http://codex.wordpress.org/Plugin_API/Filter_Reference<br />
  10. 10. HackingModding other Plugins<br />Open Source plugins are free to use and modify in your own environment. But do it with care.<br />Sometimes you can actually create a new plugin that alters another plugin (very case-by-case)<br />Decide whether your mod is worth losing support from the native plugin.<br />Change the plugin name or version number to prevent accidentally update and overwriting of your changes.<br />Document/Comment all of your changes.<br />If the mod could be used by others, try to contact the original author and share your patch.<br />
  11. 11. Widgets<br />Widgets are small bits of functionality that run in special areas of a template called ‘widgetized areas’ (formerly ‘sidebars’)<br />Widgets can be created in plugin files or the theme’s functions.php file.<br />Widget structure is pretty basic<br />Class SampleWidget extends WP_Widget{<br /> function SampleWidget(){<br /> parent::WP_Widget(false, $name = ‘SampleWidget'); <br /> }<br />function widget($args, $instance){ <br /> //what the widget will output<br />}<br />function update($new_instance, $old_instance){<br /> //updating the values of the widget from the form function<br />}<br />function form($instance){ <br /> //make the form that appears in the /wp-admin widgets section<br />}<br />} //end class<br />add_action('widgets_init', create_function('', 'return register_widget(" SampleWidget");'));<br />http://codex.wordpress.org/Widgets_API<br />
  12. 12. Theme Templates<br />A standard WP theme contains the following views<br />Header.php<br />Index.php<br />Sidebar.php<br />Archive.php<br />Single.php<br />Page.php<br />Search.php<br />Footer.php<br />Comments.php<br />Functions.php<br />Some of these files are optional -- e.g. If you omit single.php the index.php will render the content.<br />
  13. 13. Functions.php<br />This is the first file loaded and acts just like a plugin file.<br />Anything you can do with a plugin, you can localize to a theme with functions.php<br />This file typically defines widget areas, loading of custom JS and CSS, and the creation of custom admin menus and logic for the theme.<br />If you find yourself writing functions into a template view, STOP! Write the logic in the functions.php file and just call it in the template.<br />If your functions.php file becomes unmanageably large, don’t be afraid to break apart the logic with includes.<br />
  14. 14. Content Templates<br />Index.php<br />The initial ‘home page’ content. Default loads the most recent posts.<br />Page.php<br />Loads content classified as ‘pages’<br />?page_id=2<br />Archive.php<br />Loads posts from a specific group/taxonomy. <br />Categories<br />Tags<br />Authors<br />Dates<br />Single.php<br />Loads content from a single ‘post’<br />
  15. 15. The Loop<br />When a content page loads a query based on what kind of template it is (archive, single, page) run.<br />This primary query is accessed by “The Loop”<br />if ( have_posts() ) : while ( have_posts() ) : the_post();<br />//call our different template tags to retrieve data (title, date, post_content)<br />endwhile; else:<br />//default if we have no posts in the loop <br />endif; <br />You can alter this main query by pre-pending the loop with the query_posts() function.<br />query_posts(‘orderby=title&order=ASC');<br />query_posts() accepts many parameters.<br />http://codex.wordpress.org/Function_Reference/query_posts<br />
  16. 16. Retrieving Data about our Post(s)<br />Template tags are functions that run within ‘The Loop’ and echo back data.<br />the_title()<br />the_content()<br />the_permalink()<br /> There are also value-returning equivalents to most of these functions.<br />get_title()<br />get_permalink()<br />The $wp_query object (outside the loop or extra data)<br />All of the data about the loop is stored in this object<br />Within this object there are many arrays within this object<br />query_vars, request, comments, post, etc<br />The $post object<br />All of the data about the post is stored in this object<br />$post->comment_count , $post->post_modified, etc<br />http://codex.wordpress.org/Function_Reference/WP_Query<br />
  17. 17. Running Multiple Queries<br />Sometime we need to run additional queries on our pages (to get related posts perhaps).<br /><?php $related_posts = new WP_Query(‘cat=3&showposts=5');<br />while ($related_posts->have_posts()) : $related_posts->the_post(); ?><br /><div class=“related_post"><br /> <h2><?phpthe_title(); ?></h2><br /> <?phpthe_excerpt(); ?><br /> <a href="<?phpthe_permalink(); ?>”>Learn More</a><br /></div><br /><?phpendwhile; wp_reset_query(); ?><br />WP_Query accepts the same arguments as query_posts()<br />http://codex.wordpress.org/Function_Reference/query_posts<br />Note that you can query posts from post/page name or category name but I generally resist this approach due to the possibility of error.<br />Use wp_reset_query() to return back to the original query<br />
  18. 18. What NOT to do in Templates<br />Get, don’t build URL’s<br /><a href="'.get_bloginfo('url').'/category/'.$ctBX->category_nicename.‘”><br />get_category_link($id) or get_permalink($id)<br />Not checking if plugin function exists<br />if(function_exists(‘plugin_function’)):<br />plugin_function();<br />endif;<br />Don’t use URL to find location<br />if(isset($_GET[‘s’]) || $_SERVER[‘REQUEST_URI’] == ‘/index.php’)<br />if(is_search() || is_home())<br />Calling JS or CSS from template<br />ex. Loading jQuery from the template will NOT ensure that another plugin doesn’t load jQuery too. Sometimes different versions lead to conflicts and errors.<br />Should use the wp_enqueue_script and wp_enqueue_style in functions.php<br />
  19. 19. Things to Remember<br />Having modular plugins that can work with any theme pays off in the long run. Never write a plugin to be site-specific. Build it to be flexible and scalable, or let that feature exist only in the functions.php file of the parent theme.<br />Treat your theme files as views. That’s what they are so don’t make them more than that. Always add classes and/or id’s to elements to ensure that front-end styling is easy and effective.<br />If you find yourself copying/pasting snippets of code into theme files (like RSS feeds, videos, etc) turn that snippet into a widget and maintain only one piece of code.<br />Keeping core WordPress files and DB schema current is easy when following WP standards. Running the latest versions not only adds new features, but fixes bugs and security holes.<br />Remember that WordPress was not built for developers; it was built for users. The easy learning curve allows for most people to quickly start adding content to a website, but it is the responsibility of the developer to be the guardian of the output. <br />Remove all functional-level options from the user and let them access only what they are interested in—the content. <br />If aplugin requires multiple user-selected conditions to be fulfilled or code to be written into a template for it to even work, then it doesn’t work for WordPress.<br />Ultimately, WordPress is a platform that encourages its developers to innovate by creating an open system than can easily be manipulated, but we can’t do it at the cost of stability, scalability, and usability of our products.<br />