question
stringlengths 0
34.8k
| answer
stringlengths 0
28.3k
| title
stringlengths 7
150
| forum_tag
stringclasses 12
values |
---|---|---|---|
I have 3 categories with each 15 posts, I want to do ONE query to the db bringing only 5 first posts for each category, how can I do it? <code> $q = new WP_Query(array( 'post__in' => array(2,4,8), 'posts_per_page' => **FIRST_5_OF_EACH_CAT** )); </code> In case its not possible, what is more efficient, getting all the posts for the parent category and looping through them or creating 3 different queries? | What you want is possible but will require you to delve into SQL which I like to avoid whenever possible (not because I don't know it, I'm an advance SQL developer, but because in WordPress you want to use the API whenever possible to minimize future compatibility problems related to future potential database structure changes.) SQL with a <code> UNION </code> Operator is a Possibility To use SQL what you need is a <code> UNION </code> operator in your query, something like this assuming your category slugs are <code> "category-1" </code> , <code> "category-1" </code> and <code> "category-3" </code> : <code> SELECT * FROM wp_posts WHERE ID IN ( SELECT tr.object_id FROM wp_terms t INNER JOIN wp_term_taxonomy tt ON t.term_id = tt.term_id INNER JOIN wp_term_relationships tr ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.taxonomy='category' AND t.slug='category-1' LIMIT 5 UNION SELECT tr.object_id FROM wp_terms t INNER JOIN wp_term_taxonomy tt ON t.term_id = tt.term_id INNER JOIN wp_term_relationships tr ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.taxonomy='category' AND t.slug='category-2' LIMIT 5 UNION SELECT tr.object_id FROM wp_terms t INNER JOIN wp_term_taxonomy tt ON t.term_id = tt.term_id INNER JOIN wp_term_relationships tr ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.taxonomy='category' AND t.slug='category-3' LIMIT 5 ) </code> You can use SQL UNION with a <code> posts_join </code> Filter Using the above you can either just make the call directly or you can use a <code> posts_join </code> filter hook like as follows; note I'm using a PHP heredoc so be sure the <code> SQL; </code> is flush left. Also note I used a global var to allow you to define the categories outside of the hook by listing the category slugs in an array. You can put this code in a plugin or in your theme's <code> functions.php </code> file: <code> <?php global $top_5_for_each_category_join; $top_5_for_each_category_join = array('category-1','category-2','category-3'); add_filter('posts_join','top_5_for_each_category_join',10,2); function top_5_for_each_category_join($join,$query) { global $top_5_for_each_category_join; $unioned_selects = array(); foreach($top_5_for_each_category_join as $category) { $unioned_selects[] =<<<SQL SELECT object_id FROM wp_terms t INNER JOIN wp_term_taxonomy tt ON t.term_id = tt.term_id INNER JOIN wp_term_relationships tr ON tt.term_taxonomy_id = tr.term_taxonomy_id WHERE tt.taxonomy='category' AND t.slug='{$category}' LIMIT 5 SQL; } $unioned_selects = implode("\n\nUNION\n\n",$unioned_selects); return $join . " INNER JOIN ($unioned_selects) categories ON wp_posts.ID=categories.object_id " ; } </code> But There Can Be Side-effects Of course using the query modification hooks like <code> posts_join </code> always invites side-effects in that they act globally on queries and thus you usually need to wrap your modifications in an <code> if </code> that only uses it when needed and what criteria to test for can be tricky. Focus on Optimization Instead? However, I assume your question is concerned is more about optimization than about being able to do a top 5 time 3 query, right? If that is the case then maybe there are other options that use the WordPress API? Better to Use Transients API for Caching? I assume your posts won't change that often, correct? What if you accept the three (3) query hit periodically and then cache the results using the Transients API ? You'll get maintainable code and great performance; a good bit better than the <code> UNION </code> query above because WordPress will store the lists of posts as a serialized array in one record of the <code> wp_options </code> table. You can take the following example and drop into your web site's root as <code> test.php </code> to test this out: <code> <?php $timeout = 4; // 4 hours $categories = array('category-1','category-2','category-3'); include "wp-load.php"; $category_posts = get_transient('top5_posts_per_category'); if (!is_array($category_posts) || count($category_posts)==0) { echo "Hello Every {$timeout} hours!"; $category_posts = array(); foreach($categories as $category) { $posts = get_posts("post_type=post&numberposts=5&taxonomy=category&term={$category}"); foreach($posts as $post) { $category_posts[$post->ID] = $post; } } set_transient('top5_posts_per_category',$category_posts,60*60*$timeout); } header('Content-Type:text/plain'); print_r($category_posts); </code> Summary While yes you can do what you asked for using a SQL <code> UNION </code> query and the <code> posts_join </code> filter hook you are probably better offer using caching with the Transients API instead. Hope this helps? | Using WP_Query to Query Multiple Categories with Limited Posts Per Category? | wordpress |
what is option_name on database that store the information of current initiate widget in frontend sidebar ? | Solved. What EAmann said is right. The problem is in the configuration of the widget system in WordPress. For every multi-instance widget such as text, The information is stored in a different option name where the value of every widget store in a serialized manner. The trick is about how we store the serialized text widget's information that sometimes has special chars. We must use heredoc. The use of heredoc is to avoid the situation when a string must contain ['] and ["], because both can not be use on one line together. <code> $serialize_sidebar_widgets = <<< EOD a:7:{s:19:"wp_inactive_widgets";a:0:{}s:9:"sidebar-1";a:1:{i:0;s:6:"text-3";}s:9:"sidebar-2";a:0:{}s:9:"sidebar-3";a:0:{}s:9:"sidebar-4";a:0:{}s:9:"sidebar-5";a:0:{}s:13:"array_version";i:3;} EOD; $serialize_widgets_text = <<< EOD a:3:{i:2;a:0:{}i:3;a:3:{s:5:"title";s:5:"hello";s:4:"text";s:21:"saya hellokankamu yah";s:6:"filter";b:0;}s:12:"_multiwidget";i:1;} EOD; </code> Now we can store them in the database: <code> $wpdb->update( $wpdb->options, array( 'option_value' => $serialize_sidebar_widgets ), array( 'option_name' => 'sidebars_widgets' ) ); $wpdb->update( $wpdb->options, array( 'option_value' => $serialize_widgets_text ), array( 'option_name' => 'widget_text' ) ); </code> PS: If we store multi-instance widgets then we should remember that the widgets have their own configuration. For example, text widget is stored in 'widget_text' PS: Read how to use heredoc in PHP . | what is option_name on database that store the information of current initiate widget in frontend sidebar? | wordpress |
Sometimes it might be necessary to include frequently-changing content in a theme, but themes take some time to modify, it may also be necessary to let a non-technical user maintain some content that appears on more than one page. Is it possible (without heavily impacting performance) to include a post in a theme? | You can but I think it's far more easier for you theme to add a sidebar and then place a text-widget (or any other widget) inside there because that's far more flexible. What you describe I did for some sites longer ago. You can just load the post and display it. I used <code> query_posts() </code> to get the post(s) and then <code> have_posts() </code> , <code> query_posts() </code> , <code> the_content() </code> and so on to display it within the template files (e.g. probably <code> footer.php </code> in your case). | How can I include a post in a theme? | wordpress |
I am using a WordPress theme which has just header and footer. I would like to continue using it by changing the width and adding side bars. Could anyone help me to change the width (to fit to the screen) of the theme. Does anybody have an idea on how to add sidebars to this theme? ========== Sorry for not making clear in my earlier question. The theme I am using is Minicard The lines similar to ... <code> if (function_exists('register_sidebar') ) register_sidebar(array( 'name' => 'Sidebar Widgets', 'before_widget' => '<div id="%1$s" class="widget %2$s">', 'after_widget' => '</div>', 'before_title' => '<h3 class="widgettitle">', 'after_title' => '</h3>' )); </code> are already there. This is the code I found there: <code> if ( function_exists('register_sidebar') ) { register_sidebar(array( 'name' => __('Beneath the Card (Top)', 'minicard'), 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => '<div class="clear"></div></li>', 'before_title' => '<h2 class="section widgettitle">', 'after_title' => '</h2>', )); register_sidebar(array( 'name' => __('Beneath the Card (Bottom)', 'minicard'), 'before_widget' => '<li id="%1$s" class="widget %2$s">', 'after_widget' => '<div class="clear"></div></li>', 'before_title' => '<h2 class="section widgettitle">', 'after_title' => '</h2>', )); } </code> So I have created <code> sidebar.php </code> file and added the code you have given for side bar. Later I have tried to add the following code: <code> #sidebar { width: 240px; float:right; padding:0 20px 20px; } </code> to CSS. After making these changes I've looked for the sidebar and I havn't found any additional one. | Generally you can change the width from <code> style.css </code> file, which is located in the themes directory ( use firebug to determine the element ). For adding sidebars... use this tutorial . | Is there possibility to Customize the present theme adding sidebars | wordpress |
How can you have it so that the site's home page will only show the first X (let's say 300) words of the post? But without using "more" tag, or hand filled excerpts? I am looking for a plugin/hack for WP 2.9 and onward. I came across several solutions so far, but am hoping for a recommended solution. Challenges I came a cross so far: What happens in case a tag (for example ) starts on word 295, and ends after word 301 ? Can it be possible to have a different X for the home page , tags page, category page - and so on? Can the format of the text be preserved? (all the images and text formating)? Having the plugin take the least amount of recourses from the server. | Changing the word count on the home page is easy: <code> if( is_home() ) add_filter( 'excerpt_length', create_function( '', 'return 300;' ) ); </code> Just replicate that code and change the conditional check to add this to other pages. The other option is to just insert the code on the template page ( <code> home.php </code> , <code> tag.php </code> , etc.), so you know it's going to be set on the correct page. Using <code> the_excerpt() </code> will automatically strip shortcodes and html from the content if there's no excerpt provided. You can remove these filters, but it makes it much much harder to do word counts when you're adding markup into the mix. If you want the formatting/text/images preserved, that's what the <code> more </code> tag is for. It's inserted manually because it's too difficult to automatically figure out in all instances where that break should go. | How to only show the first X words (from each post) on the home page? | wordpress |
What are the options for Content Distribution Networks for use with WordPress ? I'd like to their objective pros and cons, their associated plugins or other ways to utilize them, their relative pricing, their appropriate customer profiles/scenarios/use-cases, projects they've been used on if you know of any, and any other relevant information. This is a community wiki and so please provide only one CDN option per answer and please don't duplicate answers. If you have something to include regarding a CDN already listed please either edit the answer or add comments. And please vote up the solutions you recommend and/or think are most viable. UPDATE : I found few resources on the web for WordPress+CDN so decided to list them here too: HowTo: Configure Wordpress To Use A Content Delivery Network (CDN) rewriting URLs for using a CDN for your Wordpress blog how to copy your Wordpress files to CloudFront efficiently Using a CDN for your WordPress blog Using a CDN with WordPress Plugin: WordPress Caching with CDN Integration Free CDN Plugin CDN Tools Plugin My CDN Plugin | Amazon CloudFront Amazon CloudFront is an CDN 'wrapper' around Amazon's S3 service. Distributions can be created from existing S3 buckets, and when a file is requested from it's CloudFront URL it is either served from the nearest edge locations's cache or fetched from S3 and cached. Plugins My CDN - handles URL rewriting of JS, CSS, and other theme resources. This plugin only handles the URL rewriting and not actually transferring files into Amazon S3. W3 Total Cache - A more comprehensive plugin, handles Cloudfront integration as well as other techniques to improve page load times, such as caching and minification. Pros Low barrier to entry - you don't buy bandwidth upfront, instead paying for what you use. Quick to setup A variety of tools and programs are available for managing the files you have on S3/CloudFront Supports media streaming Cons Relatively expensive compared to some other services where bandwidth is purchased in advance Use Cases Amazon lists a few use cases on their CloudFront product page , including hosting frequently accessed content, distributing software, and publishing media files. In terms of businesses using CloudFront as their CDN, Linden Lab (the makers of Second Life) use CF for distributing their software client, while storing other files on S3. Amazon also has a very good case study on how photoWALL uses CF (and the other infrastructure AWS offers) | Options for CDN with WordPress Including Supporting Plugins? | wordpress |
I just ran over a problem to properly use the count of external (meaning no relative or absolute links to my own blog) links on my blog for the Comment Moderation count Option. It's labeled Hold a comment in the queue if it contains [your number here] or more links. (A common characteristic of comment spam is a large number of hyperlinks.) on Settings -> Discussion in the Wordpress Back-end. Screenshot: I'm aware that currently it counts all links inkl. links to the blog and other comments (reported it here: #14681 ) but I can't imagine that there isn't a plugin or hack already available that properly corrects the count to only external links. So my question is: Is there a plugin / hack that makes Wordpress properly count only the external links in comments for it's Moderation Options? | Haha, I actually figured out a way to do this. As a plugin, this should work. <code> class JPB_CommentCounter { var $count = 0; function __construct(){ add_filter( 'pre_comment_content', array( $this, 'content' ), 100 ); add_filter( 'comment_max_links_url', array( $this, 'counter' ) ); } function JPB_CommentCounter(){ $this->__construct(); } function counter( $num, $url ){ if($this->count < 1) return $num; elseif( $this->count > $num ) return 0; else return $num - $this->count; } function content( $content ){ $homeurl = preg_quote( home_url() ); if( preg_match_all( '@<a [^>]*href=['|"](/|'.$homeurl.')@i', $content, $matches ) ) $this->count = count($matches[0]); return $content; } } $JPBCC = new JPB_CommentCounter(); </code> I should add that I have not in any way tested this. But it should theoretically work. | Number of External Links in Comments - Moderation Option | wordpress |
I recently added the following into my theme's <code> functions.php </code> , in order to load jQuery from the CDN: <code> function my_init_method() { wp_deregister_script('jquery'); wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js'); } add_action('init', 'my_init_method'); </code> However, this causes problems with the admin screens, notably the WYSIWYG editor which then refuses to allow HTML mode (via the tab). I get an error: <code> jQuery is not defined </code> from the wp-admin/load_scripts.php file. What am I doing wrong? | jQuery is not defined This is because the Google CDN Jquery is not in no-conflict mode. Use the following to make sure the included WordPress no-conflict jquery is used in admin. <code> if( !is_admin()){ wp_deregister_script('jquery'); wp_register_script('jquery', ("http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"), false, '1.4.2'); wp_enqueue_script('jquery'); } </code> | Registering jQuery kills admin functions | wordpress |
WordPress is undoubtely very customizable using plugins, but every customization possibility surely has limits defined by the underlying architecture. For those familiar with WP architecture and source code: What would be the effort required to customize the data layer used by WP to use another data store (e.g. files (or another database system) instead of MySQL?). Is WordPress architecture layered in the sense of having the possibility to switch layers? The UI layer is apparently very easy to switch (any theme does this), but how about other layers, namely the data layer? | Wordpress is not designed to have a replace-able database layer. Computer Science has some different concepts in it's chest to deal with different databases in the same application on different level of abstraction, Wordpress does not tend to make use of any of such. To say it in more simple words: Not at all. But wordpress offers the ability to replace it's own code with some other code, for example the whole database class. That is not always (read: normally) enough to replace the whole database layer but helps tinkering. The WPDB class replacing HyperDB for example does not add a new database layer in full, but handles multiple MySQL servers instead of one, which is a well known example (this is considered bad practice to do with PHP, there are better ways, but it's a good example what can be done). Next to replacing the database class, Wordpress has the ability that even more code can be replaced and you can completely change it, e.g. creating an own distribution that takes care of everything regarding the database layer on it's own. If you want to see a real life example on how to replace the whole database layer, so to make wordpress use a totally different type of database server (here: MSSQL instead of the hardcoded MySQL), you find a full distribution and a patch here: WordPress on SQL Server Distro & Patch It's free software you can study how such a database layer can be implemented, the website provides more information about that topic as well. Tip: Don't fight Wordpress. Stick to MySQL and that's it. Otherwise look for something else better designed to fit your needs. Just take the right tool for the job. | Is it possible to switch the data layer within WordPress? | wordpress |
Let's say I'm doing a site about cars, and in the main content area of a Page (using a certain template), there are a few paragraphs about a particular car. In the sidebar, are several standard widgets. But I also want a widget with an 'info panel' about the particular car. So what's the sanest way of putting in a per-page widget in Wordpress? I guess ideally the info-panel could be entered via the standard page editing in Wordpress .. perhaps via the Custom Fields, so you could enter "Volvo" for the Manufacturer field and it would show up in the sidebar. (or is this something a plug-in already covers?) | You want the Widget Logic Plugin if you're going to use widgets to do this. However, as you have guessed, this is not the best way to do this. I think the best way to achieve what you want to do is to create a custom widget that accesses the posts information if it detects that it's on the correct page. Something like this: <code> global $wp_query; $custom_data = get_post_meta( $wp_query->post->ID, 'your_custom_postmeta_key', true ); if( is_page() && !empty( $custom_data ) ){ echo $before_widget . $before_title . $title . $after_title; echo apply_filters( 'the_content', $custom_data ); echo $after_widget; } </code> If you stick that inside the normal widget structure , that would be pretty effective at creating a per-page widget that only appears if you're on a page and that page has the meta content relevant to the widget. At that point, you could just use the custom fields that WordPress already provides on the pages to input the custom content. | Custom per-page sidebar widgets .. possible? | wordpress |
You may have learned already to reconfigure your WP3 so that it loads in MU mode, and set it for subdomains. Evidently my Dallas client claims that instead of just subdomains , there are some tricks you can do (cpanel? wp-admin? plugin? config file change?) to make a full domain like example.com for a subdomain, instead of having a subdomain like blog1.example.com . Is this true? How is it achieved? Does it have any caveats that you can think of? | You can map regular domains to a WordPress Multisite installation using the WordPress MU Domain Mapping plugin . There's also a great tutorial available: WordPress 3.0: Multisite Domain Mapping Tutorial For reference ... stackexchange-url ("I asked a similar question yesterday"). I have a client who hosts multiple blogs with unique domains, but it becomes a hassle to maintain each one separately. I'm working with them to transition to a Multisite setup instead - single superuser admin, single set of plug-ins, single set of themes, single set of core files ... much easier to upgrade and maintain. | Full Domain Mapping with WP3 in Multiuser Mode | wordpress |
Let's say I have a website about different types of cars. The structure is a little like this: <code> -Home -Cars (shows a submenu with a list of cars, ie Volvo 850, Porsche 911 ) -Volvo 850 overview (the page you get when you click Volvo 850 on the Car page) -Volvo 850 tech spec (the three Volvo pages are shown as submenu links on any Volvo page) -Volvo 850 pictures -Porsche 911 overview -Porsche 911 tech spec -Porsche 911 pictures </code> What's the best way of doing this? I guess what I'm asking is how to automatically make the Cars page list the different Cars, and link to the overview page and not the others. And then on the individual car pages, have more sub-menus for overview, tech spec, and pictures page. I could have a structure like this: <code> -Cars (shows a submenu with a list of cars, ie Volvo 850, Porsche 911 ) -Volvo 850 -Volvo 850 overview (the page you get when you click Volvo 850 on the Car page) -Volvo 850 tech spec (the three Volvo pages are shown as submenu links on any Volvo page) -Volvo 850 pictures </code> .. but I don't want that intermediate Volvo 850 page to show, because there would be nothing on it. | Referencing the wp_list_pages function reference You'll probably need to use the second structure you listed, with one change: <code> -Cars (shows a submenu with a list of cars, ie Volvo 850, Porsche 911 ) -Volvo 850 overview (the page you get when you click Volvo 850 on the Car page) -Volvo 850 tech spec (the three Volvo pages are shown as submenu links on any Volvo page) -Volvo 850 pictures </code> I think the following may work, although it might show all descendants (rather than immediate children only): <code> <?php if($post->post_parent) $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0"); else $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0"); if ($children) { ?> <ul> <?php echo $children; ?> </ul> <?php } ?> </code> Your statement And then on the individual car pages, have more sub-menus for overview, tech spec, and pictures page. Seems contradictory to not wanting an 'intermediate' page, since you said you want the "overview" page to be what you land on when clicking on a car model on the cars page. If you just want all pages related to the Volvo 850 to have a listing of Volvo 850 pages (for instance, in the sidebar), you could possibly use this : <code> <?php // use wp_list_pages to display parent and all child pages all generations (a tree with parent) $parent = 93; $args=array( 'child_of' => $parent ); $pages = get_pages($args); if ($pages) { $pageids = array(); foreach ($pages as $page) { $pageids[]= $page->ID; } $args=array( 'title_li' => 'Tree of Parent Page ' . $parent, 'include' => $parent . ',' . implode(",", $pageids) ); wp_list_pages($args); } ?> </code> | Automatically going to the first page in a hierarchy? | wordpress |
(note: this question was originally about Custom Fields, but @MikeSchinkel had a better solution involving Custom Post Types) On my site I have several pages which I want to show the same data in the sidebar. For instance, in a structure like this: <code> -Home -Cars -Volvo 850 overview -Volvo 850 tech spec -Volvo 850 pictures -Porsche 911 overview -Porsche 911 tech spec -Porsche 911 pictures -Roads -Route 66 overview -Route 66 history -Route 66 pictures -Pan-American Highway overview -Pan-American Highway history -Pan-American Highway pictures </code> I would like all the Volvo 850 pages to show the same data in the sidebar, all the Porsche pages to show a different set of data (for instance Speed, Maker, etc). The Road pages would have their own set of data for each road. Cars and Roads would also have there own page template, and the way I figure it would get the right sidebar is something like this within sidebar.php: <code> if ( is_page_template('car-profile-template.php') ) : // show car widgets </code> Here's an example page, the Volvo 850 Pictures page. The same (left) sidebar should appear on the other Volvo 850 pages, while the stuff on the right is just page content. <code> | Home •Cars Roads | -------------------------------------------------------- | Overview | Volvo 840 Pictures | | Tech Spec | (some pics) | | •Pictures | | ------------------ | | -Specs- | | | Volvo 850 | | | Speed:150mph | | | Maker:Volvo | | | Download PDF | | ------------------ | | -Rating- | | | Style:3 | | | Safety:5 | | | Reliablity:4 | | ------------------ | </code> In this example, the two sidebar widgets, Specs and Rating should be getting their info from a Custom Post Type. Is there a method, which would be easy for the end-user to edit, which means that they would have to enter this custom data only once? It may not be necessary for each of the fields to be separate (ie all of Spec could be entered within an Editor field, and all of Rating could be put in Excerpt field.. maybe) | UPDATE: Based upon the update of the question I think I need to explicitly state that what is asked in the question can be done with the answer below, just used custom fields in the "Car" custom post type for each of the items you want displayed on all pages for a given car. If you want to do it simply just hardcode the sidebar into the <code> single-car.php </code> template file I included below and then use your <code> if </code> statement to determine which content to display for the different URLs. You could go to the effort to widgetize your sidebar and develop a custom widget where the widget would pull the information for the current post ID, but why both unless you are building this as a theme for other people to use? There are actually a bunch of subtly different ways to accomplish this but the one I am suggesting should wonder wonderfully for your needs. Hi @cannyboy: I actually don't know what the best way would be to share custom fields across posts. But that might just be the red flag you need. If something seems too hard maybe... An Alternate Approach? ...you could shonsider architecting it differently ? I think you'll be much better off creating a Custom Post Type of "Car" and then you can store everything for each "page" into the one Car post type. Here are some sample URLs: <code> http://example.com/cars/volvo850/ <-- overview http://example.com/cars/volvo850/tech-specs/ http://example.com/cars/volvo850/pictures/ </code> Learning about Custom Post Types You can learn more about Custom Post Types at the answers to these questions: stackexchange-url ("Tips for using WordPress as a CMS?") stackexchange-url ("Can a CrunchBase.com clone be implemented using WordPress?") A Custom Post Type and A Rewrite Rule To implement Custom Post Types and the multiple pages you'd use code like the following which registers your "Car" Custom Post Type and then sets a rewrite rule for your car pages . Put this code in your theme's <code> functions.php </code> file or in a plugin, whichever you prefer: <code> <?php add_action('init','car_init'); function car_init() { register_post_type('car', array( 'label' => 'Cars', 'public' => true, 'show_ui' => true, 'query_var' => 'car', 'rewrite' => array('slug' => 'cars'), 'hierarchical' => true, //'supports' => array('title','editor','custom-fields'), ) ); global $wp,$wp_rewrite; $wp->add_query_var('car-page'); $wp_rewrite->add_rule('cars/([^/]+)/(tech-specs|pictures)','index.php?car=$matches[1]&car-page=$matches[2]', 'top'); $wp_rewrite->flush_rules(false); // This should really be done in a plugin activation } </code> A Car -specific Theme Template File Then you'll need a Car -specific template file in your theme ; the default name for this would be <code> single-car.php </code> . I've coded a starter template for you that renders all three of the URLs (the (overview) , 'tech-specs' and 'pictures' ) in one template by using an if statement to determine which content to render: <code> <?php get_header(); ?> <div id="container"> <div id="content"> <?php if ( have_posts() ): the_post(); ?> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h1 class="entry-title"><?php the_title(); ?></h1> <div class="entry-content"> <?php if(is_car_techspecs()): ?> <a href="..">Back</a> <h1>Tech Specs</h1> The tech specs go here! <?php get_post_meta($post->ID,'_car_tech_specs'); ?> <?php elseif (is_car_pictures()): ?> <a href="..">Back</a> <h1>Pictures</h1> Car Pictures go here! <?php get_post_meta($post->ID,'_car_pictures'); ?> <?php else: ?> <ul> <h1>Overview</h1> <li><a href="tech-specs/">Tech Specs</a></li> <li><a href="pictures/">Pictures</a></li> </ul> <?php the_content(); ?> <?php endif; ?> <?php the_content(); ?> </div> <?php endif; ?> </div> </div> <?php get_sidebar(); ?> <?php get_footer(); ?> </code> Note in the example above I'm being very simplistic with the use of <code> get_post_meta() </code> ; real site would need to have a lot more complexity there. Template Tags a.k.a. Helper Functions Of course I used some template tags a.k.a. helper functions to minimize complexity in the template file in the if statement conditions. Here they are and you can put these in your theme's <code> functions.php </code> file too: <code> function is_car_techspecs() { global $wp_query; return is_car_page('tech-specs'); } function is_car_pictures() { global $wp_query; return is_car_page('pictures'); } function is_car_page($page) { global $wp_query; return (isset($wp_query->query['car-page']) && $wp_query->query['car-page']==$page); } </code> Screenshots filled with Custom Post Type Love Once you have all that code in place and you've added a Car post like Volvo 850 you can get it to work like the following screenshots: Overview Page Tech Specs Page Pictures Page | Custom Post Type Data in Sidebar widgets? | wordpress |
As part of a theme for a client, I want to be able to show a custom menu (defined via the admin) in a select box that automatically changes pages after changing the selection . Is there a plugin (or a handy code snippet) that will accomplish this? | Hi @Keith S. : WordPress' new menu system is both wondrous and infinitely frustrating , depending on what you are trying to do and what day of the week it happens to be. :) It's a great idea but far from mature so while it's a feature I applaud I'll be happier when v3.3 or v3.4 of WordPress rolls out and we get a lot more use-cases directly supported by the menu system's API. That said, not sure if there is an existing plugin to do what you are looking for, but how about the code you need to write you own plugin? Or you could just include it in your theme's <code> functions.php </code> file; whatever your preference. What I'm providing is a fully self-contained example that you can save as <code> test.php </code> in your website's root directory in order to test it. If your domain were <code> example.com </code> you'd load to test at: <code> http://example.com/test.php </code> Here's what it look's like in action: From the code below it should be easy to incorporate the <code> get_page_selector() </code> function into your theme and to call it whenever you need this functionality: <code> <?php include "wp-load.php"; echo 'Jump to:'; echo get_page_selector('My Select Menu'); function get_page_selector($menu) { $page_menu_items = wp_get_nav_menu_items($menu,array( 'meta_key'=>'_menu_item_object', 'meta_value'=>'page', )); $selector = array(); if (is_array($page_menu_items) && count($page_menu_items)>0) { $selector[] =<<<HTML <select id="page-selector" name="page-selector" onchange="location.href = document.getElementById('page-selector').value;"> HTML; $selector[] = '<option value="">Select a Page</option>'; foreach($page_menu_items as $page_menu_item) { $link = get_page_link($page_menu_item->object_id); $selector[] =<<<HTML <option value="{$link}">{$page_menu_item->title}</option> HTML; } $selector[] = '</select>'; } return implode("\n",$selector); } </code> So you might wonder how it works? The <code> wp_get_nav_menu_items() </code> function WordPress 3.0 stores it's menus in the <code> wp_posts </code> table as <code> post_type </code> type of <code> nav_menu_item </code> . The <code> wp_get_nav_menu_items() </code> indirectly just calls the <code> get_posts() </code> function. The first parameter to <code> wp_get_nav_menu_items() </code> is either 1.) a menu name (which is what I used: "My Select Menu" ), 2.) a menu item ID (i.e. the menu item's post <code> ID </code> the database) or 3.) a menu slug (the slug from the menu's taxonomy term; yes menus are implemented using taxonomy terms with a taxonomy of <code> 'nav_menu' </code> .) Beyond the first parameter it forwards on to <code> get_posts() </code> most (if not all?) of the <code> $args </code> you pass to <code> wp_get_nav_menu_items() </code> thus you can treat it like a custom post type (even though longer term when they improve the menu API that probably won't be such a great idea. But today? Make hay while the sun shines!) Filtering Menu Items with <code> meta_key </code> and <code> meta_value </code> WordPress' underlying use of posts for menu items is why we can query for <code> meta_key </code> and <code> meta_value </code> ; WordPress uses a series of <code> meta_keys </code> prefixed with <code> _menu_item </code> for the additional information it needs for each menu item. <code> _menu_item_object </code> will contain <code> page </code> for every menu item that corresponds to a WordPress "Page" post type. (If you want to include items besides Pages you you'll need to do a bit more research than I did here but at least I gave you the tools you need to do the research yourself.) Here's a screenshot using Navicat for MySQL of a query showing the meta records for several <code> nav_menu_items </code> : Grabbing the Page's URL with <code> get_post_link() </code> Next I'll point out that get the page's URL from the <code> get_post_link() </code> function and that I'm setting the HTML <code> <option> </code> 's <code> value </code> to be the URL... <code> <?php $link = get_page_link($page_menu_item->object_id); $selector[] =<<<HTML <option value="{$link}">{$page_menu_item->title}</option> HTML; </code> Using Javascript's <code> onchange </code> to Navigate to our Selected Page ...So that I can grab it from the <code> value </code> property of the <code> 'page-selector' </code> <code> <select> </code> element and assign it to <code> location.href </code> . Assigning <code> location.href </code> causes the browser to immediately navigate to the new URL, and that, in a nutshell, is how it's all done: <code> <?php $selector[] =<<<HTML <select id="page-selector" name="page-selector" onchange="location.href = document.getElementById('page-selector').value;"> HTML; </code> An Empty <code> value="" </code> as the Default Option You might note that the "Select a Page" default option has an empty value; that's not a mistake but instead by design. When it is selected and the <code> "onchange" </code> is triggered 1 setting <code> location.href </code> to an empty string will have no effect, which is exactly what we want and it doesn't require us to write an exception code. Viola! <code> <?php $selector[] = '<option value="">Select a Page</option>'; </code> Having selection of "Select a Page" trigger <code> "onchange" </code> can only happen on a browser back navigation to a page that doesn't trigger a page reload where another option had previously been selected, but it can still happen so we should address it. | Show a WP 3.0 Custom Menu in an HTML Select with Auto-Navigation? | wordpress |
In your experience, when is the time one needs to start thinking about scaling up? What is the expected performance of a common WordPress installation on a standard Apache web server, without any [performance tweaks or plugins] (stackexchange-url ("Steps to Optimize WordPress in Regard to Server Load?"))? In terms of page loads (let's assume no caching): Is it in range of 100's/1000's/+ of page loads per second? In terms of traffic: At which number of users per day can one expect to start hitting performance bottlenecks (ignoring traffic, assuming great connection)? | A lot of this is very subjective and hard to answer because of different server environments, themes, size of database etc. In your experience, when is the time one needs to start thinking about scaling up? If you are concerned with your users experience you should already be practicing sound front end performance techniques. When is it time to scale up? When your users experience starts degrading and slow page loads are causing your bounce rate to increase. What is the expected performance of a common WordPress installation on a standard Apache web server, without any performance tweaks or plugins? A common WordPress installation running the default theme for a small to medium blog on one of the recommended shared hosts should be able to handle hundreds of users a day without issue. In terms of page loads (let's assume no caching): Is it in range of 100's/1000's/+ of page loads per second? For this question I ran a Apache Benchmark on a WordPress installation running the default 2010 theme with no caching. I made 500 requests at 10 requests per second and was able to average 3.6 requests per second but as the requests started piling up the longest request took almost 2 minutes. In terms of traffic: At which number of users per day can one expect to start hitting performance bottlenecks (ignoring traffic, assuming great connection)? It is impossible to answer this question without running load tests or benchmarks on the server. For the benchmark above you would start having bottlenecks anytime there were more than 10 users using the site at once. | What is the expected limit for acceptable performance of WordPress without any adjustments? | wordpress |
I am having a problem with CPU usage on my website, and am looking for a way to detect (and fix) what is causing it. A topic not covered in stackexchange-url ("this question"). Following on stackexchange-url ("Hakre answer here"), I now realize that what I need to do is profile my PHP calling. Is it reasonable to put the website on my own computer, run the profiler, and use that information to improve my website? Any other suggestions on how to do this in the best way? | Profiling with Profiler-Plugins Not sure exactly what you need to accomplish with your profiling, but WP Tuner (Wordpress Plugin) goes a long way to finding what is slowing down your WP install. It looks at each plugin and give your the memory, CPU time and SQL queries involved. The SQL Monitor (Wordpress Plugin) analyzes SQL performance. Combine it with W3 Total Cache (Wordpress Plugin) and you should get better performance on any platform. Also, look to using transient API to store fragments you do not need to generate everytime. This can really help on a slow DB. | Profiling a WordPress Website for Deployment on Shared Hosting? | wordpress |
I've got a spreadsheet where each row of the first column is a question, and the next 4 columns are the optional 4 answers to that question. I want to turn these questions into an online form (like as the one offered by google docs) Is there a form plugin (or another solution) that can offer something like this? | Your best option for a form plugin is Gravity Forms . It has the ability to create multiple choice options via a drop down or check box and you can use conditional logic that will display fields based on choices in previous fields. I highly recommend it. | Creating an online questionnaire form - by Importing the questions from a spreadsheet? | wordpress |
Is there a way to draw the categories listing and highlight the current category being viewed? In addition, it would be great to highlight the current category if a post or page that's assigned to it is being viewed. Any help much appreciated... Here's my current code (I'm excluding the default "uncategorized" category)... <code> echo "<div class='menu top'><ul>"; $cat_args = array('orderby' => 'name', 'show_count' => $c, 'hierarchical' => $h); $cat_args['title_li'] = ''; $cat_args['exclude_tree'] = 1; wp_list_categories(apply_filters('widget_categories_args', $cat_args)); echo "</ul></div>"; </code> | The Wordpress Codex for the wp_list_categories tag is actually pretty helpful here - Wordpress is already assigning a class to the < li > tag of the current category. At that point you just need to add an entry to your theme's .css file to apply whatever highlighting you want to that class. For instance: <code> li.current-cat { background: #CCC; } </code> Should give you a nice grey background. | Categories Listing with "selected" category highlighted | wordpress |
If I have a couple of different Page templates, how would I show a different collection of sidebar widgets for each of these templates? I'm using the Starkers theme as a starting point. | You will need to create more sidebars in your functions.php file and then edit the page templates to call the sidebar you want. Adding sidebars Go in to your functions.php file. You should see some sidebars already being registered. The code will look something like this: <code> //Adds default sidebar if ( function_exists('register_sidebar') ) register_sidebar(); </code> To add another sidebar, add the following code any number of times after the existing sidebar registration. <code> //Registers new sidebar if ( function_exists('register_sidebar') ) { register_sidebar(array('name' => 'Name Sidebar Here','before_widget' => '','after_widget' => '','before_title' => '<h2 class="widgettitle">','after_title' => '</h2>')); } </code> Where it says 'Name Sidebar Here' put a logical name for this new sidebar. The rest of the array allows you to put HTML before the widget (before_widget) if your theme requires that for its design and put HTML after the widget (after_widget). Also, more commonly used in themes is a custom style for widget titles. You can put that HTML before the title (before_title) and after the title (after_title). In the example above, each widget title will have <code> <h2 class="widgettitle"> </code> placed before it and after it to close the opening tag. Add your new sidebar to your page templates Now that you've added a sidebar, you'll need to put it in the page template where you want it. Find where the default sidebar is being called inside of your template ( usually ) and replace it with the following, where the number is the order of where the sidebar was added in functions.php file. <code> <?phpif ( !function_exists('dynamic_sidebar') || !dynamic_sidebar(Sidebar number here) ) : ?><?php endif; ?> </code> This sidebar was the second one added in the functions.php file, so to call it in the page template, you'll put 2 inside of <code> !dynamic_sidebar(Put sidebar number here) ) </code> . Add widgets Once you've added it to the page template, just add widgets to the sidebar in your Appearance--> Widgets administration page. The new sidebar will appear there with the name you gave it in the functions.php file. Hope this helps! | Different widgets on different page templates? | wordpress |
I have some users who are posting to a group blog and are able to cut-and-paste but their pastes include things like: <code> <!– /* Font Definitions */ @font-face {font-family:”Cambria Math”; panose-1:2 4 5 3 5 4 6 3 2 4; mso-font-charset:1; mso-generic-font-family:roman; mso-font-format:other; mso-font-pitch:variable; mso-font-signature:0 0 0 0 0 0;} @font-face {font-family:Calibri; panose-1:2 15 5 2 2 2 4 3 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:-520092929 1073786111 9 0 415 0;} @font-face {font-family:”Trebuchet MS”; panose-1:2 11 6 3 2 2 2 2 2 4; mso-font-charset:0; mso-generic-font-family:swiss; mso-font-pitch:variable; mso-font-signature:647 0 0 0 159 0;} /* Style Definitions */ p.MsoNormal, li.MsoNormal, div.MsoNormal {mso-style-unhide:no; mso-style-qformat:yes; mso-style-parent:”"; margin-top:0in; margin-right:0in; margin-bottom:10.0pt; margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:12.0pt; font-family:”Trebuchet MS”,”sans-serif”; mso-fareast-font-family:Calibri; mso-fareast-theme-font:minor-latin; mso-bidi-font-family:”Times New Roman”; mso-bidi-theme-font:minor-bidi; color:black;} p {mso-style-noshow:yes; mso-style-priority:99; mso-margin-top-alt:auto; margin-right:0in; mso-margin-bottom-alt:auto; margin-left:0in; mso-pagination:widow-orphan; font-size:12.0pt; font-family:”Times New Roman”,”serif”; mso-fareast-font-family:”Times New Roman”;} .MsoChpDefault {mso-style-type:export-only; mso-default-props:yes; font-size:12.0pt; mso-ansi-font-size:12.0pt; mso-bidi-font-size:12.0pt; mso-ascii-font-family:”Trebuchet MS”; mso-fareast-font-family:Calibri; mso-fareast-theme-font:minor-latin; mso-hansi-font-family:”Trebuchet MS”; mso-bidi-font-family:”Times New Roman”; mso-bidi-theme-font:minor-bidi; color:black;} .MsoPapDefault {mso-style-type:export-only; margin-bottom:10.0pt; line-height:115%;} @page WordSection1 {size:8.5in 11.0in; margin:1.0in 1.0in 1.0in 1.0in; mso-header-margin:.5in; mso-footer-margin:.5in; mso-paper-source:0;} div.WordSection1 {page:WordSection1;} –> /* Style Definitions */ table.MsoNormalTable {mso-style-name:”Table Normal”; mso-tstyle-rowband-size:0; mso-tstyle-colband-size:0; mso-style-noshow:yes; mso-style-priority:99; mso-style-qformat:yes; mso-style-parent:”"; mso-padding-alt:0in 5.4pt 0in 5.4pt; mso-para-margin-top:0in; mso-para-margin-right:0in; mso-para-margin-bottom:10.0pt; mso-para-margin-left:0in; line-height:115%; mso-pagination:widow-orphan; font-size:11.0pt; font-family:”Calibri”,”sans-serif”; mso-ascii-font-family:Calibri; mso-ascii-theme-font:minor-latin; mso-fareast-font-family:”Times New Roman”; mso-fareast-theme-font:minor-fareast; mso-hansi-font-family:Calibri; mso-hansi-theme-font:minor-latin; mso-bidi-font-family:”Times New Roman”; mso-bidi-theme-font:minor-bidi;} </code> What can I do to filter out code like this automatically? | There is a button on the visual text editor built in to WordPress that will strip Microsoft Word formating. It is labeled "Paste From Word" | How can I filter Microsoft Word gunk from pasted content? | wordpress |
I just finished a tutorial that told me to create my <code> header.php </code> without closing a tag at the bottom of the included file. Now while I realize that in anyone of the parent files which includes <code> header.php </code> it includes the closing tag; this really goes against my better judgement as a front-end developer; because someone who edits the theme later (and it could be me, it could be somebody else) would have to know that this tag needed to be closed in the parent file which includes it. It just feels wrong. It feels like when your editor marks the tag as "an extra closing tag" you want to delete it. I'm not breaking a standard if I use: <code> <?php include(TEMPLATEPATH . '/justTheHTMLHeader.php'); ?> <!-- AND --> <?php include(TEMPLATEPATH . '/justTheBlogHeader.php');` ?> </code> instead of <code> get_header() </code> ? It seems to me that this approach would be more modular and not leave any extraneous tags not closed between included files and their parents. I also noticed that the default Wordpress template is setup this way, so I'm obviously wrong and breaking some sort of Wordpress theme standard not matter what I think. What's the reasoning behind this? | Well, that tutorial is pretty old and out of date. It was written for WordPress 2.0; 10 major releases ago. The short answer is: it's done that way because it's the best way to do it. It's the fastest/simplest way to separate content from design and give all the control to you, the theme developer. If you don't want to open a tag in the header without closing it in the header, don't. I personally always do that (although I usually close it in the footer, not the index.php file). The great thing about WordPress is that it lets you do whatever you want. Here are two good reasons to use <code> get_header() </code> : It fires an action hook that plugins may be using, and It makes your theme more compliant and therefore easier to use as a template for child themes. | Wordpress Theme Development Seemingly Awful Partitioning of Includes? | wordpress |
I have some utility categories that are only used by my theme. To help separate these categories I place them all as children of uncategorized. How can I make sure that any call to wp_list_categories() excludes the child categories under "uncategorized" cat_id = 1? I want this to work even if the call wp_list_categories() comes from a third party plugin that I don't control. Perhaps a filter I can place in functions.php that intercepts any call for the wp_list_categories() function to attach the exlude_tree = '1' to the arguments. For example, in my own categories plugin widget, I use this... <code> <ul> <?php $cat_args['title_li'] = ''; $cat_args['exclude_tree'] = 1; wp_list_categories(apply_filters('widget_categories_args', $cat_args)); ?> </ul> </code> | Hi @Scott B : UPDATE FROM PRIOR ANSWER : Due you my evidently poor reading comprehension skills(!) where I missed the requirement to filter out children (Thanks @Adam BlackStrom for calling attention to my oversight) I've modified the code provided. I think you want to use the <code> list_terms_exclusions </code> filter hook. Add this to your plugin (or others needing the same add to the bottom of your theme's <code> functions.php </code> file): <code> function my_list_terms_exclusions($exclusions,$args) { $children = implode(',',get_term_children(1,'category')); $children = (empty($children) ? '' : ",$children"); return $exclusions . " AND (t.term_id NOT IN (1{$children}))"; } </code> Of course the above will affect all category listings which you might not want so you might need to inspect the values in the <code> $args </code> array or more likely inspect other global state to only add the filter criteria only in the context(s) in which you need it. If you have specifics we of where you need help limiting please ask a follow up question so we can help. P.S. Also, I agree with Adam. If possible use a custom taxonomy. | Filtering Children of the “uncategorized” Category out of the Loop? | wordpress |
Hay all, I'm playing around with WordPress 3.0 and two (2) of the new features, Custom Post Types and the Menu Editor . I've started off by creating a new post type called " <code> products </code> ", as you've guessed, this list products. I'm using the bog standard template and I'm creating a new menu to replace the top nav. As far as I can see I can only add certain "products" to it, I cannot add a "archive" of products. What I'm trying to do is add a link to the menu to go to a page which lists ALL products. Any idea how to do this? | @dotty As you can see by this trac ticket: There should be index pages for custom post types so obviously the need has not yet been addressed in WordPress core. Both @John P Bloch and @Chris_O give you good alternatives; I'm going to give you a 3rd. A "Products" Page First Create a Page for your Custom Post Type and call it "Products" . That will give it the following URL: http://example.php/products/ A "Products List" Shortcode Next create a Shortcode that you can embedded into your "Products" page. In my example I called it <code> [product-list] </code> . Here's a screenshot of what using it would look like: Note that such a shortcode would be a great candidate for adding lots of optional functionality and enabling it to work for many different post types but in the interest of clarity I pretty much hardcoded everything. You can of course use it as a starting point for your own shortcode: <code> <?php add_shortcode('product-list', 'my_product_list'); function my_product_list($args) { $save_post = $GLOBALS['post']; // Save state so you can restore later $post_type = 'product'; $template_file = get_stylesheet_directory() . "/post-{$post_type}.php"; if (!file_exists($template_file)) { return "<p>Missing template [$template_file].</p>"; } else { global $post; $q = new WP_Query("showposts=10&post_type={$post_type}&orderby=title&order=ASC"); $rows = array(); $rows[] = '<div class="post-list ' . $post_type . '-post-list">'; global $post_list_data; $post_list_data = array(); $post_list_data['post_count'] = $post_count = count($q->posts); foreach ($q->posts as $post) { $q->the_post(); ob_start(); include($template_file); $rows[] = ob_get_clean(); } $rows[] = '</div>'; $GLOBALS['post'] = $save_post; return implode("\n",$rows); } } </code> A <code> post-product.php </code> Theme Template File Next you'll need to create a theme template file that only displays one product. The function that implements the shortcode names the template file <code> post-product.php </code> and here's a good starting point: <code> <?php /** * post-product.php - File to display only one product within a list of products. */ ?> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <h2 class="entry-title"><?php the_title(); ?></h2> <div class="entry-content"> <?php the_content(); ?> </div> </div> </code> Add the Menu Option Last you'll want to add the menu option. This is very straightforward as you can see from this screenshot (the following assumes you've done nothing with WordPress 3.0 menus before and that you are using a theme that supports WordPress 3.0 menus such as Twenty Ten): Select the menu option in the admin menu. Click the " + " to add a new menu. Type in your menu name, whatever you like. Click the "Create Menu" button (the screen shot shows "Save Menu" but it will be "Create Menu" when adding.) Select your new Menu as your "Primary Navigation" . Select your "Products " page. Click "Add to Menu" Click "Save Menu" Finally, the Output And here's what a basic product listing might look like: | Adding an Archive of Posts to the Navigation Menu in WordPress 3.0 | wordpress |
I'd like to add a new area on a WordPress 3.0 site that contains a new video from YouTube each day . This video would be manually picked, and manually added each day. I'm not sure how to properly set this up though. My current thought-process is that I would create a category called " videos ," and then add a new post in that category each day placing the embed code as the post-body. This seems like ugly hackery though, so I'm open to a better and more leaner solution. Ideally I would have a simple admin-side form where I would put in a title, and the link to the YouTube video (converting the link to an embed code on my own programmatically). Does WordPress 3.0 accomodate odd post types like this pretty well? What should I read to gain a better understanding of how I would accomplish things like "video of the day" , and "daily cartoons" ? | I'd recommend using a custom post type to handle this. You can add the custom post type and set it to only accept the YouTube url as content. Then you can display the "most recent" post from this setup with a custom loop on your home page. Here are a couple other good resources to start with: Description of custom post types Great tutorial | Implementing "Video of the Day" Feature? | wordpress |
I have a client who runs 8 different blogs, currently on 8 separate installations of WordPress. I'm trying to encourage them to move to a single MS installation instead to make it easier (mostly on me) to maintain the different sites, themes, and mix of plug-ins. Unfortunately, I shied away from MU for the longest time, and now I have no idea where to start with MS. I've used WP-Hive in the past because it allowed me to use multiple domains with one installation of WordPress (I don't like sub-folder blogs or sub-domains sites). This client project, if we go forward, will be a similar setup - multiple single-domain blogs hosted on a single WordPress installation. So what steps should I follow to Set up Multisite - I know how to install it, but how should I configure it considering I want to use it for separate domains, not sub-folders or sub-domains? Move content - I assume the regular WP export-import process will work? Map the domains to their new home on the new installation? | To map your domains, you can consider to use the WordPress MU Domain Mapping plugin which works with wordpress 3.0 as well. Otto has a tutorial online: WordPress 3.0: Multisite Domain Mapping Tutorial Next to that Import/Export should mainly do the job to transfer the sites. | How do I transition multiple installations to a single Multisite installation? | wordpress |
I'm looking for an efficiently coded plugin that will do 3 things... 1) Allow a person to rate a product when they submit a comment, based on a 5 star rating, by simply selecting the appropriate star on the 5 star icon widget. 2) List the user's rating of the product, inline with their comment. 3) List an overall product rating, based on the cumulative ratings of each rater, at the top of the post. I can place the relevant tags inside single.php and comments.php if need be. I like wp-postratings for the most part, but the ratings are not displayed beside each person's comment, they are just rolled up to the top, so you can't see what rating a particular reviewer gave the product. Other than that, its what I'm looking for. | The GD Star Rating plugin is immensely popular, and has an entire site dedicated to it. | Amazon-like star ratings plugin needed. Lightweight and effective. Prefer Ajax | wordpress |
After installed All in one SEO plugin my home page has two descriptions. One by WordPress itself and one by All in one SEO plugin. Is there a simple way to remove WordPress one? Please reconsider closing post as off-topic. Cos already done twice: stackexchange-url ("stackexchange-url stackexchange-url ("stackexchange-url | I'd need to see your site to be sure, but there's a very good chance it's your theme (not WordPress itself) that's setting the extra description field. You can remove that from your <code> header.php </code> file and you should be set. WordPress itself doesn't have SEO features like that built-in. | Two description meta tags All in One SEO WordPress | wordpress |
Is there a way to have the styles on a page appear differently for certain categories, when viewing a page that is only of that category? | Hi @GSto : @EAMann has a great answer if you want different layouts for different categories. OTOH if you only want to change the CSS to, for example, have a different background color for each category then you'll find that most themes will include the category slug as a CSS class on the <code> <body> </code> element and/or possibly other HTML elements that are output by the theme. (And even if your theme doesn't you could always add that functionality yourself.) For example the TwentyTen theme does exactly that; for the following URL: http://example.com/category/category-1/ Here's what the <code> <body> </code> element looks like: <code> <body class="archive category category-category-1"> </code> Knowing the above you could add the following styles to your theme's <code> style.css </code> file to have different color backgrounds for each page (I'm being very simplistic here of course; your actual CSS would certainly be more sophisticated): <code> /* style.css */ body.category-category-1 { background-color: red; } body.category-category-2 { background-color: green; } body.category-category-3 { background-color: blue; } </code> All you really need to do do figure out if your theme does this or not is to view source on the category pages of interest and search for your category slug. Use a Child Theme Of course you probably don't want to modify your theme's <code> style.css </code> ; you probably want to create a <a href="stackexchange-url Child Theme instead. Here are some answers where I talk about Child Themes: stackexchange-url ("Customizing a WordPress Theme without Changing it?") stackexchange-url ("Making the Header on the Twenty Ten Theme Less Tall?") Note that not all themes support child themes, Thesis being one notable example. In the case of those themes you'll have to research more into how they are extended. | Custom Stylings for category pages | wordpress |
Is there a way for me to add an <code> <img> </code> tag in a Post, but then have a plugin download that image, and put it on the server for me instead of me needing to manually download the file from online to my computer and then upload it to the server? Thanks | Sure. You could hook the <code> save_post </code> action, use <code> WP_Http </code> class to download it and then insert it as an attachment using <code> wp_insert_attachment </code> and <code> wp_update_attachment_metadata() </code> . It's not trivial but shouldn't be that hard. | Automatically Import Image into Posts from URLs on the Web? | wordpress |
I am taking on a project where I need to build a static website (due to hosting restrictions). I thought of trying to do this by building a WP site on my computer, then creating a sitemap, and then ripping that site, and finally uploading the files to the host. Any better suggestions on how to do this? (or any good reason why I shouldn't even try) | I am doing this right now (still in process). The best setup seems to be: 1) HTML extension on posts - easy, just use custom post pattern 2) HTML extension on pages - need a plugin for that, if you use pages 3) Disable feeds (in function.php by removing headers for it) 4) wget -x -nH -P scraped -np -k -R php -E -X wp-content,wp-includes -m http://address/siteroot/ That last one sucks down your site, changes WordPress-style directory URLs to .html URLs, changes internal links to relative, etc. Feed URLs on all levels (root, category, article, etc) mess this up, which is why they have to be removed. Obviously, the assumption is that the site is fully reachable from the root. If that's not the case, use a sitemap plugin (as you yourself mentioned) and scrape from there. 5) Run some sort of processor to remove http://address/ or change it to absolute root of your static site. If you need to move directories about (e.g. media/uploads), that's a little more difficult. This should get you about 80% of the way. If you do end up going this way, track me down when you know more and I will share the rest of the setup from my work computer. (If more than one person needs this, rank this up and I will put it somewhere public in a month or so, once fully done). | Creating a Static Website based on a WordPress Website? | wordpress |
I would like to create a dmoz like website, using WP. Any suggestions on plugins or site's architecture would be welcomed. | A great starting point would be stackexchange-url ("Mike's answer") to the question about stackexchange-url ("cloning CrunchBase"). You'll want to do something similar with custom post types for entries in your directory. If you want to allow visitors to submit sites, you could perhaps use the TDO Mini Forms plugin to allow visitors to create a new listing, and adjust the settings so that any new listings created through that form get held for administrator approval before being published. | Creating a Link Directory using WordPress? | wordpress |
I'm making a framework parent theme and in the parent <code> functions.php </code> , I want to register all the possible js files I use frequently and if I want it to load it, in the child <code> functions.php </code> I just have to use <code> wp_enqueue_script() </code> . But it doesn't work... Any clue why? | The child functions.php file loads before the parent functions.php, so you're registering them after enqueueing them. Try enqueueing the scripts on a hook, like <code> 'after_setup_theme' </code> instead. | JavaScript Files Registered in Parent Theme Won't Load When Calling wp_enqueue_script() in Child Theme? | wordpress |
In this post: http://humus101.com/?p=1734 We've got 4 images set (in the img property) to a width of 246 pixel. In chrome it looks fine. In IE6 it doesn't. Any suggestions on how to solve this? | I solved the problem. In the style.css I needed to make the following change <code> #content img { margin: 0; height: auto; max-width: 640px; /*width: auto;*/ } </code> I now wonder how to make that stay for all the following theme updates... | How to resolve - IE 6 ignores img "width" properties | wordpress |
I had to modify a published post and for some unknown reason, it removed the categories the post was in. I tried reassigning them, but it does not work: WordPress does not save the categories, so the post ends in the default "unclassified" category. I've checked and it happens also if I create a new post. So it's a quite strange issue. I deactivated my caching plugin, to no avail. Any idea what provokes this bug? | IT turns out the Role Scoper plugin needed an update. That, and the server admin bumped a new PHP 5.3.3 update. I'm not sure which caused which exactly, but at least you know more now where to look at if the issue arises. | Cannot add / edit categories to a post anymore | wordpress |
I am running WordPress with "WPML Multilingual CMS", so that it has multiple language versions. In a function used with <code> add_action('template_redirect',<functionname>) </code> , I need to find out what the current language is. What should I call? | I have no experience with the plugin whatsoever, but from a quick scout of their site, it looks like: <code> ICL_LANGUAGE_CODE </code> will give you the current language. Worth a try, anyway! | Checking current language in a function | wordpress |
Starting a community wiki to collect up objective best practices for plugin development. This question was inspired by @EAMann's comments on wp-hackers. The idea is to collaborate on what objective best practices might be so that we can potentially eventually use them in some community collaboration review process. UPDATE: After seeing the first few responses it becomes clear that we need to have only one idea/suggestion/best-practice per answer and people should review the list to ensure there are no duplicates before posting. | stackexchange-url ("Use Actions and Filters") If you think people would like to add or alter some data: provide apply_filters() before returning . P.S. One thing I find a bit disappointing and that your question addresses is the percentage of plugins that are designed only for end-users, i.e. that have no hooks of their own. Imagine if WordPress were designed like most plugins? It would be inflexible and a very niche solution. Maybe things would be different if WordPress were to have the ability to auto-install plugins on which other plugins depended? As it is I typically have to write a lot of the functionality I need from scratch because clients want things a certain way and the available plugins, while 90% there, don't allow me the flexibility to update the remaining 10%. I really do wish those leading the WordPress community would identify a way to ensure that plugins are rewarded for following best practices (such as adding in hooks for other developers) much like good answers are rewarded on a StackExchange site. Let's take an example from stackexchange-url ("another question"): Example: I want to do something in my plugin when someone retweets an article. If there was a custom hook in whatever the popular retweet plugin is that I could hook in to and fire off of, that would be great. There isn't, so I can modify their plugin to include it, but that only works for my copy, and I don't want to try to redistribute that. Related stackexchange-url ("Offer Extensible Forms") | Objective Best Practices for Plugin Development? | wordpress |
I'm using the latest build of WP and would like to display the first image attached to the post at the top of the post content. What code do I have to add to single.php to make this happen? | Attachments are considered children of the post they're attached to, so this should work: <code> $images=get_children( array('post_parent'=>$post->ID, 'post_mime_type'=>'image', 'numberposts'=>1)); echo wp_get_attachment_image($images[0]->ID, 'large'); </code> for a large image... replace "large" with the size definition you want or a width,height array. | Displaying Post Attachment(s) at Top of single.php | wordpress |
I'm developing a WordPress site on my Mac, running OS X 10.6.4. I'm using OS X's built-in Apache server to run the site locally during development. I've set up WordPress and connected it to OS X's MySQL with no problems. The site seems to work fine, and I can post, edit, etc. The WordPress installation is in a folder called <code> ~/Sites/mysite.dev </code> . I've also customized my <code> .hosts </code> file and Apache's <code> httpd-vhosts.conf </code> file, to redirect requests for mysite.dev to this folder. So when I enter <code> http://mysite.dev </code> in a browser window, the site loads. No problems here. So I can access the site, in a browser, from two different addresses, <code> http://mysite.dev </code> , and <code> http://localhost/~Gabe/mysite.dev/ </code> . Here's what's weird: When I go to <code> http://mysite.dev </code> , the WordPress site loads normally. When I go to <code> http://localhost/~Gabe/mysite.dev/ </code> , WordPress can't find any posts from the database: It gives me the "Sorry, no posts met your criteria" message (which is built into the theme for when a search for posts returns nothing). N.B.: Apache processes the PHP code normally in both cases -- but in one case WordPress can get posts from MySQL, and in the other case it can't. My first thought was that this was a problem with WordPress's configuration, so I changed the WordPress URL to <code> http://localhost/~Gabe/mysite.dev/ </code> , but this made no difference. I don't understand why using the two addresses produces different results. Any help appreciated. (Here's why I care, in case you're wondering: I want to preview the site in BBEdit's web preview window, and BBEdit will only load the site via the <code> http://localhost/~Gabe/mysite.dev/ </code> address.) | I was able to solve this problem—it turns out that WordPress behaves better when I set both the WordPress address and the site address to http://localhost/~Gabe/mysite.dev/ . | Why does WordPress get posts from MySQL from a virtual hostname but not the direct hostname? | wordpress |
I have an idea for a new plugin. Where can I propose the idea for the plugin so that someone might pick it up? p.s: I won't be willing to pay for it (it is not that important to me), but I still think it is a cool idea. I am also not going to try to make it myself, since my PHP skills are not good enough. | I'd suggest jobs.wordpress.net . It's a job listing site for freelance WordPress development. Just be very clear that you aren't offering any pay for the project. Alternatively, you can also suggest things in the official WordPress forums: Requests and Feedback . One third option is to mention it to someone on the WP-Hackers mailing list . | Where can I propose a new plugin? | wordpress |
I use Git on my development and I find it to be reliable so I wonder what is the reason Automattic choose to use SVN for WordPress? | More then likely it is personal preference. Some people like the workflow introduced by SVN, and some just don't like the distributed model of Git. Some like the way commits, branches, tags etc are handled in one revision control over another. It could also be that they where using SVN before Git was stable enough and they don't want to go through and switch. Why fix something that isn't broken? I really don't think there is a good answer you are going to get on this board, unless someone from Automattic is here. There isn't a right or wrong answer in picking version control systems. | Why Does Automattic use SVN for WordPress Instead of Git? | wordpress |
How do we add language support using .pot and .mo files in a WordPress theme? And how we retrieve the theme? | The .po (Portable Object) file is like a small library containing all the English terms in the theme with an empty column for non-English translations. Using software like Poedit, the .po file can be opened, translations can be added, and it can be saved, which also generates the .mo (Machine Object) file. With a suitably localized theme, the steps involved in translating it are: Run a tool over the code to produce a POT file (Portable Object Template), simply a list of all localizable text. Use a plain text editor or a special localization tool to generate a translation for each piece of text. This produces a PO file (Portable Object). The only difference between a POT and PO file is that the PO file contains translations Compile the PO file to produce a MO file (Machine Object), which can then be used in the theme or plugin. Open Source Software Needed for the translation process: Poedit a cross-platform gettext catalogs (.po files) editor Gettext the GNU `gettext' utilities are a set of tools that provides a framework to help other GNU packages produce multi-lingual messages. A complete guide and tutorial on translating WordPress themes can be found on Urban Giraffe | Adding Language Support using .pot and .mo files to a WordPress Theme? | wordpress |
I'm starting to learn Selenium and PHPUnit and I am interested in implementing what I've learned in my WordPress projects. I've seen http://unit-test.svn.wordpress.org and wonder if there are any tutorials or core-developer's notes on how to use it? | Resources on how to use the WordPress unit-test: WordPress Automated Tests Trac Automated Testing in The Codex The Unit-Test README File The PHPUnit Manual Hakre/WP Unit-Tests Codex Page | Tutorials for Unit-Testing in WordPress and for unit-test.svn.wordpress.org? | wordpress |
I want two images to appear side-by-side. However, WordPress inserts a line-break between the elements, even if I use the HTML editor rather than the Visual editor. How can I make the editor trust that if I don't insert a line-break, I don't want it? | To avoid the line break when posting 2 images side by side assign the alignleft or alignright class to them and put them on the same line in the editor without skipping any spaces between them. Example: <code> <img src="/wp-content/uploads/your_image.jpg" alt="" class="alignleft" /><img src="/wp-content/uploads/your_image2.jpg" alt="" class="alignright" /> </code> Edit I forgot to mention that content after the floated images will overflow between the images unless you clear the floats. I add: <code> <div class="clear">&nbsp;</div> </code> after the images and add <code> .clear {clear:both;} </code> to my css. | How can I make the page editor trust me? | wordpress |
The question is "What is the Difference Between Hierarchical and Non-Hierarchical Taxonomies?" This question really stumped me at first so I figured it would be a good idea to show the difference to others surfing the site looking for the distinction. Specifically the question is referring to the <code> hierarchical </code> argument passed to the <code> register_taxonomy() </code> function. More specifically, what's the difference between this: 'hierarchical' => false <code> register_taxonomy('movie-genre', 'movie', array( 'hierarchical' => false, 'label' => 'Genre', 'query_var' => 'movie-genre', 'rewrite' => array('slug' => 'genres' ), )); </code> And this? 'hierarchical' => true <code> register_taxonomy('movie-genre', 'movie', array( 'hierarchical' => true, 'label' => 'Genre', 'query_var' => 'movie-genre', 'rewrite' => array('slug' => 'genres' ), )); </code> Note I'm going to go ahead and answer my own question but won't mark it as best unless nobody else steps up with a really good answer too. Also my gut feeling tells me I might not have capture every distinction between the two dichotomies so if not please let us know what I missed. | The simple answer is that terms in hierarchical taxonomies can have child terms . But what else? 'hierarchical'=> false When you specify a <code> 'hierarchical'=>false </code> you get the following type of metabox which is the metabox format WordPress also uses for Post Tags : 'hierarchical'=> true However when you specify <code> 'hierarchical'=>true </code> you get the following type of metabox which is the metabox format WordPress also uses for Categories : Of course the example above also points out where hierarchical categorization can be a bit of a mixed bag because in real life subcategories often apply to many parent categories. Even so alowing "many parents" is not how hierarchical taxonomies works in WordPress but IMO categorizing anything perfectly is almost impossible regardless of how WordPress works. So Caveat Emptor! On Custom Taxonomy Registration, or "Why Won't it Save?" While not directly related to the question if you are a newbie trying out custom taxonomies, ( or an experienced dev who isn't paying attention like happened to me when I wrote this up! ) it's likely that you'll try adding <code> register_taxonomy() </code> like the code you see in the question directly into your theme's <code> functions.php </code> file. Oops! If you do add the code directly into <code> functions.php </code> your metabox will display but it won't save your newly added terms (and in the <code> 'heirarchical'=>true </code> form of the metabox your existing terms won't load with checkboxes.) That's because you need to register custom taxonomies (and custom post types) inside an <code> init </code> hook, like so: <code> <?php add_action('init','register_movie_genre_taxonomy'); function register_movie_genre_taxonomy() { register_taxonomy('movie-genre', 'movie', array( 'hierarchical' => true, 'label' => 'Movie Genre', 'query_var' => 'movie-genre', 'rewrite' => array('slug' => 'genres' ), )); } </code> Hope this helps! | The Difference Between Hierarchical and Non-Hierarchical Taxonomies? | wordpress |
I'd like to cause a plugin to restrict its loading of CSS stylesheets and JavaScript JS files to only those pages for which they are needed. An example for my question is the plugin Contact Form 7 which I've used to create a form in one page on my site (the "contact me" page). However it adds the following lines to EVERY page/post on the website: <code> <link rel='stylesheet' id='contact-form-7-css' href='http://www.r-statistics.com/wp-content/plugins/contact-form-7/styles.css?ver=2.3.1' type='text/css' media='all' /> <script type='text/javascript' src='http://www.r-statistics.com/wp-content/plugins/contact-form-7/scripts.js?ver=2.3.1'></script> </code> This makes me suspect that this plugin is impairing my site's loading time, for an extension that interests me on only one page on the site. Thus, my question is how can I remove these extra lines from all the pages except for the "Contact Me" page but without deactivating the plugin? | Styles and scripts are always set up by the functions <code> wp_enqueue_script() </code> and <code> wp_enqueue_style() </code> , which have to be tied to a particular action hook in order to function. I took a peek inside Contact Form 7, and it looks like it's using action tags of <code> wpcf7_enqueue_scripts </code> and <code> wpcf7_enqueue_styles </code> to add them to the <code> wp_print_scripts </code> and <code> wp_print_styles </code> hooks. So, what you need to do is un-hook the scripts and styles from every page but your contact page. The <code> wp_head </code> action fires before the script and styles actions, so you'll need to add something like this to your theme's functions.php file: <code> function remove_wpcf7_extras() { remove_action('wp_print_scripts', 'wpcf7_enqueue_scripts'); remove_action('wp_print_styles', 'wpcf7_enqueue_styles'); } if( ! is_page('contact me') ) { add_action('wp_head', 'remove_wpcf7_extras'); } </code> The is_page() function will return <code> true </code> when you're on the contact page (assuming the name is "contact me") ... you can also use the page slug and page ID for the filter. On all other pages, the <code> if() </code> conditional will add the script/style removal function to the <code> wp_head </code> action, which fires just before the <code> wp_print_scripts </code> and <code> wp_print_styles </code> actions. This should remove the extra code from your pages, and you won't have to deactivate the plug-in or edit any core files. The functions and code I've listed above also won't cause your theme to break if you remove Contact Form 7 in the future, either ... so no need to worry about future upgrade compatibility. | Restricting a Plugin to Only Load its CSS and JS on Selected Pages? | wordpress |
I'm creating a community wiki to ask the following question: What features would you most like to see added to WordPress? This Question Implies a Few Things: It should surface the features enthusiasts want most , not just drive bys from people who can't be bothered to know that the "P" needs to be capitalized ( inside joke. Of course... ) Favor features that benefit the more advanced users and especially the theme and/or plugin developers . Also favor APIs and other enablers vs. just yet another new UI widget. Examples of this might be a Backup API that many developers could build on top of, or a Twitter API that themers could build on. Focus on only the few things you really want most , not everything you can think of. Don't let this be a dumping ground for everything you can think of or have ever thought of. When adding a wanted feature ask yourself if you'd prefer to have it or your top 3 features; if not maybe you shouldn't add it. Give some great details including, if appropriate: A. Wireframes (maybe using Balsamiq?), B. API Interfaces C. Suggested Hooks D. URL Structures E. And more. F. Even Source code Significant Features Only , please. Don't add something like "I want the admin console to be purple" or "I really want the admin menu to be on the right." Avoid things that only Automattic can control like things on WordPress.com!! (not that enthusiasts would care, but...) Better to stick with the things that contributors to an open-source project can affect like code and collaboration. Rules of This Wiki Do not duplicate suggestions . It's okay if you do but a moderator may down-vote it and/or delete if possible. In the case a significant duplicate exists but with some good additions we should edit the answer that's duplicating it to include the additions. More rules will come as needed , as we realize they are needed. If you have concerns about this related to WordPress Ideas , Core Team buy-in or relationship with WordPress/Automattic , please see the comments in one of my own " answers " posted to this question, below. My hope is that this effort will be entirely positive and that everyone including Automattic and the WordPress core team will get huge value from its outcome. | A Custom Fields UI I think really custom fields with custom UI is really a big requirements for a lot of people. I mean, compulsory, repeating, grouped, multiple images, etc. There is a bunch of plugins trying to provide the functionality, but they are all add-ons and have to play catch up to new WP features every time. Magic Fields seems reasonably good as a start point. And they would make perfect addition to the new Custom Posts. | What Features would you Most Like to See Added to WordPress? | wordpress |
I need to get the URL of my theme directory to reference an image in the theme's image/headers directory. How is this done in PHP? | This function will return the theme directory URL so you can use it in other functions: <code> get_bloginfo('template_directory'); </code> Alternatively, this function will echo the theme directory URL to the browser: <code> bloginfo('template_directory'); </code> So an example for an image in the themes <code> images/headers </code> folder would be: <code> <img src="<?php bloginfo('template_directory'); ?>/images/headers/image.jpg" /> </code> | How do I get the theme URL in PHP? | wordpress |
How to give "Interesting Tags" "Ignored Tags" selection option like stackoverflow.com in a WordPress blog? If a blog is about lots of topics and I want to give option to user to choose option like "Interesting Tags" and "Ignored Tags" option of stackoverflow.com. How to give that facility? Is there any plugin? | SO does not hide the posts (AFAIK), it just highlights or unhighlights them. And I am sure they are basically using CSS classes for that. From (very) quick look at the source, they basically use tags as CSS classes and then load a unique-to-you javascript that adds styles to entries with those classes. You basically would need to generate a visitor specific CSS or Javascript which you generate based on the tags. Plus user interface to select/unselect those tags (I don't like the one SO uses). Plus extending WordPress user model to store those preferences. Not a big project, but a medium size one. | Adding "Interesting Tags" & "Ignored Tags" like StackOverflow.com in a WordPress Blog? | wordpress |
I wish to have a "subscribe to new posts" widget for my blog. I know I can use feedburner system, but I want a plugin based solution. The best I could find was Subscribe2 , the downside of it is that you can't have it send full HTML e-mails for subscribers who are not registered users. Is there any alternative plugin, or solution that can do this (maybe a work around based on the GPL subscribe2 plugin?) p.s: the solution need to work with WP 3. So the plugin Subscribe2 for Social Privacy , that is supporting up to WP 2.6, is not a good answer. | The best WordPress plugin for email subscriptions to your blog without using third party services like Feedburner is the WP Responder Email Newsletter and Autoresponder Plugin | Plugin for Sending Email to Readers about New Posts? (besides "Subscribe2 ") | wordpress |
I need to access a list of all categories for a plugin I'm working on, I know that there is the <code> wp_list_categories </code> template tag for use in themes. What would be the best way of accessing these categories for use in a plugin? Is there a specific function or is it a case of writing a specific query? Edit : Here's a screenshot which shows the context of how I'm trying to display a list of categories: | The <code> get_categories() </code> function is what you're looking for. Update: Thanks for the clarifications. Sounds like you're doing the same thing as stackexchange-url ("this question"), ie. creating a new taxonomy for attachments. (I'm not sure they get these categories automatically, maybe someone else can clarify.) I haven't played with that functionality yet, but does that other post sound like what you're looking for? | Getting a List of Categories for Use in a Plugin? | wordpress |
I'm looking for a plugin that will let me easily place a jQuery based (because I want to avoid the hassle of multiple javascript libraries) slider on my site in various places. I'd like it to be able to handle images as well as html. I'm aware of the Featured Content Gallery plugin, but I would like to find an alternative (partly because of this tweet by Brad Williams, whose opinion I trust). Ideally, I'd like something that can automatically create a 'slideshow' based on categories, tags, recent posts, etc., but that can also let me manually create a 'slideshow' with whatever post, image, or other content I want to use. Edit: I'm looking for a WordPress plugin, not just a jQuery plugin. | I've settled on the SlideDeck plugin for WordPress for this project. In short, it's very well put together, looks great, is very flexible, etc. etc. I'm pretty impressed thus far. The only drawback is that the free version includes a very small attribution image link, but honestly, it's probably worth the $49 they want for the WP plugin. | What is a good jQuery content slider plugin? | wordpress |
Going to upgrade WordPress 2.7.1 to 3.0.1 along with all plugins, any tips to do without trouble? Edit: 7 September Dashboard is showing "New version available" for both, WordPress version and for some plugins. So i want to upgrade everything. then what should be upgraded first, WordPress or plugins? And which update would be best for both automatic through dashboard or manually through FTP | You shouldn't have any trouble ... but before doing the upgrade I recommend you do the following: Backup everything Back up your theme Back up all of your plug-ins Back up your existing database This will allow you to "undo" the upgrade if needed. Check theme compatibility If you're using a commonly available theme, check to make sure it's compatible with WordPress 3.0.1 before upgrading. Chances are good that it will be, but if you can double check before upgrading you can save yourself a potential headache. I've seen people try to upgrade from version 2.0 to version 2.9 with themes that broke afterwards ... Check plug-in compatibility Some plug-ins might not work with the new version of WordPress. Check to see if they are rated as compatible before upgrading - if they're not, be prepared for a plug-in to potentially break ... so if it's an absolute necessity, look for a potential alternative in the event that it doesn't work. I've had various calendar plug-ins fail on new version of WordPress ... so make sure you have an option available if something goes wrong. Be prepared for everything to work anyway I've upgraded several systems from 2.7.X to 3.0 over the past few weeks without any problems. So there's a very good chance that your update will go off without a hitch and these precautionary steps were a waste of time. But better to waste the time now than to have to fix a broken site after the upgrade. Final suggestion Upgrade your plug-ins one-at-a-time. If you're upgrading a whole slew of things at once, it can be harder to track down what caused any errors (if any do occur). Upgrading plug-ins one-at-a-time will help you isolate and fix any problems. If a plug-in doesn't work after the upgrade, you can always go back to the back-up you made earlier. | Upgrading WordPress and Plugins; any Tips to Avoid Trouble? | wordpress |
Is there a plugin that logs my usage of plugins on the blog? (when I downloaded a new plugin. When I activated/deactivated it and so on) ? | I have searched fairly extensively, and have not found such a plugin. The best recommendation I could make is to use the WordPress File Monitor plugin. This will at least let you know when a new plugin is installed. Really, you should be using it regardless - it's a great plugin to use as part of an overall security strategy. | Is there a plugin-log plugin? | wordpress |
I have a website who is having a high CPU usage. The only way I know of it, is the information I get from the support people of the hosting company. Is there any other way for me to become informed of the resource usage done by my website? (specifically the plugins, but not only them) Thanks. | You need a so called profiler to measure which part of your application does make use of CPU and Memory Resources. XDebug is such a profiler for example. Using it will show you exactly which part of your application uses how much of CPU and memory. | Is there a way to measure server resource (CPU) usage by WP plugins? | wordpress |
I am using WordPress 3 and would like to backup the database to my computer (a Mac). My webhost is using PHP safe mode, so that sometimes limits what plugins I can use. What is a good way to do a database backup? Is it possible to be automated? Are incremental backups recommended/easy? Obviously I then need to test restoring form a backup. | I've personally had limited success with the backup/restore plug-ins that are commonly available. Many times, the best backup plug-ins don't allow for a direct restoration from a backup file. So I do things manually. It's a bit more difficult, but far more reliable, too. Backing up with phpMyAdmin Log in to your host's control panel (it might be cPanel, it might be something else). Find phpMyAdmin and go to your WordPress database Click "Export" Make sure all tables are selected Click the option to save as a text file Export the database and save the exported file in a safe place. Restoring with phpMyAdmin Log in as before, go to phpMyAdmin, select your database If you want a full restore (i.e. delete everything and roll back in your backup file): Empty all of your database tables Click "Import" Load your backup text file to restore all of your previous data I've done this with 10 different sites. The only times it has problems is when the backup file is huge (> 2MB). In those situations, you'll need to open your backup file in a text editor (Notepad or Wordpad) and copy-paste each set of SQL queries (I break it up by table) into the phpMyAdmin statement window. Even then, it's a fairly quick process and will work every time. Disclaimer: If you've never used phpMyAdmin before, have difficulty reading SQL statements, or are working on someone else's site as a favor, please hire a professional with loads of experience to do this. If you accidentally delete your database or are working with a corrupt backup file there is nothing we can do to fix it. | Backup the Database and Restore from the Backup? | wordpress |
I'm trying to remove the last separator (normally a <code> <br/> </code> tag but I changed it to "//") from the last link from wp_list_categories. Basically I want this: Category 1 // Category 2 // Category 3 // to look like this: Category 1 // Category 2 // Category 3 Here's the current code I'm using: <code> <?php $cat_array = array(); $args = array( 'author' => get_the_author_meta('id'), 'showposts' => -1, 'caller_get_posts' => 1 ); $author_posts = get_posts($args); if ( $author_posts ) { foreach ($author_posts as $author_post ) { foreach(get_the_category($author_post->ID) as $category) { $cat_array[$category->term_id] = $category->term_id; } } } $cat_ids = implode(',', $cat_array); echo strtr(wp_list_categories('include='.$cat_ids.'&title_li=&style=none&echo=0'),array('<br />'=>' // ')); ?> </code> | Change the last line to this: <code> $output = strtr( wp_list_categories( 'include='.$cat_ids.'&title_li=&style=none&echo=0' ), array( '<br />' => ' // ' ) ); echo preg_replace( '@\s//\s\n$@', '', $output ); </code> | WordPress remove separator from last item in wp_list_categories | wordpress |
This is a strange question, but I want to know how I can access the Date and Time settings <code> Admin > Settings > General > Date Format Admin > Settings > General > Time Format </code> I am using the Any+Time jQuery plugin as a date/time selector for the editor view for a custom post type. It allows you to specify a date and time format using the same settings WordPress does . Edit: Turns out it doesn't use the same Date part tokens that WordPress does. Lame. http://www.ama3.com/anytime/#AnyTime.Converter.format Ideally I want to do something like this... <code> <?php $wpDateFormat = get_admin_settings('DateFormat'); // $wpDateFormat now holds something like "F j, Y" ?> <script> $("#datetime").AnyTime_picker({ format: '<?php echo $wpDateFormat ?>' ); </script> </code> What I don't know is... is there such a function like <code> get_admin_settings() </code> ? | <code> get_option('date_format'); get_option('time_format'); </code> | How to get the Date Format and Time Format settings for use in my template? | wordpress |
I need a way to create a custom field that will let me pick an image from the media gallery. How do I do that? The custom field should have a button that when clicked will take me to the media gallery and place the src destination url within a input text box. looking for a plugin or online tutorial and I'm having little luck. | A few weeks ago I added a feature similar to Magic Fields . Here's the github project . The most important thing is in this file: <code> js/custom_fields/media_image.js </code> | How do I make a custom field choose an image? | wordpress |
The question is " How to Allow Two Developers Access to a Plugin on the WordPress.org Plugin Repository? " This question was asked on the wp-hackers list and @EAMann answered it nicely and it's a great question to have here so I'm posting it for Eric to answer here. | There are two (2) steps. Add the WordPress.org username of the contributor you want to add to the " contributors " line in the header info of the Readme file, and that person will have SVN commit access to the plugin. Go to the plugin repository and log in with the main account Go to your plug-in and click the " admin " tab Add the user's WordPress login name to the list of committers by entering their name and clicking " Add Committer ." That's it! | Allowing Two Developers Access to a Plugin on the WordPress.org Plugin Repository? | wordpress |
I am adding a new "Custom Post Type" named "Seminar". I am defining three custom fields Location StartTime EndTime StartTime and EndTime are going to store dates (surprise, surprise). I am wondering if there's any way to tell WordPress to treat these like dates so that I can sort by them and stuff. I am very new to WP, so forgive me if this is a dumb question. | Hia. Basically no. But, you can order by meta_value in WP_Query, so you can sort. I am not sure what format you are storing the dates as, but it will need to be something that MySQL can order by, a simple Unix timestamp would be fine, you would do: <code> $query = new WP_Query( 'post_type=seminar&meta_key=start_time&meta_value=' . time() . '&meta_compare=>' ); </code> Would get all the seminars with a start date after "now" | Is it possible to define the data type of a Custom Field? | wordpress |
I'm registering a Custom Post Type and in the rewrite array I am trying to do something like this: <code> 'rewrite' => array('slug' => "explore/resources/".$CATEGORY, 'with_front' => false) </code> I want the rule to 'dynamically' get the post's category name somehow. I also tried using <code> %category% </code> there but it doesn't work either. I need the post's url to represent the entire path/route to it. Any ideas on how to achieve this? UPDATE: Here is more clarification: I have a custom post type of ' <code> resources </code> ' and these post have several different categories like ' <code> forms </code> ', ' <code> mp3 </code> ' etc. now this Resources area in the site is under another section (that is a page with custom loop for those custom posts) which is called Explore. What I want to achieve is: domain.com/Explore/Resources/Resource-Category/Resource-Name or domian.com/explore/resources/forms/production-form-1 My current rewrite rule in <code> register_post_type() </code> is: <code> 'rewrite' => array('slug' => "explore/resources", 'with_front' => false) </code> . Thanks! | You could use my plugin: http://wordpress.org/extend/plugins/custom-post-permalinks/ That will only work if it's a non-hierarchical post type. If it's hierarchical, you're going to have to register the permastruct yourself. This is a huge ordeal which I don't have the time to write out at the moment. You can look at the code in my plugin above and try to work it out for yourself. Some pointers: In order to get the category into the URL, you're going to have to hook into the <code> 'post_type_link' </code> You'll also have to hook into <code> 'parse_request' </code> to make sure the post type is recognized. | Writing Custom Rewrite Rules that Incorporate Category for Custom Post Types? | wordpress |
I've often heard that having a lot of plugins will slow down a WordPress site. This makes sense of course, as the more code that executes, the longer it will take. I'm wondering whether the slowness is mostly: a result of the sheer number of plugins? (because WP has to do some processing to locate and load each plugin) a result of having a few slow/heavy plugins? More practically, when I am writing my own, should I combine functionality into fewer files to gain speed? Or is it okay to have 10-20 plugins each doing a quick task? | Generalities The rule of thumb " lots of plugins slow down a site " is a very blunt instrument and is perpetuated by those who don't understand how plugins work so they pick something easy to demonize. Yes plugins can slow down your site but it doesn't have to do with the quantity it has to do with the quality and what they are trying to accomplish. I could write a single plugin that would bring a site to it's knees (if there were a reason for me to do so) and it would be worse than 50 other well-written plugins. Of course people write plugins all the time that will bring a site to its knees because they don't know any better. I guess the only truth to " lots of plugins slow down a site " is that when you have a lot of plugins it's more likely that you'll catch a bad one. Specifics So let's talk more specifics. Plugins use " hooks " which are bits of PHP code that run a certain points along the execution path and they can either do something or filter a value or both. WordPress starts calling hooks earlier in its efforts to compose a web page and generate HTML to send to the browser and continues calling hooks almost until it finishes running for a given page. Depending on which hooks a plugin uses it might be called only on certain pages, in the " background " or even almost never. Some hooks only work within the admin console. Some hooks only work within certain pages of the admin console. And some hooks are called by the internal psuedo-cron system. OTOH, some plugins can load extra CSS or JS files and each of those files slows down performance because of Web Performance Rule #1. If you want to get a feel for what hooks are called on each page consider using the " Instrument Hooks for WordPress " plugin I wrote for the question " <a href="stackexchange-url Where Can I Find a List of WordPress Hooks? " Here's a screen shot of what the plugin shows in the footer when used: But just knowing the hooks won't help you know for sure if there is a problem with a plugin. You could call a plugin 100 times and calling it could be negligible compared to another hook call that adds a WHERE clause to a SQL query that could bog down a site that has more than a few hundred posts. Or it could do an HTTP call to another server. Or it could flush the rewrite rules on every page load. The list of sins goes on. The only real way to know for sure it so audit the plugin's hooks by reviewing the source code or better running it through a debugger like PhpStorm+XDEBUG. Your Own Plugins Don't worry about how the code is organized for purposes of performance ; worry about what your code does. Optimizing a frequently run SQL query buy leveraging the Transient API (See: Presentation about the Transient API) would be far better for performance than merging the code of 10 plugins into one. On the other hand, do consider organizing your code for other reasons. I think a long list of plugins can create psychological distress for a lot of users; they see a screen like this, get overwhelmed and just want to simplify things: Yet on the other hand sometimes users can be overwhelmed because one plugin does too much. For example I felt that way with the GD Star Rating Plugin. After trying it on a project (and worse, trying to hook it to get it to do what I needed) I decided to toss it out on it's ear. So some people (like me) will often prefer lots of small tight plugins that each do one thing and do it well (it would be nice though if WordPress would support a grouping feature kinda like how iPhone iOS 4 lets you group apps in folders.) Anyway, hope this helps. | Is it heavyweight plugins or lots of plugins that make a site slow? | wordpress |
I have created a Custom Post Type called <code> 'listing' </code> and added a Custom Taxonomy called <code> 'businesses' </code> . I would like to add a dropdown list of Businesses to the admin list for the Listings. Here is what this functionality looks like in admin list for Posts (I would like the same for my Custom Post Type): Here is my current code (And here is the same code on Gist.): <code> <?php /* Plugin Name: Listing Content Item Plugin URI: Description: Author: Version: 1.0 Author URI: */ class Listing { var $meta_fields = array("list-address1","list-address2","list-country","list-province","list-city","list-postcode","list-firstname","list-lastname","list-website","list-mobile","list-phone","list-fax","list-email", "list-profile", "list-distributionrange", "list-distributionarea"); public function loadStyleScripts() { $eventsURL = trailingslashit( WP_PLUGIN_URL ) . trailingslashit( plugin_basename( dirname( __FILE__ ) ) ) . 'css/'; wp_enqueue_style('listing-style', $eventsURL.'listing.css'); } function Listing() { // Register custom post types register_post_type('listing', array( 'labels' => array( 'name' => __('Listings'), 'singular_name' => __( 'Listing' ), 'add_new' => __( 'Add Listing' ), 'add_new_item' => __( 'Add New Listing' ), 'edit' => __( 'Edit' ), 'edit_item' => __( 'Edit Listing' ), 'new_item' => __( 'New Listing' ), 'view' => __( 'View Listing' ), 'view_item' => __( 'View Listing' ), 'search_items' => __( 'Search Listings' ), 'not_found' => __( 'No listings found' ), 'not_found_in_trash' => __( 'No listings found in Trash' ), 'parent' => __( 'Parent Listing' ), ), 'singular_label' => __('Listing'), 'public' => true, 'show_ui' => true, // UI in admin panel '_builtin' => false, // It's a custom post type, not built in '_edit_link' => 'post.php?post=%d', 'capability_type' => 'post', 'hierarchical' => false, 'rewrite' => array("slug" => "listings"), // Permalinks 'query_var' => "listings", // This goes to the WP_Query schema 'supports' => array('title','editor') )); add_filter("manage_edit-listing_columns", array(&$this, "edit_columns")); add_action("manage_posts_custom_column", array(&$this, "custom_columns")); // Register custom taxonomy #Businesses register_taxonomy("businesses", array("listing"), array( "hierarchical" => true, "label" => "Listing Categories", "singular_label" => "Listing Categorie", "rewrite" => true, )); # Region register_taxonomy("regions", array("listing"), array( 'labels' => array( 'search_items' => __( 'Search Regions' ), 'popular_items' => __( 'Popular Regions' ), 'all_items' => __( 'All Regions' ), 'parent_item' => null, 'parent_item_colon' => null, 'edit_item' => __( 'Edit Region' ), 'update_item' => __( 'Update Region' ), 'add_new_item' => __( 'Add New Region' ), 'new_item_name' => __( 'New Region Name' ), 'separate_items_with_commas' => __( 'Separate regions with commas' ), 'add_or_remove_items' => __( 'Add or remove regions' ), 'choose_from_most_used' => __( 'Choose from the most used regions' ), ), "hierarchical" => false, "label" => "Listing Regions", "singular_label" => "Listing Region", "rewrite" => true, )); # Member Organizations register_taxonomy("organizations", array("listing"), array( 'labels' => array( 'search_items' => __( 'Search Member Organizations' ), 'popular_items' => __( 'Popular Member Organizations' ), 'all_items' => __( 'All Member Organizations' ), 'parent_item' => null, 'parent_item_colon' => null, 'edit_item' => __( 'Edit Member Organization' ), 'update_item' => __( 'Update Member Organization' ), 'add_new_item' => __( 'Add New Member Organization' ), 'new_item_name' => __( 'New Member Organization Name' ), 'separate_items_with_commas' => __( 'Separate member organizations with commas' ), 'add_or_remove_items' => __( 'Add or remove member organizations' ), 'choose_from_most_used' => __( 'Choose from the most used member organizations' ), ), "hierarchical" => false, "label" => "Member Organizations", "singular_label" => "Member Organization", "rewrite" => true, )); # Retail Products register_taxonomy("retails", array("listing"), array( 'labels' => array( 'search_items' => __( 'Search Retail Products' ), 'popular_items' => __( 'Popular Retail Products' ), 'all_items' => __( 'All Retail Products' ), 'parent_item' => null, 'parent_item_colon' => null, 'edit_item' => __( 'Edit Retail Product' ), 'update_item' => __( 'Update Retail Product' ), 'add_new_item' => __( 'Add New Retail Product' ), 'new_item_name' => __( 'New Retail Product Name' ), 'separate_items_with_commas' => __( 'Separate retail products with commas' ), 'add_or_remove_items' => __( 'Add or remove retail products' ), 'choose_from_most_used' => __( 'Choose from the most used retail products' ), ), "hierarchical" => false, "label" => "Retail Products", "singular_label" => "Retail Product", "rewrite" => true, )); # Farming Practices register_taxonomy("practices", array("listing"), array( 'labels' => array( 'search_items' => __( 'Search Farming Practices' ), 'popular_items' => __( 'Popular Farming Practices' ), 'all_items' => __( 'All Farming Practices' ), 'parent_item' => null, 'parent_item_colon' => null, 'edit_item' => __( 'Edit Farming Practice' ), 'update_item' => __( 'Update Farming Practice' ), 'add_new_item' => __( 'Add New Farming Practice' ), 'new_item_name' => __( 'New Farming Practice Name' ), 'separate_items_with_commas' => __( 'Separate farming practices with commas' ), 'add_or_remove_items' => __( 'Add or remove farming practices' ), 'choose_from_most_used' => __( 'Choose from the most used farming practices' ), ), "hierarchical" => false, "label" => "Farming Practices", "singular_label" => "Farming Practice", "rewrite" => true, )); # Products register_taxonomy("products", array("listing"), array( 'labels' => array( 'search_items' => __( 'Search Products' ), 'popular_items' => __( 'Popular Products' ), 'all_items' => __( 'All Products' ), 'parent_item' => null, 'parent_item_colon' => null, 'edit_item' => __( 'Edit Product' ), 'update_item' => __( 'Update Product' ), 'add_new_item' => __( 'Add New Product' ), 'new_item_name' => __( 'New Product Name' ), 'separate_items_with_commas' => __( 'Separate products with commas' ), 'add_or_remove_items' => __( 'Add or remove products' ), 'choose_from_most_used' => __( 'Choose from the most used products' ), ), "hierarchical" => false, "label" => "Products", "singular_label" => "Product", "rewrite" => true, )); // Admin interface init add_action("admin_init", array(&$this, "admin_init")); add_action("template_redirect", array(&$this, 'template_redirect')); // Insert post hook add_action("wp_insert_post", array(&$this, "wp_insert_post"), 10, 2); } function edit_columns($columns) { $columns = array( "cb" => "<input type=\"checkbox\" />", "title" => "Business Name", "description" => "Description", "list-personal" => "Personal Information", "list-location" => "Location", "list-categorie" => "Categorie", ); return $columns; } function custom_columns($column) { global $post; switch ($column) { case "description": the_excerpt(); break; case "list-personal": $custom = get_post_custom(); if(isset($custom["list-firstname"][0])) echo $custom["list-firstname"][0]."<br />"; if(isset($custom["list-lastname"][0])) echo $custom["list-lastname"][0]."<br />"; if(isset($custom["list-email"][0])) echo $custom["list-email"][0]."<br />"; if(isset($custom["list-website"][0])) echo $custom["list-website"][0]."<br />"; if(isset($custom["list-phone"][0])) echo $custom["list-phone"][0]."<br />"; if(isset($custom["list-mobile"][0])) echo $custom["list-mobile"][0]."<br />"; if(isset($custom["list-fax"][0])) echo $custom["list-fax"][0]; break; case "list-location": $custom = get_post_custom(); if(isset($custom["list-address1"][0])) echo $custom["list-address1"][0]."<br />"; if(isset($custom["list-address2"][0])) echo $custom["list-address2"][0]."<br />"; if(isset($custom["list-city"][0])) echo $custom["list-city"][0]."<br />"; if(isset($custom["list-province"][0])) echo $custom["list-province"][0]."<br />"; if(isset($custom["list-postcode"][0])) echo $custom["list-postcode"][0]."<br />"; if(isset($custom["list-country"][0])) echo $custom["list-country"][0]."<br />"; if(isset($custom["list-profile"][0])) echo $custom["list-profile"][0]."<br />"; if(isset($custom["list-distributionrange"][0])) echo $custom["list-distributionrange"][0]."<br />"; if(isset($custom["list-distributionarea"][0])) echo $custom["list-distributionarea"][0]; break; case "list-categorie": $speakers = get_the_terms(0, "businesses"); $speakers_html = array(); if(is_array($speakers)) { foreach ($speakers as $speaker) array_push($speakers_html, '<a href="' . get_term_link($speaker->slug, 'businesses') . '">' . $speaker->name . '</a>'); echo implode($speakers_html, ", "); } break; } } // Template selection function template_redirect() { global $wp; if (isset($wp->query_vars["post_type"]) && ($wp->query_vars["post_type"] == "listing")) { include(STYLESHEETPATH . "/listing.php"); die(); } } // When a post is inserted or updated function wp_insert_post($post_id, $post = null) { if ($post->post_type == "listing") { // Loop through the POST data foreach ($this->meta_fields as $key) { $value = @$_POST[$key]; if (empty($value)) { delete_post_meta($post_id, $key); continue; } // If value is a string it should be unique if (!is_array($value)) { // Update meta if (!update_post_meta($post_id, $key, $value)) { // Or add the meta data add_post_meta($post_id, $key, $value); } } else { // If passed along is an array, we should remove all previous data delete_post_meta($post_id, $key); // Loop through the array adding new values to the post meta as different entries with the same name foreach ($value as $entry) add_post_meta($post_id, $key, $entry); } } } } function admin_init() { // Custom meta boxes for the edit listing screen add_meta_box("list-pers-meta", "Personal Information", array(&$this, "meta_personal"), "listing", "normal", "low"); add_meta_box("list-meta", "Location", array(&$this, "meta_location"), "listing", "normal", "low"); } function meta_personal() { global $post; $custom = get_post_custom($post->ID); if(isset($custom["list-firstname"][0])) $first_name = $custom["list-firstname"][0];else $first_name = ''; if(isset($custom["list-lastname"][0])) $last_name = $custom["list-lastname"][0];else $last_name = ''; if(isset($custom["list-website"][0])) $website = $custom["list-website"][0];else $website = ''; if(isset($custom["list-phone"][0])) $phone = $custom["list-phone"][0];else $phone = ''; if(isset($custom["list-mobile"][0])) $mobile = $custom["list-mobile"][0];else $mobile = ''; if(isset($custom["list-fax"][0])) $fax = $custom["list-fax"][0];else $fax = ''; if(isset($custom["list-email"][0])) $email = $custom["list-email"][0];else $email = ''; ?> <div class="personal"> <table border="0" id="personal"> <tr><td class="personal_field"><label>Firstname:</label></td><td class="personal_input"><input name="list-firstname" value="<?php echo $first_name; ?>" /></td></tr> <tr><td class="personal_field"><label>Lastname:</label></td><td class="personal_input"><input name="list-lastname" value="<?php echo $last_name; ?>" /></td></tr> <tr><td class="personal_field"><label>Email:</label></td><td class="personal_input"><input name="list-email" value="<?php echo $email; ?>" size="40"/></td></tr> <tr><td class="personal_field"><label>Website:</label></td><td class="personal_input"><input name="list-website" value="<?php echo $website; ?>" size="40"/></td></tr> <tr><td class="personal_field"><label>Phone:</label></td><td class="personal_input"><input name="list-phone" value="<?php echo $phone; ?>" /></td></tr> <tr><td class="personal_field"><label>Mobile:</label></td><td class="personal_input"><input name="list-mobile" value="<?php echo $mobile; ?>" /></td></tr> <tr><td class="personal_field"><label>Fax:</label></td><td class="personal_input"><input name="list-fax" value="<?php echo $fax; ?>" /></td></tr> </table> </div> <?php } // Admin post meta contents function meta_location() { global $post; $custom = get_post_custom($post->ID); if(isset($custom["list-address1"])) $address1 = $custom["list-address1"][0];else $address1 = ''; if(isset($custom["list-address2"])) $address2 = $custom["list-address2"][0];else $address2 = ''; if(isset($custom["list-country"])) $country = $custom["list-country"][0];else $country = ''; if(isset($custom["list-province"])) $province = $custom["list-province"][0];else $province = ''; if(isset($custom["list-city"])) $city = $custom["list-city"][0];else $city = ''; if(isset($custom["list-postcode"])) $post_code = $custom["list-postcode"][0];else $post_code = ''; if(isset($custom["list-profile"])) $profile = $custom["list-profile"][0];else $profile = ''; if(isset($custom["list-distributionrange"])) $distribution_range = $custom["list-distributionrange"][0];else $distribution_range = ''; if(isset($custom["list-distributionarea"])) $distribution_area = $custom["list-distributionarea"][0];else $ddistribution_area = ''; ?> <div class="location"> <table border="0" id="location"> <tr><td class="location_field"><label>Address 1:</label></td><td class="location_input"><input name="list-address1" value="<?php echo $address1; ?>" size="60" /></td></tr> <tr><td class="location_field"><label>Address 2:</label></td><td class="location_input"><input name="list-address2" value="<?php echo $address2; ?>" size="60" /></td></tr> <tr><td class="location_field"><label>City:</label></td><td class="location_input"><input name="list-city" value="<?php echo $city; ?>" /></td></tr> <tr><td class="location_field"><label>Province:</label></td><td class="location_input"><input name="list-province" value="Ontario" readonly /></td></tr> <tr><td class="location_field"><label>Postal Code:</label></td><td class="location_input"><input name="list-postcode" value="<?php echo $post_code; ?>" /></td></tr> <tr><td class="location_field"><label>Country:</label></td><td class="location_input"><input name="list-country" value="Canada" readonly /></td></tr> <tr><td class="location_field"><label>Profile:</label></td><td class="location_input"><input name="list-profile" value="<?php echo $profile; ?>" size="60" /></td></tr> <tr><td class="location_field"><label>Distribution Range:</label></td><td class="location_input"><input name="list-distributionrange" value="<?php echo $distribution_range; ?>" size="60" /></td></tr> <tr><td class="location_field"><label>Distribution Area:</label></td><td class="location_input"><input name="list-distributionarea" value="<?php echo $distribution_area; ?>" size="60" /></td></tr> </table> </div> <?php } } // Initiate the plugin add_action("init", "ListingInit"); function ListingInit() { global $listing; $listing = new Listing(); $add_css = $listing->loadStyleScripts(); } </code> How can I do add a dropdown list of Businesses to the admin list for the Listings? | UPDATE: I've included a new complete answer but even so I've left my original response at the bottom to which the first few comments reference. Hi @tarasm : Although I said it shouldn't be hard it is a little involved. But before we dig into the code... The Screenshots: ...let's check out some screen shots for the finished product: Listings list page with No Filtering: Listings list page With Filtering: The Code So here we go... ( Note: I used a singular form for the taxonomy name of <code> business </code> ; I hope that matches your. From lots of experience with both WordPress and database development in the past I believe it is best to do it this way.) Step #1: The <code> restrict_manage_posts </code> action hook. First thing you need to do is to hook the <code> restrict_manage_posts </code> action which has no parameters and is called from <code> /wp-admin/edit.php </code> (in v3.0.1 that call is on line 378.) This will allow you to generate the drop down select at the appropriate location above the list of Listing posts. <code> <?php add_action('restrict_manage_posts','restrict_listings_by_business'); function restrict_listings_by_business() { global $typenow; global $wp_query; if ($typenow=='listing') { $taxonomy = 'business'; $business_taxonomy = get_taxonomy($taxonomy); wp_dropdown_categories(array( 'show_option_all' => __("Show All {$business_taxonomy->label}"), 'taxonomy' => $taxonomy, 'name' => 'business', 'orderby' => 'name', 'selected' => $wp_query->query['term'], 'hierarchical' => true, 'depth' => 3, 'show_count' => true, // Show # listings in parens 'hide_empty' => true, // Don't show businesses w/o listings )); } } </code> We start by checking the <code> $typenow </code> variable to ensure we are in fact on a <code> post_type </code> of <code> listing </code> . If you don't you'll get this drop down for all post types which in some cases is what you want, but not this case. Next we load information about the business taxonomy using <code> get_taxonomy() </code> . We need it to retrieve the label for the taxonomy (i.e. " Businesses "; we could have hard-coded, but that's not very good if you need to internationalize later.) Then we call <code> wp_dropdown_categories() </code> with all the appropriate arguments in the <code> $args </code> array to generate the drop down <code> <?php return wp_dropdown_categories(array( 'show_option_all' => __("Show All {$business_taxonomy->label}"), 'taxonomy' => $taxonomy, 'name' => 'business', 'orderby' => 'name', 'selected' => $wp_query->query['term'], 'hierarchical' => true, 'depth' => 3, 'show_count' => true, // Show # listings in parens 'hide_empty' => true, // Don't show businesses w/o listings )); </code> But what are the appropriate arguments? Let's look at each individually: <code> show_optional_all </code> - Pretty straightforward, it's what is displayed in the drop down at first and when there has been no filtering applied. In our case it's going so be "Show All Businesses " but we could have called it "Listings for All Businesses" or whatever you like. <code> taxonomy </code> - This arguments tells the function what taxonomy to pull terms from even though the function has <code> categories </code> in its name. In v2.8 and earlier WordPress didn't have custom taxonomies but when they were added the team decided it would just be easier to add an taxonomy argument to this function than to create another function with another name. <code> name </code> - This argument allows you to specify the value that WordPress with use for the <code> name </code> attribute of the <select> element generated for the drop down. Just in case it isn't obvious this is also the value that will be used in the URL when filtering. <code> orderby </code> - This argument tells WordPress how to order the results alphabetically. In our case we specified to order buy the <code> name </code> of the terms in the taxonomy, i.e. the business names in this case. <code> selected </code> - This argument is needed so that the drop down can show the current filter in the drop down. It should be the <code> term_id </code> from the selected taxonomy term. In our case it might be the <code> term_id </code> from "Business #2" . Where do we get this value? From WordPress' global variable <code> $wp_query </code> ; it has a property <code> query </code> that contains an array of all the URL parameters and their values (unless some wayward plugin modified it already, of course.) Given how WordPress processes things there will be a <code> term </code> URL parameter passed on the URL when the user clicks the filter button if the user selected a valid term (i.e. one of the listed businesses). <code> hierarchical </code> - By setting this to <code> true </code> you tell the function to respect the hierarchical nature of the taxonomy and display them in a tree view if the terms (businesses) in fact have children. For a screen shot to see what this looks like, see below. <code> depth </code> - This argument collaborates with the <code> hierarchical </code> argument to determine how many levels deep the function should go in displaying children. <code> show_count </code> - If <code> true </code> this argument will display a count posts within parentheses to the left of the term name within the drop down. In this case it would display a count of listings associated with a businesses. For a screen shot to see what this looks like, see below. <code> hide_empty </code> - Finally, if there are terms in the taxonomy that are not associated with a post (i.e. businesses not associated with a listing) then setting this to <code> true </code> will omit them from being included in the drop down. Step #2: The <code> parse_query </code> filter hook. Next we call our attentions to the <code> parse_query </code> filter hook which has one parameter ( <code> $query </code> ) and is called from <code> /wp-includes/query.php </code> (in v3.0.1 that call is on line 1549.) It is called when WordPress has finished inspecting the URL and setting all appropriate values in the currently active <code> $wp_query </code> including things like <code> $wp_query->is_home </code> and <code> $wp_query->is_author </code> , etc. After the <code> parse_query </code> filter hook runs WordPress will call <code> get_posts() </code> and load up a list of posts based on what is specified in the currently active <code> $wp_query </code> . So <code> parse_query </code> is often a great place to get WordPress to change it's mind about which posts it is going to load. In your use-case we want to get WordPress to filter based on the businesses selected; i.e. to display only those Listings which have been associated with the the selected business (I'd say "...only those Listings that have been "categorized" by the selected business" but that's not technical correct; <code> category </code> is it's own taxonomy on peer with <code> business </code> except that <code> category </code> is built into WordPress and <code> business </code> is custom. But for those familiar with categorizing posts this may help you understand as they work almost identically. But I digress...) On to the code. The first thing we do is grab a reference to the currently active <code> $wp_query </code> 's <code> query_vars </code> so that it's more convenient to work with, just like how its done within WordPress' own <code> parse_query() </code> function. Unlike <code> $wp_query->query </code> which is used to mirror the parameters passed on the URL the <code> $wp_query->query_vars </code> array is used to control the query that WordPress runs and is expected to be modified. So if you need to modify one, that'd be the one (at least I think that is the different between the two; if anyone knows otherwise please let me know so I can update this!) <code> <?php add_filter('parse_query','convert_business_id_to_taxonomy_term_in_query'); function convert_business_id_to_taxonomy_term_in_query($query) { global $pagenow; $qv = &$query->query_vars; if ($pagenow=='edit.php' && isset($qv['taxonomy']) && $qv['taxonomy']=='business' && isset($qv['term']) && is_numeric($qv['term'])) { $term = get_term_by('id',$qv['term'],'business'); $qv['term'] = $term->slug; } } </code> Next we test <code> $pagenow </code> to ensure that we are indeed loading WordPress from the URL path <code> /wp-admin/edit.php </code> . We do this to keep from accidentally screwing up queries on other pages. We also check to make sure that we have both <code> business </code> as a <code> taxonomy </code> element and a <code> term </code> element too. (Note <code> taxonomy </code> and <code> term </code> are a pair; they are used together to allow querying of a taxonomy term; gotta have both or WordPress doesn't know which taxonomy to inspect.) You might wonder how <code> business </code> turned up in the <code> taxonomy </code> element of the <code> query_vars </code> array. What we wrote in our <code> parse_query </code> hook triggered WordPress' internal magic that was laid in waiting when you registered the " <code> business </code> " taxonomy by setting <code> query_var </code> to be true ( <code> register_taxonomy() </code> copies the name of the taxonomy as its <code> query_var </code> ; you can change it of course but unless you have a conflict it's best to stick with the same): <code> <?php add_action('init','register_business_taxonomy'); function register_business_taxonomy() { register_taxonomy('business',array('listing'),array( 'label' => 'Businesses', 'public'=>true, 'hierarchical'=>true, 'show_ui'=>true, 'query_var'=>true )); } </code> Now WordPress' $wp_query was written to use slugs for standard taxonomy filtered queries, not taxonomy term IDs. For this use-case what we really need to make our filtering query work are these: <code> taxonomy </code> : business <code> term </code> : business-1 (i.e. the <code> slug </code> ) Not these: <code> taxonomy </code> : business <code> term </code> : 27 (i.e. the <code> term_id </code> ) Interestingly and unfortunately the drop-down generated by <code> wp_dropdown_categories() </code> set the <code> <option> </code> 's <code> value </code> attribute to the term's(/business') <code> term_id </code> , not the term <code> slug </code> . So we need to convert <code> $wp_query->query_vars['term'] </code> from a numeric <code> term_id </code> to it's string <code> slug </code> as following in the snippet snagged from above (Note this is not the most performant way to query a database but until WordPress adds support for term_ids into its query that's the best we can do!): <code> <?php $term = get_term_by('id',$qv['term'],'business'); $qv['term'] = $term->slug; </code> And that's it! With those two functions you get the filtering you desire. BUT WAIT, THERE'S MORE! :-) I went ahead and added a "Businesses" column to your Listing list because, well, I knew it was going to be your next question. Without having a column for what you filter it can be very confusing for the end user. (I struggled with it myself, and I was the coder!) You can of course already see the "Businesses" column in the prior screen shots above. Step #3: The <code> manage_posts_columns </code> filter hook. To add a column to the post list takes calling two (2) more hooks. The first one is <code> manage_posts_columns </code> or the post type-specific version <code> manage_listing_posts_columns </code> that I called instead. It accepts one parameter ( <code> posts_columns </code> ) and is called from <code> /wp-admin/includes/template.php </code> (in v3.0.1 that call is on line 623): <code> <?php add_action('manage_listing_posts_columns', 'add_businesses_column_to_listing_list'); function add_businesses_column_to_listing_list( $posts_columns ) { if (!isset($posts_columns['author'])) { $new_posts_columns = $posts_columns; } else { $new_posts_columns = array(); $index = 0; foreach($posts_columns as $key => $posts_column) { if ($key=='author') $new_posts_columns['businesses'] = null; $new_posts_columns[$key] = $posts_column; } } $new_posts_columns['businesses'] = 'Businesses'; return $new_posts_columns; } </code> Your <code> manage_posts_columns </code> hook function gets passed an array of columns where the value is the displayed column header and the key is the internal column identifier. Standard column identifiers can include these and more: <code> 'cb' </code> , <code> 'title </code> ', <code> 'author' </code> , <code> `'date' </code> , etc. <code> 'cb' </code> , is the <code> checkbox </code> column and both <code> 'title' </code> and <code> 'date' </code> refer to <code> post_title </code> and <code> post_date </code> from the <code> wp_posts </code> table, respectively. <code> 'author' </code> of course is the <code> post_author </code> field after the author name is retrieved from the <code> wp_users </code> table. For the <code> manage_posts_columns </code> hook we are simply wanting to insert our column <code> businesses </code> into the <code> $posts_columns </code> array before <code> 'author' </code> , assuming some other plugin hasn't removed <code> author </code> from the list yet! <code> $new_posts_columns['businesses'] = 'Businesses'; </code> ( Note as I wrote <code> add_businesses_column_to_listing_list() </code> it occurred to me that PHP must have an easier way to insert a value into an associative array in the proper order?!? Or at least there's got to be a function in WordPress core to do it? But since Google let me down so I went with what worked. If anyone has any suggested alternatives I'll be all ears and appreciative in advance!) Which finally brings us to... Step #4: The <code> manage_posts_custom_column </code> action hook The second thing of two (2) we need to do to make our businesses display in the column is to actually output the name of each of the associated businesses using the <code> manage_posts_custom_column </code> action hook. This hook accepts two (2) parameters ( <code> column_id </code> and <code> post_id </code> ) and is also called from <code> /wp-admin/includes/template.php </code> (in v3.0.1 that call is on line 1459.): <code> <?php add_action('manage_posts_custom_column', 'show_businesses_column_for_listing_list',10,2); function show_businesses_column_for_listing_list( $column_id,$post_id ) { global $typenow; if ($typenow=='listing') { $taxonomy = 'business'; switch ($column_name) { case 'businesses': $businesses = get_the_terms($post_id,$taxonomy); if (is_array($businesses)) { foreach($businesses as $key => $business) { $edit_link = get_term_link($business,$taxonomy); $businesses[$key] = '<a href="'.$edit_link.'">' . $business->name . '</a>'; } //echo implode("<br/>",$businesses); echo implode(' | ',$businesses); } break; } } } </code> This hook is called for each column for each post(/business) row. We first verify that we are indeed working with only the <code> listing </code> custom post type and then we use a <code> switch </code> statement to test against the <code> column_id </code> . I chose <code> switch </code> because this hook is often used to generate output for many different columns, especially if we use one function for many different post types which might look something like this: <code> <?php add_action('manage_posts_custom_column', 'my_manage_posts_custom_column',10,2); function my_manage_posts_custom_column( $column_id,$post_id ) { global $typenow; switch ("{$typenow}:{$column_id}") { case 'listing:business': echo '...whatever...'; break; case 'listing:property': echo '...whatever...'; break; case 'agent:listing': echo '...whatever...'; break; } } </code> Inspecting our use-case just a little closer you see the <code> get_the_terms() </code> function which simply returns the list of terms for this taxonomy (i.e. businesses for this listing.) Here get the permalink for the term's front-end web page that normally lists posts that are associated with the term but of course could might differently depending on the theme and/or plugins installed. We use the permalink to hyperlink the term just because I like to hyperlink things. We then merge all the hyperlinked terms(/businesses) together separated with the pipe (' <code> | </code> ') character and output to the PHP buffer which sends it to the user's browser/HTTP client: <code> <?php $businesses = get_the_terms($post_id,$taxonomy); if (is_array($businesses)) { foreach($businesses as $key => $business) { $edit_link = get_term_link($business,$taxonomy); $businesses[$key] = '<a href="'.$edit_link.'">' . $business->name . '</a>'; } //echo implode("<br/>",$businesses); echo implode(' | ',$businesses); } </code> NOW we are finally done. Summary So in summary you need to use the following four (4) hooks to get both a filter and a related column in the custom posts list page (Oh, it will also work with Posts and Pages.) They are: Step #1: The <code> restrict_manage_posts </code> action hook. Step #2: The <code> parse_query </code> filter hook. Step #3: The <code> manage_posts_columns </code> filter hook. Step #4: The <code> manage_posts_custom_column </code> action hook Where to download the code But if I forced you to read through all the above then I would certainly not be a very nice person if I also made you dig out the code just to be able to try it out! But contrary to what some people say, I am nice. So here ya go: Download the Code at : http://gist.github.com/541505 NOTE to @tarasm : I included hooks for a <code> register_post_type() </code> and <code> register_taxonomy() </code> so that others could try this out without having to recreate them. You'll probably want to delete those two function calls before you test this out. THE END Original Response: Hi @tarasm : Are you looking for one drop down at the top like this screen or are you looking for one drop down per post record and if so how would you expect the latter to work? If the former, take a look at this answer to the question <a href="stackexchange-url How to sort the admin area of a Wordpress custom post type by a custom field? If that is what you need I can provide more specifics related to taxonomy. | Adding a Taxonomy Filter to Admin List for a Custom Post Type? | wordpress |
I have a client that wants to create several WordPress sites and utilize a "site switcher" at the top, sort of like ThemeForest.net. I know in WP 3 you can create multiple blogs on the same installation, but what about enabling users who login to one blog to be logged into all of the blogs in the WordPress installation? Is this possible? | @brianmcculloh As @John P Bloch said, WordPress Multisite is a perfect fit . The list of sites is what WordPress now calls a Network . Here are some resources that you might find helpful: Creating a Network (WordPress Codex) Installing Multiple Blogs (WordPress Codex) How to enable Multi-Site option in WordPress 3.0 (WPBeginner.com) WordPress 3.0 Walkthrough: Getting Started with Multisite (WebToolsCollection.com) WordPress 3.0: Multisite Domain Mapping Tutorial (ottopress.com) WordPress MU Domain Mapping Plugin (wordpress.org/extend/plugins) | Multi-site User Sessions | wordpress |
I'm trying to work sub-menus into my theme but am running into issues when navigating to BuddyPress pages (as opposed to standard WP pages, posts, etc.). Basically, what I want to do is have pages (where appropriate) display a sub menu, ala: But when I navigate to pages that exist under BuddyPress' control, I get the following: I'm using the following to generate the sub-menu: <code> if (is_page()) { global $wp_query; if( empty($wp_query->post->post_parent) ) { $parent = $wp_query->post->ID; } else { $parent = $wp_query->post->post_parent; } if(wp_list_pages("title_li=&child_of=$parent&echo=0" )) { ?> <ul id="subnav"> <?php wp_list_pages("title_li=&child_of=$parent&echo=1" ); ?> </ul> <?php } } </code> Where am I going astray? | EDIT: I received a direct, easy answer from the folks over on the BuddyPress forums: There is a template tag called bp_current_component() that returns a boolean. So, in short, to tell if we're currently in a BuddyPress-ized section of the site, we simply call: <code> if( bp_current_component() ){ </code> ...or, if we want to detect when we're NOT in a BuddyPress area, the inverse: <code> if( !bp_current_component() ){ </code> Easy peasy. So, in total, the code looks like this: <code> if( !bp_current_component() ){ if ( is_page() ) { if( empty( $wp_query->post->post_parent ) ) { $parent = $wp_query->post->ID; } else { $parent = $wp_query->post->post_parent; } if( wp_list_pages( "title_li=&child_of=$parent&echo=0" ) ) { echo '<ul id="subnav">'; wp_list_pages( "title_li=&child_of=$parent&echo=1" ); echo '</ul>'; } } } else { echo '<ul id="subnav">'; if ( is_user_logged_in() ){ bp_get_loggedin_user_nav(); } else { bp_get_displayed_user_nav(); } echo '</ul>'; } </code> | How can I detect whether a BuddyPress page is active from within my theme? | wordpress |
I put a <code> if(is_home()) </code> bit in my theme's functions.php and it doesn't seem to work. The function containing this bit is called on init so <code> is_home </code> should work already. | <code> is_home() </code> won't work until <code> wp_query </code> is run. The earliest hook you can use where is_home will work is <code> 'parse_query' </code> , but <code> 'template_redirect' </code> would be better. | Why isn't is_home() working correctly? | wordpress |
I didn't know this site exists. So, I asked it on stackexchange-url ("WebApps") I didn't get a solution still. :-( I am unable to install any theme/plugin to my WordPress 3.0 <code> Downloading install package from http://downloads.wordpress.org/plugin/contact-form-7.2.3.1.zip… Unpacking the package… Installing the plugin… Could not copy file. /public_html/blog/wp-content/plugins/contact-form-7/languages/wpcf7-lt_LT.po Plugin install failed. Downloading install package from http://wordpress.org/extend/themes/download/piano-black.2.2.zip… Unpacking the package… Could not create directory. /public_html Downloading install package from http://downloads.wordpress.org/plugin/contact-form-7.2.3.1.zip… Unpacking the package… Could not create directory. /public_html/blog/wp-content/upgrade/contact-form-7.tmp/contact-form-7 </code> I get similar messages everytime. Is there any solution? | It's either the configuration of the path where WordPress is installed (you don't have the right path setup) or if the path is correct, you don't have got enough permissions to modify the file system. So as this answer is very broad, that's because it is of a very technical nature that is bound to your concrete hosting environment. Please contact your hosting support and figure out together with them which path and permission settings are needed for your WordPress installation. In case you copied over your blog from another system, please reset the path related configuration constants and options. Check your <code> wp-config.php </code> if you make any specific settings in there. | How to prevent plugin, theme installation failures on Wordpress? | wordpress |
I've already added my scripts, but I wanted to know the preferred way. I just put a <code> <script> </code> tag directly in the <code> header.php </code> of my template. Is there a preferred method of inserting external or custom js files? How would I bind a js file to a single page? (I have the home page in mind) | Use <code> wp_enqueue_script() </code> in your theme The basic answer is to use <code> wp_enqueue_script() </code> in an <code> wp_enqueue_scripts </code> hook for front end <code> admin_enqueue_scripts </code> for admin. It might look something like this (which assumes you are calling from your theme's <code> functions.php </code> file; note how I reference the stylesheet directory): <code> <?php add_action( 'wp_enqueue_scripts', 'mysite_enqueue' ); function mysite_enqueue() { $ss_url = get_stylesheet_directory_uri(); wp_enqueue_script( 'mysite-scripts', "{$ss_url}/js/mysite-scripts.js" ); } </code> That's the basics. Pre-defined and Multiple Dependent Scripts But let's say you want to include both jQuery and jQuery UI Sortable from the list of default scripts included with WordPress and you want your script to depend on them? Easy, just include the first two scripts using the pre-defined handles defined in WordPress and for your script provide a 3rd parameter to <code> wp_enqueue_script() </code> which is an array of the script handles used by each script, like so: <code> <?php add_action( 'wp_enqueue_scripts', 'mysite_enqueue' ); function mysite_enqueue() { $ss_url = get_stylesheet_directory_uri(); wp_enqueue_script( 'mysite-scripts', "{$ss_url}/js/mysite-scripts.js", array( 'jquery', 'jquery-ui-sortable' ) ); } </code> Scripts in a Plugin What if you want to do it in a plugin instead? Use the <code> plugins_url() </code> function to specify the URL of your Javascript file: <code> <?php define( 'MY_PLUGIN_VERSION', '2.0.1' ); add_action( 'wp_enqueue_scripts', 'my_plugin_enqueue' ); function my_plugin_enqueue() { wp_enqueue_script( 'my-script', plugins_url('/js/my-script.js',__FILE__), array('jquery','jquery-ui-sortable'), MY_PLUGIN_VERSION ); } </code> Versioning your Scripts Also note that above we gave our plugin a version number and passed it as a 4th parameter to <code> wp_enqueue_script() </code> . Version number is output in source as query argument in URL to script and serves to force browser to re-download possibly cached file if version changed. Load Scripts only on pages where needed The 1st rule of Web Performance says to Minimize HTTP Requests so whenever possible you should limit the scripts to load only where needed. For example if you only need your script in the admin limit it to admin pages using the <code> admin_enqueue_scripts </code> hook instead: <code> <?php define( 'MY_PLUGIN_VERSION', '2.0.1' ); add_action( 'admin_enqueue_scripts', 'my_plugin_admin_enqueue' ); function my_plugin_admin_enqueue() { wp_enqueue_script( 'my-script', plugins_url( '/js/my-script.js', __FILE__ ), array( 'jquery', 'jquery-ui-sortable' ), MY_PLUGIN_VERSION ); } </code> Load Your Scripts in the Footer If your scripts is one of those that need to be loaded into the footer there is a 5th parameter of <code> wp_enqueue_script() </code> that tells WordPress to delay it and place it in the footer (assuming your theme did not misbehaved and that it indeed calls the wp_footer hook like all good WordPress themes should): <code> <?php define( 'MY_PLUGIN_VERSION', '2.0.1' ); add_action( 'admin_enqueue_scripts', 'my_plugin_admin_enqueue' ); function my_plugin_admin_enqueue() { wp_enqueue_script( 'my-script', plugins_url( '/js/my-script.js', __FILE__ ), array( 'jquery', 'jquery-ui-sortable' ), MY_PLUGIN_VERSION, true ); } </code> Finer Grained Control If you need finer grained control than that Ozh has a great article entitled How To: Load Javascript With Your WordPress Plugin that details more. Disabling Scripts to Gain Control Justin Tadlock has a nice article entitled How to disable scripts and styles in case you want to: Combine multiple files into single files (mileage may vary with JavaScript here). Load the files only on the pages we’re using the script or style. Stop having to use !important in our style.css file to make simple CSS adjustments. Passing Values from PHP to JS with <code> wp_localize_script() </code> On his blog Vladimir Prelovac has a great article entitled Best practice for adding JavaScript code to WordPress plugins where he discusses using <code> wp_localize_script() </code> to allow you to set the value of variables in your server-side PHP to be later used in your client-side Javascript. Really Fine Grained Control with <code> wp_print_scripts() </code> And finally if you need really fine-grained control you can look into <code> wp_print_scripts() </code> as discussed on Beer Planet in a post entitled How To Include CSS and JavaScript Conditionally And Only When Needed By The Posts. Epiloque That's about it for Best Practices of including Javascript files with WordPress. If I missed something (which I probably have) be sure to let me know in the comments so I can add an update for future travelers. | What is the preferred way to add custom javascript files to the site? | wordpress |
I don't feel like making my own theme from scratch, so I looked for some theme frameworks, but they're all old and when I install them on WP 3.0 they produce loads of errors and don't behave properly. I just need a 3.0 ready blank theme with the bare elements (just text, but functional) to then shape myself into a good looking blog. Thanks in advance. | From what I understand Starkers 3.0 fits the bill. Do you want something this naked , or less? | Is there a blank theme framework compatible with WP 3.0? | wordpress |
I am trying to use tips from stackexchange-url ("here") to add my JS file. I put the following in the functions.php of atahualpa theme I've got installed <code> function lektor_init() { if (true) { wp_enqueue_script('lektor',TEMPLATEPATH.'/js/synteza.js'); } } add_action('init','lektor_init'); </code> <code> TEMPLATEPATH </code> has been already used before in there, so I just adapted it. But it doesn't show up. What did I do wrong? | <code> TEMPLATEPATH </code> is a directory path, not a url. You'll need to use <code> get_template_directory_uri() </code> . | Why doesn't wp_enqueue_script() work when including a JavaScript file with TEMPLATEPATH? | wordpress |
I did some quick looking around, but my PHP skills are pretty nascent. I am sure there is just a package that needs installing. Edit to add additional information about the setup: Using: <code> yum info php </code> I get the version of PHP as 5.1.6: <code> Name : php Arch : i386 Version : 5.1.6 </code> More information, this is a VM running CentOS at GoDaddy: <code> CentOS release 5.4 (Final) </code> | Upgrade to PHP 5.2 or above The Error Message you see is by WordPress. It's very misleading what it basically saying is, that you need a PHP version > = 5.2 for that feature to work. Please look into your operating systems documentation or contact technical support on how to update your PHP version. For CentOS, for example: CentOS HowTos: PHP 5.1 To 5.2 Keep Timezones Upgraded To get the most out of PHP Timezone support , there is a PECL package that contains all the latest updates: timezonedb . So next to upgrading PHP to a recent version, you can install that PECL package and keep it updated to get the latest timezone updates (last one was on August 16): <code> $ yum install php-pear php-devel $ pecl install timezonedb </code> | I get "The PHP Date/Time library is not supported by your web host." on my CentOS host, what library to I need to install to add support? | wordpress |
After a certain amount of time WP logs out all users and forces them to log back in again. For development environments on my local machine this is obnoxious and absolutely unnecessary. Is there an API-driven way of disabling the auto-logout indefinitely? Ideally I'd like something I can add to <code> wp-config.php </code> along with other dev-setup-related settings. A plugin would be overkill for me so I won't consider it an answer, but you might as well post it as an option. | By default, the "Remember Me" checkbox makes you get remembered for 14 days. This is filterable though. This code will change that value: <code> add_filter( 'auth_cookie_expiration', 'keep_me_logged_in_for_1_year' ); function keep_me_logged_in_for_1_year( $expirein ) { return 31556926; // 1 year in seconds } </code> | What's the easiest way to stop WP from ever logging me out | wordpress |
I have been working on an image gallery feature where I grab images which are attached to pages and display them in various places via the <code> get_posts() </code> function. However, I am finding that when I remove images from the page that they have been placed that they still seem to be set as attachments. I'm just wondering if there's something I'm mis-understanding about attachments or if this is buggy behaviour? It may be worth me adding that I am getting images as attachments of pages because I need to be able to categorise the images and display them via categories in different places on the site. If I was able to categorise images directly I realise I wouldn't need to worry about this problem I'm encountering! | Deleting an image from a post or page is a confusing process. When you upload an image to a post/page, it's added to that post/page's gallery. You can then insert the image into the content of the post/page and edit content as you see fit. When you click on the image in the wysiwyg editor, you'll see two icons - one to edit the image's settings and one to remove it from the editor - this second icon does not delete the image even though it looks like a typical "delete" icon. When you press that "delete" button, it removes the image from the visual editor but keeps it in the post/page's gallery . To actually remove/delete the image, you need to do the following Click the "Add Image" button to view the image screen Click the "Gallery" tab to view what images are currently attached to the post Click the "Show" link for the image you want removed. Click "Delete" towards the bottom of the image detail screen You'll be asked to confirm deletion, then the image will be unattached to the post/page and removed entirely from WordPress. | Image still linked as attachment to page even though it has been deleted | wordpress |
Is there anyway to create blogs with 2 depths using multisite? I want to have an installation in root and blogs with 2 depths. Something like: <code> / - WP installation: root aggregate /foo - WP installation: aggregate for a topic /foo/item - WP installation: blog for an item </code> Trouble is that multisite only goes in one level. Other problem is that if I install in root, then I'm afraid that this blog takes everything bellow. So my questions are: Is it possible to do an installation of a blog inside another blog? or Is it possible to get multisite to allow for 2 depth levels? Thank you. | Answering your first question, yes it is absolutely possible to have one installation of WordPress running 'within' another (i.e. installed at example.com and example.com/child). I have something like that running right now. | Depth > 2 possible with multisite? | wordpress |
A static front page and other pages which are children of it are used on a blog. To give an example: www.example.com The slug for that page shows up in the permalink for sub pages like www.example.com/long-slug-from-static-front-page/sub-page-slug.html. The question now is how to make the URL Design more natural? Since the parent page is the frontpage, it's slug should be the sites homepage-URL (e.g. none as in http://www.example.com/ ) but the static pages slug is added instead. I smell that this is a shortcoming in WordPress, any ideas? I was asked to make the scenario more concrete by an Illustration because it was quite akward describben. Sorry. Aim is to use WordPress as a CMS to reflect the following structure (please not the other way round): Illustration: Logical Data and it's Structure: Start Blue Red Dark Red Light Red Burned Red Yellow Mapping of Data to Pages: Start: Home-Page Blue: Blue-Page Red: Red-Page Dark Red: Dark Red-Page Light Red: Light Red-Page Burned Red: Burned Red-Page Yellow: Yellow-Page URL Layout: Home-Page: http://example.com/ Blue-Page: http://example.com/blue/ Red-Page: http://example.com/red/ Dark Red-Page: http://example.com/red/dark/ Light Red-Page: http://example.com/red/light/ Burned Red-Page: http://example.com/red/burned/ Yellow-Page: http://example.com/yellow/ Is WordPress the tool for the job? Or does using page hierarchy and static front-page contradicts the URL layout? | WordPress does have a way of doing what you want. Make them all top level pages. Unless you have a good reason not to. | Natural URL Design and static front page | wordpress |
I sometimes build applications in Flash for the web that need a fair bit of dynamic data. Would WordPress be a good fit for my CMS solution? can it "talk" to flash? Does it allow output as different formats such as XML, JSON, or AMF? | Absolutely. WordPress is implemented in PHP and anything Flash needed to interface with can be coded as a plugin, probably very easily. You can also implement any embedding of Flash as ShortCodes . Here are some (honestly not very good) links on the subject of PHP & Flash: http://www.kirupa.com/developer/actionscript/displayinphp.htm http://www.techmynd.com/get-data-in-flash-from-php/ http://www.dreamincode.net/forums/topic/9848-pass-complex-data-from-php-to-flash/ http://www.video-animation.com/dbase001.shtml http://www.smartwebby.com/Flash/external_data.asp http://www.devx.com/webdev/Article/36748 Of course then there is what Adobe has: http://www.google.com/search?q=php+flash+data+site:adobe.com Can you update your question to provide more details on exactly what you need for/from Flash? Maybe included some links that explain the things you want WordPress handling for Flash (Flash is quite a large beast, you know.) | Can I / Should I use WordPress as a CMS for my Flash application | wordpress |
I'm using the following template code to display attachment links: <code> $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $main_post_id ); $attachments = get_posts($args); foreach ($attachments as $attachment) { the_attachment_link($attachment->ID, false); } </code> but after the link I need to display the file's size. How can I do this? I'm guessing I could determine the file's path (via <code> wp_upload_dir() </code> and a <code> substr() </code> of <code> wp_get_attachment_url() </code> ) and call <code> filesize() </code> but that seems messy, and I'm just wondering if there's a method built into WordPress. | As far as I know, WordPress has nothing built in for this, I would just do: <code> filesize( get_attached_file( $attachment->ID ) ); </code> | How do I get the size of an attachment file? | wordpress |
I was wondering about the impact nonces would have on the default comment form a theme has. Because Nonces are a built-in feature of WordPress I thought about giving it a try. Does somebody has already implemented nonces in the standard comment form? (can't imagine that I'm the first one who thinks about that... !) Can someone suggest an already existing plugin that does the job or provide a code snippet that integrates the WP Nonce Field into the themes comment form and checks for it when the form gets submitted? | I haven't done this personally, but it would be pretty easy. If you are building your comment form manually, just before the end of the <code> </form> </code> put: <code> <?php wp_nonce_field( 'comment_nonce' ) ?> </code> Then, just hook into the <code> pre_comment_on_post </code> action which fires when you submit a comment: <code> add_action( 'pre_comment_on_post', 'my_verify_comment_nonce' ); function my_verify_comment_nonce() { check_admin_referer( 'comment_nonce' ); } </code> If you want to just hook into the standard comment form that Twenty Ten uses ( <code> comment_form() </code> ) then you could instead hook into <code> comment_form </code> like so: <code> add_action( 'comment_form', 'my_add_comment_nonce_to_form' ); function my_add_comment_nonce_to_form() { wp_nonce_field( 'comment_nonce' ); } </code> Not tested, so let me know if you have any issues! | Experiences with adding Nonces to the comment form | wordpress |
I always find myself in HTML mode in the editor to try and get simple things like breaks between paragraphs to show up right (using <code> <p></p> </code> ). Is that normal? Is there a better editor out there that I could use? | What happens is that TinyMCE converts every double line break in the HTML source to <code> <p></p> </code> and vice versa. It will actually strip away any <code> <p/> </code> you manually enter in the HTML source after you save, because when the post's content is rendered, <code> <p> </code> and <code> </p> </code> will be added. The auto- <code> <p> </code> replacement only works when you're rendering a post's content with <code> <?php the_content() ?> </code> , if you output <code> $post->post_content </code> directly, it won't go through the same formatting hooks and will look plain and without line breaks or paragraphs. If what you want is lots of <code> <br/> </code> tags in the rendered markup, you should probably find a better solution based on CSS and the use of the <code> margin </code> or <code> padding </code> CSS properties. | How can I improve the line break handling in the WYSIWYG editor? | wordpress |
Drupal 7 has support for the semantic web (RDF/RDFa). Is there a plugin or similar plans for WordPress? | As far as I know, there are no plans to implement RDF into WordPress. RDFa on the other hand can be quite easily implemented by any theme or plugin author by simply adding the RDFa attributes to the generated markup. Writing a plugin to expose WordPress' taxonomy as RDF wouldn't be hard and making it two-ways would probably not be that difficult either. I know of no plugins in existence that does this, though. | How can I use RDFa with WordPress? | wordpress |
Disclaimer: I am brand spanking new to WP. I am using the Starkers HTML5 framework theme . In the <code> functions.php </code> I see this code: <code> function starkers_widgets_init() { // Area 1, located at the top of the sidebar. register_sidebar( array( 'name' => __( 'Primary Widget Area', 'starkers' ), 'id' => 'primary-widget-area', 'description' => __( 'The primary widget area', 'starkers' ), 'before_widget' => '<li>', 'after_widget' => '</li>', 'before_title' => '<h3>', 'after_title' => '</h3>', ) ); // Area 3, located in the footer. Empty by default. register_sidebar( array( 'name' => __( 'First Footer Widget Area', 'starkers' ), 'id' => 'first-footer-widget-area', 'description' => __( 'The first footer widget area', 'starkers' ), 'before_widget' => '<li>', 'after_widget' => '</li>', 'before_title' => '<h3>', 'after_title' => '</h3>', ) ); // ... more calls to register_sidebar() ... } </code> And in <code> footer.php </code> I see this code: <code> <?php get_sidebar( 'footer' ); ?> </code> I don't understand how <code> get_sidebar() </code> knows how to take that string argument and find the appropriate widgets that were defined by <code> register_sidebar() </code> . In the functions.php snippet I posted above. There isn't any mention of "footer" except for the <code> name </code> , <code> id </code> and <code> description </code> properties. But it would seem odd to me that <code> get_sidebar() </code> would search for 'footer' inside those properties. Does this make sense what I am asking? Is there some missing piece? The reasons I am asking is because - I would like to know more about the WP architecture - I would like to be able to define a custom widget area and know how to render it on a specific page. Thanks a ton. | You just call <code> get_sidebar() </code> from <code> index.php </code> and it loads the theme file <code> sidebar.php </code> . <code> register_sidebar() </code> , on the other hand, is used for widgets where plugins and such want to dynamically add content in your <code> sidebar.php </code> file if your theme supports it. In your case, is there a file called <code> sidebar-footer.php </code> in your theme's directory? | How do register_sidebar() and get_sidebar() work together? | wordpress |
I am using <code> register_taxonomy_for_object_type() </code> to add the Category taxonomy field to Media uploads (attachments). I'm using this code to do so: <code> add_action('init', 'reg_tax'); function reg_tax() { register_taxonomy_for_object_type('category', 'attachment'); } </code> This works and adds a simple text field for Category to the Media page when viewing an image. What I really want is to make it display the actual Categories Metabox so that I can choose the Categories I want to use rather than just type them into the plain field. I've also found that putting the slug for a category into this text field such as <code> my-category-name </code> ends up displaying as the actual category name like <code> My Category Name </code> when it's saved, which makes the simple text field even less of a useful option. I've been looking at the <code> add_post_type_support() </code> function for adding Metaboxes and have seen it used for Custom Post Types, I just can't see if it's possible to add the same for attachments. | I'm going to answer my own question here as I have managed to figure out a solution to what I've been trying to do. I came to the conclusion that it wasn't possible to get the Category Metabox enabled for attachments. However, I found that it was easy enough to get a basic field for Categories added to the attachments page by using <code> register_taxonomy_for_object_type </code> and <code> add_post_type_support </code> : <code> add_action('admin_init', 'reg_tax'); function reg_tax() { register_taxonomy_for_object_type('category', 'attachment'); add_post_type_support('attachment', 'category'); } </code> The field added showed like this: It's just a plain text field but what I found was that you could type the name of an existing category in there and it would then be successfully saved when the attachment was updated (The only odd behaviour is that it rendered back the normal version instead of the slug after saving). Once I realised that I could save categories this way then I figured that I could get a list of all available categories as checkboxes and check the ones that had been selected. I then used a bit of jQuery to grab the values of checked categories and put all the categories' slugs into the Category field. To make this seem even more seamless I then used a simple bit of CSS to hide the table row that contained the Category field, so all you ever see are the checkboxes, like so: Now that I can add categories to image attachments I can use something like: <code> get_posts('post_type=attachment&category_name=timber-fixed-windows') </code> And pull the categorised images into a page! Exactly what I was hoping to do, I didn't think there was going to be a way to do it but glad I managed to figure something out. I've turned this into a plugin called <code> WOS Media Categories </code> which I have made available to download from my website, Suburbia.org.uk, I hope it may be of use to somebody else! Thanks again to those who commented on this and other questions I've asked here which helped figure it out! Update: I've added a fix to enable categories to be added whilst images are uploaded using the Flash bulk uploader. | Can I add a Category Metabox to attachment? | wordpress |
I have a 3.0.1 site with <code> MULTISITE </code> enabled and would like one of the sites to live at <code> /blog </code> , but when I try to create a new site with that path, I get this error: <code> The following words are reserved for use by WordPress functions and cannot be used as blog names: page, comments, blog, files, feed </code> How can I get a site at <code> /blog </code> ? | You can't. That's part of the main site's permalink structure. There's no way to get around it. You can find more information here: http://core.trac.wordpress.org/ticket/13527 | How do I get /blog on my WordPress multisite | wordpress |
I have a standard dynamic sidebar using <code> register_sidebar </code> and <code> dynamic_sidebar </code> and I need the last widget in the sidebar (which will not have a set number of widgets) to have a distinct class ( <code> 'last_widget' </code> ) added to the <code> <li> </code> that wraps it. What's the best way to do this? | Hi John : I think this is what you are looking for (I'd explain the code be I think it's self-explanatory; let me know if not): <code> <?php add_filter('dynamic_sidebar_params','my_dynamic_sidebar_params'); function my_dynamic_sidebar_params($params) { $sidebar_id = $params[0]['id']; $sidebar_widgets = wp_get_sidebars_widgets(); $last_widget_id = end($sidebar_widgets[$sidebar_id]); if ($last_widget_id==$params[0]['widget_id']) $params[0]['before_widget'] = str_replace(' class="',' class="last_widget ',$params[0]['before_widget']); return $params; } </code> | How Do I Add Custom CSS To Only Certain Widgets | wordpress |
Previously, I was able to selectively load child pages for a currently-selected parent page using logic such as: <code> if( $post->post_parent ) { $children = wp_list_pages("title_li=&child_of=".$post->post_parent."&echo=0"); } else { $children = wp_list_pages("title_li=&child_of=".$post->ID."&echo=0"); } if ($children) { ?> <ul id="subnav"> <?php echo $children; ?> </ul> <?php } else { } </code> There doesn't seem to be a native way to do this using the new register_nav_menus()/wp_nav_menu() functionality. Anyone know how I could patch this together at this point? Here's a screenshot of what I'm trying to achieve: | I created a Widget named Page Sub Navigation (clever I know) that is working for me. If you install this, you can just drag the widget to one of your widget areas and BAM it works. <code> <?php /* Plugin Name: Page Sub Navigation Plugin URI: http://codegavin.com/wordpress/sub-nav Description: Displays a list of child pages for the current page Author: Jesse Gavin Version: 1 Author URI: http://codegavin.com */ function createPageSubMenu() { if (is_page()) { global $wp_query; if( empty($wp_query->post->post_parent) ) { $parent = $wp_query->post->ID; } else { $parent = $wp_query->post->post_parent; } $title = get_the_title($parent); if(wp_list_pages("title_li=&child_of=$parent&echo=0" )) { echo "<div id='submenu'>"; echo "<h3><span>$title</span></h3>"; echo "<ul>"; wp_list_pages("title_li=&child_of=$parent&echo=1" ); echo "</ul>"; echo "</div>"; } } } function widget_pageSubNav($args) { extract($args); echo $before_widget; createPageSubMenu(); echo $after_widget; } function pageSubMenu_init() { wp_register_sidebar_widget("cg-sidebar-widget", __('Page Sub Navigation'), 'widget_pageSubNav'); } add_action("plugins_loaded", "pageSubMenu_init"); ?> </code> Or if you just want the juicy parts... <code> if (is_page()) { global $wp_query; if( empty($wp_query->post->post_parent) ) { $parent = $wp_query->post->ID; } else { $parent = $wp_query->post->post_parent; } if(wp_list_pages("title_li=&child_of=$parent&echo=0" )) { wp_list_pages("title_li=&child_of=$parent&echo=1" ); } } </code> UPDATE I found another plugin that does essentially the same thing (and maybe does it better, I don't know). http://wordpress.org/extend/plugins/subpages-widget/ | Generate a Menu that Displays Child Pages using wp_list_pages() with the New Menu Functionality in WordPress 3.0? | wordpress |
Blogs hosted on wordpress.com get automatic link shortening via http://wp.me/ , but for those who prefer to seek out our own hosting solution is there a plugin that will, upon publishing a new post/page, make an api call to bit.ly (or other such service) store the resulting url and return it from <code> wp_get_shortlink() </code> ? I have searched without success. Any help would be appreciated. | There's this plugin: http://wordpress.org/extend/plugins/wp-bitly/ | Automagic Link Shortening for Non-Hosted WP | wordpress |
I run a WordPress site with about 70 active plugins. Every so often, I'll get a random error page ("Not Found", though I haven't checked the headers to see if it's a 404) on a <code> /wp-admin/ </code> page that pops up out of nowhere. Simply trying again resolves the error, however it's quite inconvenient if the error happens during a plugin upgrade (because the auto-reactivation fails). I think this same issue is responsible for certain modules on my Dashboard failing to load sometimes. Given the list of plugins I have installed , does anyone know of issues with or between any of them that might cause this problem? Edit: Hosting info: DreamHost; I think the server's running a custom Debian build with Apache httpd | i was having problems all day with what seemed to be 404 misfirings. anyway, i just finished chatting with a dreamhost tech support person who told me that a user account i have with them was hitting process memory resource limits (all processes) and that was what was causing strange, seemingly htaccess-related problems. i was getting intermittent 404 errors from an htaccess file that should not have been called at all! it was dreamhost with a haunted house server. apparently, the process killing robot that dreamhost uses will kill a web process in the middle and then for some reason, the (now zombie) apache actually tries to finish its job (doing its best to exit cleanly out of the unglamorous end to a subrequest is my best guess). it throws a 500 error into the main http log, but after doing so, it actually fires off the rewrite condition and rule that should never have been fired (using the standard file -f and directory -d htaccess file above) - and it doesn't write a new log entry! a new (invisible man) request then triggers the index file in the last line of the htaccess file beware the resource limits in dreamhost basic accounts! if you go over their limits, and you have htacess with mod_rewrite lines you will see strange things that are only fit for halloween night - invisible men, haunted 404s! undead processes! zombie apache! htaccess moving on its own! yikes! hope this helps you avoid some hours of pain. | How to eliminate weird 404 errors in wp-admin? | wordpress |
Is there way to have multiple WYSIWYG editors for a custom post type? For example, if I had a 2 column layout I wanted to have one editor for one column and another editor for the other. | Say your custom post type was called <code> Properties </code> , you would add the box to hold your additional tinyMCE editor using code similar to this: <code> function register_meta_boxen() { add_meta_box("wysiwyg-editor-2", "Second Column", "second_column_box", "properties", "normal", "high"); } add_action('admin_menu', 'register_meta_boxen'); </code> <code> wysiwyg-editor-2 </code> is the ID that the meta box will have applied to it, <code> Second Column </code> is the title that the meta box will have, <code> second_column_box </code> is the function which will print out the HTML for the meta box, <code> properties </code> is our custom post type, <code> normal </code> is the location of the meta box, and <code> high </code> specifies that it should be shown as high in the page as possible. (Usually below the default tinyMCE editor). Then, taking this as the most basic example, you must attach the tinyMCE editor to a textarea. We still have to define our <code> second_column_box </code> function which will print the HTML for the meta box so this is as good a place as any to do this: <code> function second_column_box() { echo <<<EOT <script type="text/javascript"> jQuery(document).ready(function() { jQuery("#tinymce").addClass("mceEditor"); if ( typeof( tinyMCE ) == "object" && typeof( tinyMCE.execCommand ) == "function" ) { tinyMCE.execCommand("mceAddControl", false, "tinymce"); } }); </script> <textarea id="tinymce" name="tinymce"></textarea> EOT; } </code> There are a couple of issues which I'm not sure of how to overcome. The tinyMCE editor will be nested inside of a metabox, which might not be ideal, and it will not feature the ability to switch between HTML and Visual editing modes, as well as the the media insertion commands which the normal post editor has. Switching the modes appears to be defined as a function who's first argument is the ID, but yet it also appears to coded into the wp-tinymce script. It is possible to use the built in tinyMCE functions to do so, but this changes the textarea between full tinyMCE and a basic textarea, without any of the WP HTML insertion buttons. | Is there a way to get N number of WYSIWYG editors in a custom post type? | wordpress |
Is there any WordPress plugin that provides OpenID authentication for comments that works in WordPress 3.0? The OpenID plugin appears to be broken in WP 3.0 and no longer in active development (10 months since last update). | stackexchange-url ("stackexchange-url | OpenID for WordPress 3.x? | wordpress |
From the WordPress support forums: Hi, this is my website http://www.mp3ojax.com . I want to insert permalinks on the images on main page This is the code: <code> <a href="<?php the_permalink() ?> <?php endif; ?> <?php $metadataContent = ob_get_clean(); ?> <?php if (trim($metadataContent) != ''): ?> <div class="art-PostMetadataHeader"> <?php echo $metadataContent; ?> </a> </code> But I get urls like this: http://mp3ojax.com/joseph-krikorian-artarutyun-2008/%3C/a%3E%3C/div%3E%3Cdiv%20class= please can someone help me? Edit: Here is the full page: <code> <?php get_header(); ?> <div class="art-contentLayout"> <?php include (TEMPLATEPATH . '/sidebar1.php'); ?><div class="art-content"> <?php if (have_posts()) : ?> <?php while (have_posts()) : the_post(); ?> <div class="art-Post"> <div class="art-Post-tl"></div> <div class="art-Post-tr"></div> <div class="art-Post-bl"></div> <div class="art-Post-br"></div> <div class="art-Post-tc"></div> <div class="art-Post-bc"></div> <div class="art-Post-cl"></div> <div class="art-Post-cr"></div> <div class="art-Post-cc"></div> <div class="art-Post-body"> <div class="art-Post-inner art-article"> <h2 class="art-PostHeaderIcon-wrapper"> <span class="art-PostHeader"><a href="<?php the_permalink() ?>" rel="bookmark" title="<?php printf(__('Permanent Link to %s', 'kubrick'), the_title_attribute('echo=0')); ?>"> <?php the_title(); ?> </a></span> </h2> <?php ob_start(); ?> <?php $icons = array(); ?> <?php if (!is_page()): ?><?php ob_start(); ?><?php the_time(__('F jS, Y', 'kubrick')) ?> <?php $icons[] = ob_get_clean(); ?><?php endif; ?><?php if (!is_page()): ?><?php ob_start(); ?><?php _e('Author', 'kubrick'); ?>: <a href="#" title="<?php _e('Author', 'kubrick'); ?>"><?php the_author() ?></a> <?php $icons[] = ob_get_clean(); ?><?php endif; ?><?php if (current_user_can('edit_post', $post->ID)): ?><?php ob_start(); ?><?php edit_post_link(__('Edit', 'kubrick'), ''); ?> <?php $icons[] = ob_get_clean(); ?><?php endif; ?><?php if (0 != count($icons)): ?> <div class="art-PostHeaderIcons art-metadata-icons"> <?php echo implode(' | ', $icons); ?> </div> <?php endif; ?> <?php $metadataContent = ob_get_clean(); ?> <?php if (trim($metadataContent) != ''): ?> <div class="art-PostMetadataHeader"> <a href="<?php the_permalink() ?>"><?php echo $metadataContent; ?></a> </div> <?php endif; ?> <div class="art-PostContent"> <?php if (is_search()) the_excerpt(); else the_content(__('Read the rest of this entry &raquo;', 'kubrick')); ?> </div> <div class="cleared"></div> <?php ob_start(); ?> <?php $icons = array(); ?> <?php if (!is_page()): ?><?php ob_start(); ?><?php printf(__('Posted in %s', 'kubrick'), get_the_category_list(', ')); ?> <?php $icons[] = ob_get_clean(); ?><?php endif; ?><?php if (!is_page() && get_the_tags()): ?><?php ob_start(); ?><?php the_tags(__('Tags:', 'kubrick') . ' ', ', ', ' '); ?> <?php $icons[] = ob_get_clean(); ?><?php endif; ?><?php if (!is_page() && !is_single()): ?><?php ob_start(); ?><?php comments_popup_link(__('No Comments »', 'kubrick'), __('1 Comment »', 'kubrick'), __('% Comments »', 'kubrick'), '', __('Comments Closed', 'kubrick') ); ?> <?php $icons[] = ob_get_clean(); ?><?php endif; ?><?php if (0 != count($icons)): ?> <div class="art-PostFooterIcons art-metadata-icons"> <?php echo implode(' | ', $icons); ?> </div> <?php endif; ?> <?php $metadataContent = ob_get_clean(); ?> <?php if (trim($metadataContent) != ''): ?> <div class="art-PostMetadataFooter"> <?php echo $metadataContent; ?> </div> <?php endif; ?> </div> </div> </div> <?php endwhile; ?> <?php $prev_link = get_previous_posts_link(__('Newer Entries &raquo;', 'kubrick')); $next_link = get_next_posts_link(__('&laquo; Older Entries', 'kubrick')); ?> <?php if ($prev_link || $next_link): ?> <div class="art-Post"> <div class="art-Post-tl"></div> <div class="art-Post-tr"></div> <div class="art-Post-bl"></div> <div class="art-Post-br"></div> <div class="art-Post-tc"></div> <div class="art-Post-bc"></div> <div class="art-Post-cl"></div> <div class="art-Post-cr"></div> <div class="art-Post-cc"></div> <div class="art-Post-body"> <div class="art-Post-inner art-article"> <div class="art-PostContent"> <div class="navigation"> <?php if(function_exists('wp_page_numbers')) : wp_page_numbers(); endif; ?> </div> </div> <div class="cleared"></div> </div> </div> </div> <?php endif; ?> <?php else : ?> <h2 class="center"><?php _e('Not Found', 'kubrick'); ?></h2> <p class="center"><?php _e('Sorry, but you are looking for something that isn’t here.', 'kubrick'); ?></p> <?php if(function_exists('get_search_form')) get_search_form(); ?> <?php endif; ?> </div> <?php include (TEMPLATEPATH . '/sidebar2.php'); ?> </div> <div class="cleared"></div> <?php get_footer(); ?> </code> | There isn't really enough code as an example to fully understand if there is any additional issues, but the main thing which is causing the URL's to not work is the fact that the opening anchor tag is not closed. Adding a <code> "> </code> to the end of the first line should fix the issue. In addition the <code> art-PostMetadataHeader </code> div should be closed. <code> <a href="<?php the_permalink(); ?>"> <?php endif; ?> <?php $metadataContent = ob_get_clean(); ?> <?php if (trim($metadataContent) != ''): ?> <div class="art-PostMetadataHeader"> <?php echo $metadataContent; ?> </div> </a> </code> Having said that, nesting a block level element such as a <code> div </code> inside of an inline element such as an anchor is not standards compliant, but this code would have the same effect of linking all the <code> $metadataContent </code> , while being standards compliant. <code> <?php endif; ?> <?php $metadataContent = ob_get_clean(); ?> <?php if (trim($metadataContent) != ''): ?> <div class="art-PostMetadataHeader"> <a href="<?php the_permalink(); ?>"><?php echo $metadataContent; ?></a> </div> </code> | Permalink Problems | wordpress |
( Moderator's note: The original title was "How can I create create and use a custom template for custom post types in the Genesis theme framework?") I'm using the Genesis theme framework, with an almost completely 'stock' child theme. I have the WP Easy Post Types plugin installed, and have created one custom post type ("Members"). I have two custom fields created to use for the 'member' post type (phone number and address). I'm trying to figure out how to display the information from those fields in two places: <code> example.com/members </code> and <code> example.com/members/bob </code> . Genesis doesn't support the typical <code> single-posttype.php </code> file to create a template for the custom post type, but even if it did, that doesn't take care of <code> example.com/members </code> . Any suggestions on how to get the desired information to display? | Turns out I was wrong, Genesis does support using the <code> page_posttype.php </code> method of creating a custom template. It turned out to be very simple. Here's the contents of my page_members.php file (located in the child theme folder): <code> <?php /* Template Name: Members */ remove_action('genesis_loop', 'genesis_do_loop'); add_action('genesis_loop', 'custom_loop'); function custom_loop() { global $paged; $args = array('post_type' => 'members'); genesis_custom_loop( $args ); } genesis(); </code> | Using Custom Templates for Custom Post Types for the Genesis Theme Framework? | wordpress |
So I'm using Starkers to base my next WP theme on and I've run into a small issue, I was including my own version of jQuery in the <code> header.php </code> file but when inspecting my site using Firebug I noticed jquery was being downloaded twice, I did a bit of digging and noticed that not only was I including the file but so was the <code> wp_head() </code> function. In trying to fix the problem I noticed a comment in the header file, of which originated came from the Twenty Ten theme: <code> /* Always have wp_head() just before the closing </head> * tag of your theme, or you will break many plugins, which * generally use this hook to add elements to <head>, such * as styles, scripts, and meta tags */ </code> So here's my problem, I am under the impression that the jQuery file has to be set before any other file that wants to use it and that <code> wp_head() </code> should be the last thing in the <code> <head> </code> element, I'm slightly confused now as I'm wondering should I put <code> wp_head() </code> at the top so the WP included jQuery file will be used for all my plugins, even though it says not to do so. I did comment out the jQuery line in the <code> wp_head() </code> function but it's required for the admin page so I had to put it back. I'd also like to use (at least experiment) with using the Google CDN version of jQuery, but don't want to include it twice! I hope you understand what I'm trying to explain, any suggestions on how I can solve this problem would be most appreciated. I'd also appreciate any advice on how you handle your JavaScript files with the header file. Thanks! | From the wording of your question, you must be adding scripts by writing <code> <script> </code> tags in your template. Add your own scripts via <code> wp_enqueue_script() </code> in your template's <code> functions.php </code> , appropriately setting dependences on jQuery, and <code> wp_head() </code> will add the scripts for you. <code> function my_scripts() { wp_enqueue_script( 'my-sweet-script', get_bloginfo('template_directory') . '/script.js', array('jquery') ); } add_action('template_redirect', 'my_scripts'); </code> See the codex page for more info. | How to Link External jQuery/Javascript files with WordPress | wordpress |
I'm trying to set up a custom post type following this tutorial. However, I'm a bit confused as how/where to implement <code> update_post_meta() </code> . The tutorial suggests this pattern: <code> add_action('save_post', 'save_my_metadata'); function save_my_metadata() { global $post; update_post_meta($post->ID, 'my_metadata', $_POST['my_metadata']); } </code> Which does work, but has the unfortunate effect of adding that metadata to each and every post, whether it belongs to this custom type or not. I've put the above in <code> functions.php </code> and am guessing that might be part of the problem. I'm guessing I need to restrict the 'save_post' action to only trigger for posts of my custom type. | <code> function save_my_metadata($ID = false, $post = false) { if($post->post_type != 'your_post_type') return; update_post_meta($ID, 'my_metadata', $_POST['my_metadata']); } </code> That should work. Just replace 'your_post_type' with the name of the post type. Also, little known fact: the 'save_post' hook passes the post's ID as an argument. EDIT I updated the function to reflect Jan's comment. Thanks Jan! | How do I save metadata for a specific custom post type only? | wordpress |
I've got a project where I need to build a store locator for a client. I'm using a custom post type " <code> restaurant-location </code> " and I have written the code to geocode the addresses stored in postmeta using the Google Geocoding API (heres the link that geocodes the US White House in JSON and I've stored the latitude and longitude back to custom fields. I've written a <code> get_posts_by_geo_distance() </code> function that returns a list of posts in order of those which are closest geographically using the formula I found in the slideshow at this post . You might call my function like so (I'm starting with a fixed "source" lat/long): <code> <?php include "wp-load.php"; $source_lat = 30.3935337; $source_long = -86.4957833; $results = get_posts_by_geo_distance( 'restaurant-location', 'geo_latitude', 'geo_longitude', $source_lat, $source_long); echo '<ul>'; foreach($results as $post) { $edit_url = get_edit_url($post->ID); echo "<li>{$post->distance}: <a href=\"{$edit_url}\" target=\"_blank\">{$post->location}</a></li>"; } echo '</ul>'; return; </code> Here's the function <code> get_posts_by_geo_distance() </code> itself: <code> function get_posts_by_geo_distance($post_type,$lat_key,$lng_key,$source_lat,$source_lng) { global $wpdb; $sql =<<<SQL SELECT rl.ID, rl.post_title AS location, ROUND(3956*2*ASIN(SQRT(POWER(SIN(({$source_lat}-abs(lat.lat))*pi()/180/2),2)+ COS({$source_lat}*pi()/180)*COS(abs(lat.lat)*pi()/180)* POWER(SIN(({$source_lng}-lng.lng)*pi()/180/2),2))),3) AS distance FROM wp_posts rl INNER JOIN (SELECT post_id,CAST(meta_value AS DECIMAL(11,7)) AS lat FROM wp_postmeta lat WHERE lat.meta_key='{$lat_key}') lat ON lat.post_id = rl.ID INNER JOIN (SELECT post_id,CAST(meta_value AS DECIMAL(11,7)) AS lng FROM wp_postmeta lng WHERE lng.meta_key='{$lng_key}') lng ON lng.post_id = rl.ID WHERE rl.post_type='{$post_type}' AND rl.post_name<>'auto-draft' ORDER BY distance SQL; $sql = $wpdb->prepare($sql,$source_lat,$source_lat,$source_lng); return $wpdb->get_results($sql); } </code> My concern is that the SQL is about as non-optimized as you can get. MySQL can't order by any available index since the source geo is changeable and there's not a finite set of source geos to cache. Currently I'm stumped as to ways to optimize it. Taking into consideration what I've done already the question is: How would you go about optimizing this use-case? It's not important that I keep anything I've done if a better solution would have me throw it out. I'm open to considering almost any solution except for one that requires doing something like installing a Sphinx server or anything that requires a customized MySQL configuration. Basically the solution needs to be able to work on any plain vanilla WordPress install. (That said, it would be great if anyone wants to list alternate solutions for others who might be able to get more advanced and for posterity.) Resources Found FYI, I did a bit of research on this so rather than have you do the research again or rather than have you post any of these links as an answer I'll go ahead and include them. http://jebaird.com/blog/calculating-distance-miles-latitude-and-longitude http://wordpress.org/extend/plugins/geolocation/screenshots/ http://code.google.com/apis/maps/articles/phpsqlsearch.html http://www.rooftopsolutions.nl/blog/229 http://planet.mysql.com/entry/?id=18085 http://blog.peoplesdns.com/archives/24 http://www.petefreitag.com/item/622.cfm http://www.phpro.org/tutorials/Geo-Targetting-With-PHP-And-MySQL.html http://forum.geonames.org/gforum/posts/list/692.page http://forums.mysql.com/list.php?23 http://www.scribd.com/doc/2569355/Geo-Distance-Search-with-MySQL http://developer.yahoo.com/maps/rest/V1/geocode.html http://geocoder.us/ Regarding Sphinx Search http://sphinxsearch.com/ https://launchpad.net/wp-sphinx-plugin http://forums.site5.com/showthread.php?t=28981 http://wordpress.org/extend/plugins/wordpress-sphinx-plugin/ http://wordpress.org/extend/plugins/sphinx-search/ http://www.mysqlperformanceblog.com/2008/02/15/mysql-performance-blog-now-uses-sphinx-for-site-search/ | What precision do you need? if it's a state/national wide search maybe you could do a lat-lon to zip lookup and have precomputed distance from zip area to zip area of the restaurant. If you need accurate distances that won't be a good option. You should look into a Geohash solution, in the Wikipedia article there is a link to a PHP library to encode decode lat long to geohashs. Here you have a good article explaining why and how they use it in Google App Engine (Python code but easy to follow.) Because of the need to use geohash in GAE you can find some good python libraries and examples. As this blog post explains, the advantage of using geohashes is that you can create an index on the MySQL table on that field. | Optimizing a Proximity-based Store Location Search on a Shared Web Host? | wordpress |
What good free and open source alternatives exist to the Thesis theme ?? | I assume by " alternatives " you mean Theme Frameworks ? If yes, here's a list: Atahualpa The Buffet Framework Carrington Hybrid Sandbox Thematic WP Framework UPDATE: I added a few more: ashford Basis Brave New World Buffet Imagination Naked OnePress Starkers Startbox Starter Theme Project Vanilla Whiteboard WordPreciousss wp-constructor If that's not what you meant, please clarify. | Free/Open-Source Theme Frameworks as an Alternate to Thesis? | wordpress |
When I wrote a theme, I made sure it was compliant with XHTML 1.1 and CSS 2.1. Then I added plugins and the theme is no longer compliant with XHTMl 1.1. Then I used Google API font in my CSS and it is longer CSS 2.1 compliant. Is there a way I can keep the compliance without getting rid of the plugins, font etc or should I just ignore the validation errors? | Correction, your theme was still compliant with XHTML 1.1 and CSS 2.1, but the plug-ins you added injected additional code that wasn't compliant. Unfortunately, there's no easy way to maintain compliance if you're using plug-ins. The best you can do is validate your theme and all of the markup you are personally responsible for, then hope that other developers have taken the time to validate their own work. The alternative is a lot more work on your part - you can still use the core functionality of the plug-ins, but don't allow them to output any markup to the browser. Add your own custom layer that unhooks everything the plug-in touches, and build your own output buffer. This is the only way you will have control over the style of markup being sent to the browser. Several plug-ins are beginning to use HTML 5 ... others are trying to use CSS3. If you install these plug-ins and don't take steps to sanitize and validate their output, then your site will cease to validate properly. | How to maintain W3C standards compliance of a theme | wordpress |
The question is How do I make the header on the Twenty Ten theme less tall? That question was asked over at the LinkedIn WordPress group that is hidden from search engines so I thought I'd copy my answer to here. I've also made it a community wiki so it doesn't pass reputation to me. | To make the header on the Twenty Ten theme less tall (i.e. a height with fewer pixels) put this code at the bottom of your theme's " <code> functions.php </code> " file (being sure to change the number <code> 180 </code> to whatever height you want): <code> <?php add_action('twentyten_header_image_height','yoursite_header_image_height'); function yoursite_header_image_height($height) { return 180; // Modify this to whatever pixel height you want. } </code> Then you'll need to go to " Appearance > Header " in your admin console and upload your new smaller image (here's the URL to that admin page): http://example.com/wp-admin/themes.php?page=custom-header And here's what that admin page looks like: You might also consider making your modifications on a " Child Theme " (if you have not already.) Here's an article (that is overly complicated) but it's really as simple as just creating a directory on your web server under the " <code> /wp-content/themes/ </code> " subdirectory (I'd call it " <code> /wp-content/themes/yoursite/ </code> ") and creating a " <code> style.css </code> " in that directory with the following: <code> /* Theme Name: Your Child Theme Name Description: Theme for your-site.com Author: Your Name Version: 1.0 Template: twentyten */ @import url("../twentyten/style.css"); </code> Then you can create a new " <code> functions.php </code> " file and put the above PHP code in it rather than modifying the files in the directory of the TwentyTen theme and having to deal with doing it again it when Twenty Ten has a security update. Hope this helps. -Mike | Making the Header on the Twenty Ten Theme Less Tall? | wordpress |
By default, WordPress strips out any content that might be unescaped HTML in comments from unregistered users, which is good to protect against XSS, but it unnecessarily extends that filtering into <code> <pre> </code> elements too. On my blog, where almost every post generates comments that benefit from HTML code snippets, that filtering has caused my users (and myself) lots of frustrating trouble. Is there a way to "fix" that overly aggressive filtering inside <code> <pre> </code> elements within unregistered comments, without disabling it for the rest of the comment? Preferably, in a way that survives upgrades. | a small solution; the highlighting was in my blog via javascript <code> function pre_esc_html($content) { return preg_replace_callback( '#(<pre.*?>)(.*?)(</pre>)#imsu', create_function( '$i', 'return $i[1].esc_html($i[2]).$i[3];' ), $content ); } add_filter( 'the_content', 'pre_esc_html', 9 ); </code> | Relaxing unescaped HTML filtering inside tags? | wordpress |
What is a plugin lifetime within a deployed instance of WordPress? Namely: do the plugins modify existing files or do they only use defined extension points within WordPress? are plugins allowed to modify database schema (e.g. add new columns)? how does Wordpress make sure that plugin uninstall always leaves WordPress in original state? (Does it?) | Short answer: Plugins do not modify existing files, they hook into WordPress via an exposed API. Plugins can modify database schema. Plugins don't have to uninstall cleanly. Plugin Hooks Plugins hook into WordPress at specific point exposed by the WordPress core. http://codex.wordpress.org/Plugin_API As an example, the function <code> get_option() </code> reads a site option from the database. Before any real action is taken inside this function, WordPress calls <code> apply_filters( 'pre_option_' . $option, false ) </code> . Given an option <code> foobar </code> , a plugin could override this option's true value with the following code: <code> function override_foobar( $unused ) { return 'My custom value.'; } add_filter( 'pre_option_foobar', 'override_foobar' ); // add_filter(hook, function) </code> See also http://adambrown.info/p/wp_hooks/. Plugins modifying the database Plugins have the ability to modify the database, assuming the WordPress database user still has that permission. Some of the more complex plugins add their own tables. It's possible that a plugin could modify core tables, and hopefully they would do this responsibly and in a way that doesn't break things if the plugin is removed. This has to be examined on a plugin-by-plugin basis. Uninstalling plugins The <code> deactivate_plugins() </code> function calls the action <code> do_action( 'deactivate_' . trim( $plugin ) ) </code> . A plugin should hook to this action if specific things need to happen when the plugin is deactivated. In my experience few plugins do a lot of deactivation cleanup, ie. putting their settings in cold storage in case they are activated again. | Does plugin uninstall always put WordPress back into original state? | wordpress |
I wanted to create a WP plugin. So I requested and my request was approved by WordPress.org But I don't want to develop that plugin anymore. How can I delete the repository forever or request its deletion. | Please mail plugins - wordpress.org and ask them to remove your plugin. Provide all infos and explain that you won't start to develop the plugin so the name should no longer be blocked. I would use the same email as while registering the plugin (maybe even replying to it) and I think they will remove it after some days. | Delete WordPress plugin Repository | wordpress |