question
stringlengths
0
34.8k
answer
stringlengths
0
28.3k
title
stringlengths
7
150
forum_tag
stringclasses
12 values
When developing plugins that requires data storage, what's the pros and cons of using one method or another ? The explanation given in the codex is not detailed: Before jumping in with a whole new table, however, consider if storing your plugin's data in WordPress' Post Meta (a.k.a. Custom Fields) would work. Post Meta is the preferred method; use it when possible/practical.
Well, if I take the hat of a WP script kiddie, my answer would be: use post_meta, always. However, I happen to know a thing or two about databases, so my answer is: never, ever, ever, use an EAV (aka the post_meta table) to store data that you might to need to query. On the index front, there are basically none worth using in meta tables. So, if you're storing data type XYZ and are hoping you query all posts that have XYZ with a value of <code> 'abc' </code> , well... good luck. (See all of the users/roles/caps related tickets in the WP trac to give you an idea of how gory it can get.) On the join front, you quickly crash into the limit at which the optimizer decides to use a generic algorithm instead of analyzing the query when there are multiple join criteria. Thus, no, no, no, no. Don't ever, ever, ever use a meta. Unless what's you're storing is cosmetic and will never be part of a query criteria. It breaks down to your app. If you're storing, say, the birthdate of a movie director, than big deal. Use a meta all you want. But if you're storing, say, the release date of a movie, you'd be nuts to not use a separate table (or adding columns to the posts table) and add an index to that column.
Post meta vs separate database tables
wordpress
I installed the Deprecated Calls plugin and it's telling me to change <code> register_sidebar_widget() </code> and <code> register_widget_control() </code> , essentially add <code> wp_ </code> first. I did but I'm getting <code> Missing argument 3 for wp_register_sidebar_widget() </code> and <code> wp_register_widget_control() </code> Is it ok if I put the default <code> none </code> for the 3rd arg?
The signature of newer function is different: <code> register_sidebar_widget </code> <code> ( $name, </code> <code> $output_callback </code> <code> , $classname ); </code> <code> wp_register_sidebar_widget </code> <code> ( $id, $name, </code> <code> $output_callback </code> <code> , $options ); </code> Can't simply replace one function with another here, need to re-order arguments accordingly.
Missing argument 3 for wp_register_sidebar_widget()
wordpress
Hi all, I'd like to hear what others who are delivering complex non-blog solutions to clients with WordPress as a platform what they are using for automated Regression Testing ? For those not familiar with the term "regression testing" Wikipedia defines it as: Regression testing is any type of software testing that seeks to uncover software errors after changes to the program (e.g. bugfixes or new functionality) have been made, by retesting the program. The intent of regression testing is to assure that a change, such as a bugfix, did not introduce new bugs. More telling Wikipedia says the following which is exactly what I'm experiencing on a project right now: Experience has shown that as software is fixed, emergence of new and/or reemergence of old faults is quite common. Sometimes reemergence occurs because a fix gets lost through poor revision control practices (or simple human error in revision control). Often, a fix for a problem will be "fragile" in that it fixes the problem in the narrow case where it was first observed but not in more general cases which may arise over the lifetime of the software. Frequently, a fix for a problem in one area inadvertently causes a software bug in another area. Finally, it is often the case that when some feature is redesigned, some of the same mistakes that were made in the original implementation of the feature were made in the redesign. With the global nature of actions and filters I'm finding that complexity starts ramping as I add more client-requested functionality and it becomes hard to get a complex plugin stable, especially if it uses a lot of calls to <code> WP_Query </code> and updates the database a lot. The solution in my mind would be to set up regression testing with a series of "test cases" to comprise a "test suite." In concept it's not that hard when you are testing the HTML output of HTTP GET requests. But it gets a little more complicated when you have to test things when logged in via the admin console and/or to test jQuery interactions. I'm setting this up as a community wiki in hopes we can gather best practices here but I'm really anxious to hear processes if any other WordPress professionals are using.
PHPUnit would come to mind, if the WP test suite wasn't so broken, and if WP had been designed and written in a way that it could actually be tested properly. ;-) More seriously, you can test your plugins all you want from their functional standpoint with unit tests and the like. The issue is that these tests won't guarantee that they'll catch subtle chances introduced by WP upgrades, let alone that they'll continue to work once plugged into a customized WP install. Among the colorful things I've seen happen: A subtle change in the WP API affects your plugin's functionality, e.g. the hook you're on used to get a term id and it's now getting a term taxonomy id. (Chances are good that your test terms conveniently have the same id for both). A subtle change in the WP API results in your receiving a <code> WP_Error </code> object instead of the previously expected value of <code> false </code> as bad input. Your plugin is added from within the mu-plugins folder, resulting in a subtly different code flow. Your plugin worked fine until memcached or some other persistent store got enabled. Your plugin worked fine until the despised switch_to_blog() got called. A plugin changes the hook which it resides on when called, and unknowingly interrupts it as a side effect. A plugin (un?)knowingly messes around with your input or output data to the point where things look broken even though you're not at fault. I could expand the list on and on, but those would be the key items that broke my own plugins. The two items are arguably catchable with unit tests. The next two as well, if you're patient enough, but I'd argue that WP should not change the way things work when they occur. No amount of testing will work around the buggy implementation of switch_to_blog(). And the last two are hopelessly untestable. Oh, and... don't even get me started on the onslaught of attachments, auto drafts, revisions, menu items and what not that end up stored in the posts table. Good luck... :-)
Best Practices for Regression Testing WordPress Websites?
wordpress
I’m using Wordpress as a CMS for this site http://www.seadragon.co.uk/new_site/portfolio.html ...and it’s the first time I’ve ever used wordpress so sorry if I get the terminology wrong.... My client needs to be able to add new projects (case studies) to the portfolio section, and each of them can have it’s own slideshow. I thought they could create a new post category for each project slideshow, and then a new page for each project. The problem I have is how to get my client to associate the post category with the project page (so I can pull the correct category posts in to the slideshow dynamically). I thought maybe I could try and get them to use the same naming convention for the category she creates (for the project sildeshow) and the page she creates (for the project)? Does this sound like it’ll work? Is there a better way I can do this, or another plugin that would be better suited. Here’s the code from my portfolio template... currently the categoryID is hard coded in the query. <code> &lt;div id="slider"&gt; &lt;?php //Reset Query //wp_reset_query(); global $wp_query; $query = "post_type=post&amp;cat=5"; $wp_query = new WP_Query( $query ); if ( have_posts() ) : while ( have_posts() ) : the_post(); echo get_the_post_thumbnail($post-&gt;ID, 'large'); ?&gt; &lt;?php endwhile; endif; ?&gt; &lt;/div&gt; &lt;script type="text/javascript"&gt; $(window).load(function() { $('#slider').nivoSlider(); }); &lt;/script&gt; </code> Hope that makes some sense? Many thanks. Edit: Fixed formatting so embedded code sample would display
A better solution would be to create a "Project" post type and a custom taxonomy to separate the different types of projects. I recently did this on my own website because I wanted a way to keep my projects separate from the rest of my content. I used jQuery cycle instead of Nivo but the concept is the same. Custom post types have a built in user interface so it wont be confusing for your client to add new projects. It will also allow you to customize the way the "Projects" are displayed using a single-project.php template file. I won't go into how to register post types because The Codex explains this very well but I will show you how to get all the attached images to the post and display them in the slider. <code> &lt;?php //The following code is for a sample single-post_type.php ?&gt; &lt;?php get_header(); ?&gt; &lt;div id="content"&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;h1 class="project-title"&gt;&lt;?php the_title(); ?&gt;&lt;/h1&gt; &lt;div class="entry"&gt; &lt;div id="slider"&gt; &lt;?php // This gets all the images attached to the current post inside the loop $args = array( 'post_type' =&gt; 'attachment', 'posts_per_page' =&gt; -1, 'post_status' =&gt; null, 'post_parent' =&gt; $post-&gt;ID ); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $attachment) { echo wp_get_attachment_image($attachment-&gt;ID,'medium', false); } } ?&gt; &lt;/div&gt; &lt;!-- /slider --&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;!-- /post --&gt; &lt;?php endwhile; else: ?&gt; &lt;p&gt;&lt;?php _e('Not Found','your_theme_name'); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;?php get_sidebar(); ?&gt; &lt;?php get_footer(); ?&gt; </code>
Multiple instances of nivo slider plugin
wordpress
Is there a way to overwrite a core function is the Wordpress core using a plugin? I don't need to inject code, I need to replace the function entirely with a re-written version. The specific function is wp_nav_menu_item_post_type_meta_box() in /wp-admin/includes/nav-menu.php Basically there's a lack of functionality that is not meeting a clients need, so I need to overwrite this function with one I have created. I've made heavy modifications to the function, and I want to have the ability to overwrite the function with my own through a plugin instead of editing the file directly. I know this probably isn't much better than hacking the core, however its a temporary immediate solution.
Not really, no. You can override built-in PHP functions, but not user-defined functions. However, all this function does is define a meta box. Why not define your own? Once you've got your own meta box defined and added, you can call <code> remove_meta_box </code> to remove the standard one: <code> remove_meta_box( 'add-POSTTYPENAME', 'nav-menus', 'side'); </code> The meta box is originally added for each custom post type using a loop. The ID of the meta box is defined as <code> add-{$id} </code> where <code> $id </code> is the name of the post-type. So you can remove this meta box for all post types by doing a similar loop, or just for a specific post type. It's up to you. Then just add your custom meta box for the post types you need. Here's the function that adds the original for reference: <code> function wp_nav_menu_post_type_meta_boxes() { $post_types = get_post_types( array( 'show_in_nav_menus' =&gt; true ), 'object' ); if ( ! $post_types ) return; foreach ( $post_types as $post_type ) { $post_type = apply_filters( 'nav_menu_meta_box_object', $post_type ); if ( $post_type ) { $id = $post_type-&gt;name; add_meta_box( "add-{$id}", $post_type-&gt;labels-&gt;name, 'wp_nav_menu_item_post_type_meta_box', 'nav-menus', 'side', 'default', $post_type ); } } } </code>
Overwriting Core Wordpress Functions with Plugins
wordpress
Is there a way to use wp multifile upload system in my plugin?
You could always include the stuff related to swfupload, yes. But there will be a better way in WP 3.1: you'll be able to use the whole upload UI.
Use WordPress file upload in my plugin - on frontend and on backend?
wordpress
I'm using this piece of code to show related posts based on the tag of the post you are viewing. I'd like to modify is a little to exclude the related posts from the loop if they are in the same category of the post you are viewing Reason for this is i already have a loop to show related posts in the same category, so trying to cut out the duplicates. <code> &lt;?php $tags = wp_get_post_tags($post-&gt;ID); if ($tags) { $first_tag = $tags[0]-&gt;term_id; $args=array( 'tag__in' =&gt; array($first_tag), 'post__not_in' =&gt; array($post-&gt;ID), 'showposts'=&gt;5, 'caller_get_posts'=&gt;1 ); $my_query = new WP_Query($args); if( $my_query-&gt;have_posts() ) { while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt; &lt;!-- loop here --&gt; &lt;?php endwhile; }wp_reset_query(); } ?&gt; </code> Thanks
Very similar to what you do with tags. Retrieve IDs of categories for current post: <code> $categories = get_the_category(); $cat_ids = array(); foreach($categories as $category) $cat_ids[] = $category-&gt;term_id; </code> Then exclude them in query: <code> 'category__not_in' =&gt; $cat_ids, </code>
Related Tags not in category
wordpress
Thanks to your suggestions, I enabled wp_debug and discovered flaws with my plugin. I have a filter for sorting posts by votes. I use it when the <code> sort </code> URL parameter is on. <code> add_filter( 'posts_where', 'votes', 10, 2 ); </code> I used to get <code> Undefined index: sort </code> so I modified my function to first check if the variable is set. <code> function votes( $where, $query ) { $sort = array_key_exists('sort', $query-&gt;query_vars) ? $_GET['sort'] : null; if ( isset($sort) ) { $where .= " AND $sort &gt;= votes"; } return $where; } </code> This works fine but I'm not confident if it's correct. I'm wondering if there's a better method to do this.
The variable you have named <code> $query </code> is actually the WP_Query instance having filters applied to it. You can simply call its function <code> get </code> to retrieve query vars. For example: <code> function votes( $where, $query ) { $sort = $query-&gt;get('sort'); if (!empty($sort) $where .= " AND $sort &gt;= votes"; return $where; } </code>
Check if variable is set in filter
wordpress
I'm curious what dependencies <code> add_image_size() </code> has because I just copied a theme over to a new server and began adding thumbnails to custom post types only to find out that my request for hard-cropping is being ignored, and the images are kept proportional. functions.php <code> ... set_post_thumbnail_size( 80, 80, true ); add_image_size( 'micro', 32, 32, true); add_image_size( 'featured', 340, 225, true ); add_image_size( 'videowide', 460, 225, true ); ... </code> On my local server (WAMP Server on Windows Vista) the <code> true </code> is respected, and the images are cropped in such a way that extra pixels are lost - edges aren't respected. On my live server (CloudLinux Server 5.5 x64), the images are kept proportional. Is there some gdlibrary dependencies or something I am needing to change on the live server to get the expected results?
This particular issue was caused by an environment missing GD . After installing GD on the server, the issue was resolved. Of course you will need to go back and re-submit your thumbnails to have correct cropping, or use a plugin to retroactively recreate your thumbnails.
Server B handling add_image_size() differently than Server A
wordpress
Often times, a custom theme for Wordpress will require a dynamic content that reflects a relationship to a top level page of a site. Is there a Conditional Tag that will check if the current page is a grand-child (or separated by further generations) by ID?
Turns out there is an excellent function that has been passed around the Wordpress forums <code> is_tree() </code> <code> function is_tree($pid) { // $pid = The ID of the page we're looking for pages underneath global $post; // load details about this page $anc = get_post_ancestors( $post-&gt;ID ); foreach($anc as $ancestor) { if(is_page() &amp;&amp; $ancestor == $pid) { return true; } } if(is_page()&amp;&amp;(is_page($pid))) return true; // we're at the page or at a sub page else return false; // we're elsewhere }; </code> To use it in template, just give it the ID you want to check the current page against, and it will return true if the current page is a descendant. <code> &lt;?php if(is_tree(12)){echo 'foobar';} ?&gt; </code>
How can I detect hierarchal relationships beyond children (grandchild, great-grandchild, etc)?
wordpress
I'm wondering how/if I can access more than the most recent X posts defined in the wordpress settings. I've seen plugins that migrate all blog content through RSS, haven't poked around to see their methods. Basically I manage a couple hundred WordPress blogs, and I'm building a newsletter generator for my clients. They want to be able to select a few posts and have the excerpts appear in the newsletter body. The sites are spread across multiple servers and the newsletter generator is being built on top of our CRM, so direct database queries would be difficult. RSS would be the cleanest, but I can't seem to figure out how to access more than 10 at a time (when 10 is set in the admin). Any ideas?
Codex has example snippet on how to use <code> post_limits </code> filter to override amount set in admin for feed. <code> if (isset ($query-&gt;query_vars['feed']) and ($query-&gt;query_vars['feed'] == 'ics')) add_filter('post_limits','no_limits_for_feed'); function no_limits_for_feed($limits) { return ('') ; } </code> http://codex.wordpress.org/Function_Reference/query_posts#Usage_Tips
Get all posts in RSS
wordpress
I have custom roles in my setup and I want to be able to automatically change a user's role thru a function. Say user A has a SUBSCRIBER role, how do I change it to EDITOR? When adding a role we just: <code> add_role( $role_name , $role_display_name , array( 'read' =&gt; true, 'edit_posts' =&gt; false, 'delete_posts' =&gt; false, )); </code> How about changing a role? Is there something like: <code> change_role($old_role, $new_role); </code> UPDATE: I think this one will do: <code> $wp_user_object = new WP_User($current_user-&gt;ID); $wp_user_object-&gt;set_role('editor'); </code>
See the WP_User class, you can use this to add and remove roles for a user. EDIT: I really should of provided more information with this answer initially, so i'm adding more information below. More specifically, a user's role can be set by creating an instance of the WP_user class, and calling the <code> add_role() </code> or <code> remove_role() </code> methods. Example Change a subscribers role to editor <code> // NOTE: Of course change 3 to the appropriate user ID $u = new WP_User( 3 ); // Remove role $u-&gt;remove_role( 'subscriber' ); // Add role $u-&gt;add_role( 'editor' ); </code> Hopefully that's more helpful than my initial response, which wasn't necessarily as helpful.
How to change a user's role?
wordpress
I recently restored a WP multi-site 3.0.1 database from production to a staging environment, and when I try to login, I am being redirected to an HTTPS URL. The browser complains that the certificate is bad, and then when I click "proceed", it says page not found. I have cleared my browser cookies and all that good stuff, but it still won't let me login. Also, I am experiencing intermittent "No site defined on this host" errors when I try to login. I've never seen this issue before, and I have definitely done this backup db restore process before. Thanks for your help, Dave
I figured this one out finally. It turns out that the data in the wp_usermeta table for user_id=1 (admin) was corrupted. This was apparently causing the SSL redirect issue when trying to login to any domains. Once I restored the proper data for user_id=1 into wp_usermeta, everything worked fine. I would much rather have WordPress give an error like "hey, your usermeta data is messed up", rather than have some strange random behavior like that. Thanks for the help, Dave
wp-login.php redirecting to HTTPS
wordpress
i need a help, i have a theme, where in i have a twitter widget, i just want to separate it, and keep it in different file, as if it is a plugin, here are is the complete code, what i have to do? this code was in file admin-functions.php <code> /*-----------------------------------------------------------------------------------*/ /* Twitter's Blogger.js output for Twitter widgets */ /*-----------------------------------------------------------------------------------*/ function woo_twitter_script($unique_id,$username,$limit) { ?&gt; &lt;script type="text/javascript"&gt; &lt;!--//--&gt;&lt;![CDATA[//&gt;&lt;!-- function twitterCallback2(twitters) { var statusHTML = []; for (var i=0; i&lt;twitters.length; i++){ var username = twitters[i].user.screen_name; var status = twitters[i].text.replace(/((https?|s?ftp|ssh)\:\/\/[^"\s\&lt;\&gt;]*[^.,;'"&gt;\:\s\&lt;\&gt;\)\]\!])/g, function(url) { return '&lt;a href="'+url+'"&gt;'+url+'&lt;/a&gt;'; }).replace(/\B@([_a-z0-9]+)/ig, function(reply) { return reply.charAt(0)+'&lt;a href="http://twitter.com/'+reply.substring(1)+'"&gt;'+reply.substring(1)+'&lt;/a&gt;'; }); statusHTML.push('&lt;li&gt;&lt;span&gt;'+status+'&lt;/span&gt; &lt;a style="font-size:85%" href="http://twitter.com/'+username+'/statuses/'+twitters[i].id+'"&gt;'+relative_time(twitters[i].created_at)+'&lt;/a&gt;&lt;/li&gt;'); } document.getElementById('twitter_update_list_&lt;?php echo $unique_id; ?&gt;').innerHTML = statusHTML.join(''); } function relative_time(time_value) { var values = time_value.split(" "); time_value = values[1] + " " + values[2] + ", " + values[5] + " " + values[3]; var parsed_date = Date.parse(time_value); var relative_to = (arguments.length &gt; 1) ? arguments[1] : new Date(); var delta = parseInt((relative_to.getTime() - parsed_date) / 1000); delta = delta + (relative_to.getTimezoneOffset() * 60); if (delta &lt; 60) { return 'less than a minute ago'; } else if(delta &lt; 120) { return 'about a minute ago'; } else if(delta &lt; (60*60)) { return (parseInt(delta / 60)).toString() + ' minutes ago'; } else if(delta &lt; (120*60)) { return 'about an hour ago'; } else if(delta &lt; (24*60*60)) { return 'about ' + (parseInt(delta / 3600)).toString() + ' hours ago'; } else if(delta &lt; (48*60*60)) { return '1 day ago'; } else { return (parseInt(delta / 86400)).toString() + ' days ago'; } } //--&gt;!]]&gt; &lt;/script&gt; &lt;script type="text/javascript" src="http://twitter.com/statuses/user_timeline/&lt;?php echo $username; ?&gt;.json?callback=twitterCallback2&amp;amp;count=&lt;?php echo $limit; ?&gt;"&gt;&lt;/script&gt; </code> ` and this second code i found in theme-widget.php ` <code> /*---------------------------------------------------------------------------------*/ /* Twitter widget */ /*---------------------------------------------------------------------------------*/ class Woo_Twitter extends WP_Widget { function Woo_Twitter() { $widget_ops = array('description' =&gt; 'Add your Twitter feed to your sidebar with this widget.' ); parent::WP_Widget(false, __('Woo - Twitter Stream', 'woothemes'),$widget_ops); } function widget($args, $instance) { extract( $args ); $title = $instance['title']; $limit = $instance['limit']; if (!$limit) $limit = 5; $username = $instance['username']; $unique_id = $args['widget_id']; ?&gt; &lt;?php echo $before_widget; ?&gt; &lt;?php if ($title) echo $before_title . $title . $after_title; ?&gt; &lt;ul id="twitter_update_list_&lt;?php echo $unique_id; ?&gt;"&gt;&lt;li&gt;&lt;/li&gt;&lt;/ul&gt; &lt;?php echo woo_twitter_script($unique_id,$username,$limit); //Javascript output function ?&gt; &lt;?php echo $after_widget; ?&gt; &lt;?php } function update($new_instance, $old_instance) { return $new_instance; } function form($instance) { $title = esc_attr($instance['title']); $limit = esc_attr($instance['limit']); $username = esc_attr($instance['username']); ?&gt; &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id('title'); ?&gt;"&gt;&lt;?php _e('Title:','woothemes'); ?&gt;&lt;/label&gt; &lt;input type="text" name="&lt;?php echo $this-&gt;get_field_name('title'); ?&gt;" value="&lt;?php echo $title; ?&gt;" class="widefat" id="&lt;?php echo $this-&gt;get_field_id('title'); ?&gt;" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id('username'); ?&gt;"&gt;&lt;?php _e('Username:','woothemes'); ?&gt;&lt;/label&gt; &lt;input type="text" name="&lt;?php echo $this-&gt;get_field_name('username'); ?&gt;" value="&lt;?php echo $username; ?&gt;" class="widefat" id="&lt;?php echo $this-&gt;get_field_id('username'); ?&gt;" /&gt; &lt;/p&gt; &lt;p&gt; &lt;label for="&lt;?php echo $this-&gt;get_field_id('limit'); ?&gt;"&gt;&lt;?php _e('Limit:','woothemes'); ?&gt;&lt;/label&gt; &lt;input type="text" name="&lt;?php echo $this-&gt;get_field_name('limit'); ?&gt;" value="&lt;?php echo $limit; ?&gt;" class="" size="3" id="&lt;?php echo $this-&gt;get_field_id('limit'); ?&gt;" /&gt; &lt;/p&gt; &lt;?php } } register_widget('Woo_Twitter'); </code> i just want this code to be a different file, just like a plugin, so that i can use this in my another theme also, can anyone help me here???
Other than order of execution it doesn't really matter where code is run. In general case you can move code to Functions File ( <code> functions.php </code> ) of theme or create simple plugin and it will still work. In this specific case the code seems to be part of WooFramework so you will need to additionally check so that it isn't declared twice (causing error), for example by using <code> function_exists() </code> .
Converting theme widgets to plugins?
wordpress
I installed WordPress on my website along with a theme close to what I wanted. I then changed virtually all the formatting to make it conform to my site. I don't plan on publishing my version, but I would like to make it my own so as not to confuse it with the original. I get notices about updates to the original and I don't want to inadvertently upgrade it. I see that the folder under themes has the name of the theme, but I imagine there's more to it than that. I can do database alters if necessary. Would it be easier just to create a new theme and copy all the files to it?
The alternative to using a child theme is to make two adjustments to the current theme although technically only one is actually required. Update the theme name in the theme's style.css file in the commented section at the top, sometimes referred to as the theme's headers. Rename the theme's main folder, ie. <code> wp-content/themes/THIS-THEME-NAME </code> <code> #1 </code> is required, the second is optional, but advised so you don't clash with any new copies of the original theme that may get uploaded(which would overwrite your changed version). NOTE: If you plan to make these changes to a theme, switch to another theme momentarily on the installation whilst doing so, otherwise your database will get left holding incorrect data on the currently active theme(technically it should cause a theme reset anyway, but it would be the better practice to switch theme before making the changes). Personally i think the child theme approach is safer, but seeing as you've already modded the theme that's potentially hours of work to re-add all the custom code into new files(in the form of a child theme), so hopefully the above is helpful.. :)
How to Take Ownership of a Theme
wordpress
I see many methods of showing thumbnails in WordPress, but I'm not immediately sure how I could get only the path to a post's thumbnail rather than the html-ready code generated by functions like <code> the_post_thumbnail() </code> and <code> get_the_post_thumbnail() </code> . What methods are available to me to get only the path of the thumbnail (to set it as a bgimage) rather than the <code> &lt;img /&gt; </code> tag? Do I only have the option of parsing the results of the <code> get_ </code> method or is there an easier way?
Thumbnail is essentially attachment so you can approach from that side - lookup ID with <code> get_post_thumbnail_id() </code> and fetch data with <code> wp_get_attachment_image_src() </code> , like this: <code> if (has_post_thumbnail()) { $thumb = wp_get_attachment_image_src(get_post_thumbnail_id(), 'thumbnail_name'); echo $thumb[0]; // thumbnail url } </code> ( source )
Getting Thumbnail Path rather than Image Tag
wordpress
I am trying to output a list of categories per an article. I am using the following code, <code> &lt;?php wp_list_categories('child_of=270&amp;style=none'); ?&gt; </code> (string) Style to display the categories list in. A value of list displays the categories as list items while none generates no special display method (the list items are separated by <code> &lt;br&gt; </code> tags). How do I remove the stupid <code> &lt;br /&gt; </code> after each output? Frustrating how this code <code> &lt;?php the_category(', '); ?&gt; </code> Will output the links without a line break... Any help would be greatly appreciated.
I came to a solution for this by reviewing the Wordpress Codex . The trick is to turn off the automatic echo of wp_list_categories, and then use str_replace(). My example follows: <code> &lt;?php $variable = wp_list_categories('child_of=270&amp;style=none&amp;echo=0'); ?&gt; &lt;?php $variable = str_replace('&lt;br /&gt;', '', $variable); ?&gt; &lt;?php echo $variable; ?&gt; </code> The only real change in your query is the inclusion of "echo=0" which will return the information in a variable rather than just displaying it. The real work is done by str_replace() which looks for any <code> &lt;br /&gt; </code> tags and removes them from the string. Then just echo out the updated string and no more breaks!
Remove line breaks in wp_list_categories()?
wordpress
I would like to install a plugin on 3 out of the 20 blogs I have going on my MutliSite WP 3.0. Is this possible?
The plugins folder is shared. You can install one copy of the plugin and activate it on three blogs and not the others. If you don;t want the others to be aware of the plugin's existence... you'll have to use another plugin to exclude it. http://wordpress.org/extend/plugins/restrict-multisite-plugins/ or http://wordpress.org/extend/plugins/exclude-plugins/
Installing One Plugin on a Few Blogs on a MultiSite
wordpress
My Question: Is it possible to add custom dashboard widgets in the right hand column instead of only on the left hands side? I use <code> wp_add_dashboard_plugin( $widget_id, $widget_name, $callback, $control_callback = null ) </code> to add the plugin code, but it doesn't have any options to allow you to set the position. Any suggestions? My Comments: The Version 2.8 of WordPress suggests that it's possible, but I can't see anything in the code (/wp-admin/includes/dashboard.php) that is related to this. It seems only to add the dashboard plugin if its name is in the <code> $side_widgets </code> array, the contents of which are: <code> array('dashboard_quick_press', 'dashboard_recent_drafts', 'dashboard_primary', 'dashboard_secondary'); </code> My thoughts are that I'd have to directly modify <code> $wp_meta_boxes['dashboard'] </code> - but I'm not sure of the consequences of this.
You're right - it doesn't. Neither does the <code> wp_add_dashboard_widget </code> function. So just use the generic <code> add_meta_box </code> and indicate dashboard and placement: <code> add_action( 'wp_dashboard_setup', 'my_dashboard_setup_function' ); function my_dashboard_setup_function() { add_meta_box( 'my_dashboard_widget', 'My Widget Name', 'my_dashboard_widget_function', 'dashboard', 'side', 'high' ); } function my_dashboard_widget_function() { // widget content goes here } </code>
How to position custom dashboard widgets on side column
wordpress
Is it safe to use <code> $wpdb-> insert_id; </code> to find the <code> id </code> of a last updated <code> row id </code> just after an update? ex: <code> $sql = $wpdb-&gt;insert($table_name, $arrayWithDataToInsert, array('%s','%s')); $results['new_created_id'] = $wpdb-&gt;insert_id; </code> or am I running into the possibility that I will catch the id of another row that was inserted immediatly after mine? Thanks!
At a higher level, there truly isn't any means to know if the php/db connector will return the correct id by relying on $wpdb-> insert_id. The only way to be 100% sure is to have add a key you know will be unique (and indexed as such); you can then retrieve the id by querying the table against that unique key. The reason I write this is, if a trigger function adds rows from within the DB, or more importantly if a plugin hooks in wpdb in a such a way that it messes around with inserts alongside the one you're doing (e.g. for logging), you're not safe. With that in mind, hardly anyone in the WP community (and most other communities, for that matter) has the slightest idea of what a DB can do, and treats the thing as if it's a bunch of huge arrays. So you're very safe to rely on it in practice.
Safe way to find last inserted id in a table?
wordpress
Please help me understand how to make Multicheck type for metabox. Search for all internet and nothing. Thanks. UPDATE @Jan I have a headache from this function. I dont know whats wrong.I'm trying your method but nothing, then I'm trying get_posts but with this method I have too many troubles. With your method I get this error before content: <code> Warning: urldecode() expects parameter 1 to be string, array given in Z:\home\mysite.net\www\wp-includes\query.php on line 1878 </code> Here is my code: <code> &lt;?php $catids = get_post_meta($post-&gt;ID,'_mtb_multicheck',false); $limit = 10; query_posts( array('posts_per_page' =&gt; $limit, 'cat' =&gt; $catids, 'paged' =&gt; get_query_var('paged') ) ); ?&gt; &lt;?php if (have_posts()) : ?&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;!-- Content--&gt; &lt;?php endwhile; ?&gt; &lt;?php pagination(); ?&gt; &lt;?php else : ?&gt; &lt;!--Error message here--&gt; &lt;?php endif; ?&gt; </code> I want to know what my vatiables return. Make this: <code> query_posts( array('posts_per_page' =&gt; $limit, 'cat' =&gt; print_r($catids), 'paged' =&gt; get_query_var('paged') ) ); </code> and get this on my page: <code> Array ( [0] =&gt; 5 [1] =&gt; 5 [2] =&gt; 3 ) </code> I think it's my query_posts printed, not $catids. It's a big, big trouble. I feel myself like a nerd. Please help me.
The post metadata can store multiple values either as distinct entries in the <code> postmeta </code> table, or as one entry with the value as a serialized PHP array. The serialization may require less code, but the distinct entries allow faster querying later ("give me all posts that have at least option A of the multicheck checked"). I took the code you linked to and made the following changes to allow a "multicheck": <code> // in show(): // Line 254: replace it by: $meta = get_post_meta($post-&gt;ID, $field['id'], 'multicheck' != $field['type'] /* If multicheck this can be multiple values */); // Add the following to the switch: case 'multicheck': foreach ( $field['options'] as $value =&gt; $name ) { // Append `[]` to the name to get multiple values // Use in_array() to check whether the current option should be checked echo '&lt;input type="checkbox" name="', $field['id'], '[]" id="', $field['id'], '" value="', $value, '"', in_array( $value, $meta ) ? ' checked="checked"' : '', ' /&gt; ', $name, '&lt;br/&gt;'; } break; // In save(): // Line 358: replace it by: $old = get_post_meta($post_id, $name, 'multicheck' != $field['type'] /* If multicheck this can be multiple values */); // Lines 409-413: Wrap them in an else-clause, and prepend them by: if ( 'multicheck' == $field['type'] ) { // Do the saving in two steps: first get everything we don't have yet // Then get everything we should not have anymore if ( empty( $new ) ) { $new = array(); } $aNewToAdd = array_diff( $new, $old ); $aOldToDelete = array_diff( $old, $new ); foreach ( $aNewToAdd as $newToAdd ) { add_post_meta( $post_id, $name, $newToAdd, false ); } foreach ( $aOldToDelete as $oldToDelete ) { delete_post_meta( $post_id, $name, $oldToDelete ); } } else { // The original lines 409-413 } </code> Two extra changes to prevent PHP warnings when <code> WP_DEBUG </code> is enabled: <code> // Line 337: if ( ! isset( $_POST['wp_meta_box_nonce'] ) || !wp_verify_nonce($_POST['wp_meta_box_nonce'], basename(__FILE__))) { // Line 359: $new = isset( $_POST[$field['id']] ) ? $_POST[$field['id']] : null; </code> With these changes, you can use a "multicheck" by defining it like this: <code> array( 'name' =&gt; 'Multicheck', 'id' =&gt; $prefix . 'multicheck', 'type' =&gt; 'multicheck', 'options' =&gt; array( 'a' =&gt; 'Apple', 'b' =&gt; 'Banana', 'c' =&gt; 'Cherry', ), ) </code>
How to make multicheck for post/page meta box
wordpress
I've got a custom loop that I'm using to display some Real Estate listings that will be available within 60 days. I'm calling it with the following function: <code> &lt;?php $sixtydays = date('Y/m/d', strtotime('+60 days')); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $query = new PostsOrderedByMetaQuery(array( 'post_type' =&gt; array('post', 'real-estate'), 'meta_key' =&gt; 'Time Available', 'meta_compare' =&gt; '&lt;=', 'meta_value' =&gt; $sixtydays, 'paged' =&gt; $paged, 'orderby_meta_key' =&gt; 'Price', 'orderby_order' =&gt; 'ASC' )); ?&gt; &lt;?php while ($query-&gt;have_posts()) : $query-&gt;the_post(); ?&gt; </code> While the loop works great, I can't get it to paginate. It shows the first 10 (my default) posts but doesn't show the pagination. The only way to display all posts is to show them on one page by adding <code> 'posts_per_page' =&gt; -1, </code> I have similar loops on other pages that have no problem paginating. The only difference with this one is that there are two meta keys that are filtering the posts. I'm using WP Page Navi for this and the rest of my pages. I'm closing the loop and adding the pagination using the following code: <code> &lt;?php endwhile; // End the loop. Whew. ?&gt; &lt;?php wp_pagenavi(); ?&gt; &lt;?php wp_reset_query(); ?&gt; </code> How can I go about fixing this?
I've run into this problem with PageNavi before. My solution is to hijack the $wp_query variable temporarily and then reassign it after closing the loop. An exmaple: <code> &lt;?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args=array( 'post_type'=&gt;'post', 'cat' =&gt; 6, 'posts_per_page' =&gt; 5, 'paged'=&gt;$paged ); $temp = $wp_query; $wp_query= null; $wp_query = new WP_Query($args); /* PageNavi at Top */ if (function_exists('wp_pagenavi')){wp_pagenavi();} if ( $wp_query-&gt;have_posts() ) : while ( $wp_query-&gt;have_posts() ) : $wp_query-&gt;the_post(); /* DO STUFF IN THE LOOP */ endwhile; endif; /* PageNavi at Bottom */ if (function_exists('wp_pagenavi')){wp_pagenavi();} $wp_query = null; $wp_query = $temp; wp_reset_query(); ?&gt; </code> The last step is to reassign the $wp_query variable to what is was originally and then reset the query back to start. * Edit: *Fixed php tag. Good eye sniper.
Pagination not working with custom loop
wordpress
I added a filter to append a parameter onto the URL when navigating in categories. This is used to sort posts by their votes when browsing a category only if a <code> sort </code> parameter is set. For instance when you click view all posts with most votes, posts with high votes are displayed. From there you can view most voted posts by category by appending a <code> sort=most_voted </code> or <code> sort=doleast_voted </code> to the URL with <code> cat=? </code> . <code> add_filter( 'category_link','append_parameter', 10, 2 ); function append_parameter( $link, $query ) { $my_parameter = $query-&gt;query_vars['sort']; //get sort value if ( isset($my_parameter) ) { //if browsing posts by votes $link = add_query_arg( 'sort', $my_parameter, $link ); } return $link; } </code> I can't figure out why the sort parameter isn't appended to the URL. This works however without the if statements and a value instead of the <code> $my_parameter </code> in the add_query_arg. EDIT: New working code <code> add_filter( 'category_link','append_parameter', 10, 2 ); function append_parameter( $link, $my_parameter ) { $my_parameter = $_GET['sort']; //get sort value if ( isset($my_parameter) ) { $link = add_query_arg( 'sort', $my_parameter, $link ); } return $link; } </code>
If you take a look where the <code> category_link </code> hook is defined in category-template.php you'll see this particular hook passes on two variables. The second variable is the category ID, but your callback function treats that second incoming variable as a query object. Simply put, you're looking for a <code> query_vars </code> property/key that does not and cannot exist, because the incoming variable is not a query object.
add_query_arg not working
wordpress
What do you guys use for A/B testing with WordPress? Knowing that WordPress has plugins for everything, I went looking for A/B testing plugin and didn't find any. It also looks like http://optimizely.com or similar solution may work together with WorpdPress. But I would much rather prefer managing everything in a single app. Any ideas/suggestions?
This is not a straight WordPress solution but I would recommend a/b testing feature found in the Google website optimizer. http://www.google.com/websiteoptimizer/b/index.html . It works with your analytics account. You just need to create two (or more) pages in WordPress.
Best practices for A/B testing?
wordpress
I'm writing (rewriting) my plugin to use <code> wp_enqueue_script('jquery'); wp_enqueue_script('jquery-ui-dialog'); </code> Which is great! But to use the dialog I need to load a jquery style sheet with wp_enqueue_style, is there a way to load a built-in style, similar to the way you can load the built in scripts (as seen above)? Or do I need to make a call to an external resource?
I'm a little confused by your question, can you not simply use wp_enqueue_style, which you actually wrote into this threads heading(not sure if you know the function exists or not). <code> wp_enqueue_style </code> works in the same way as the <code> wp_enqueue_script </code> counterpart, but of course as you'd expect, enqueues stylesheets.. Here's a list of the enqueues i was able to find in WordPress core(those you can use without needing to register them or declare paths to). <code> wp_enqueue_style( 'global' ); wp_enqueue_style( 'wp-admin' ); wp_enqueue_style( 'colors' ); wp_enqueue_style( 'media' ); wp_enqueue_style( 'ie' ); wp_enqueue_style( 'imgareaselect' ); wp_enqueue_style( 'imgareaselect' ); wp_enqueue_style( 'plugin-install' ); wp_enqueue_style( 'press-this' ); wp_enqueue_style( 'press-this-ie'); wp_enqueue_style( 'colors' ); wp_enqueue_style( 'theme-install' ); wp_enqueue_style( 'thickbox' ); </code> Beyond those above you'll need to declare the path inside the enqueue(because it's not a registered style), as you would for scripts.. <code> wp_enqueue_style( 'myPluginStylesheet', WP_PLUGIN_URL . '/myPlugin/stylesheet.css' ); </code> Or register the style.. <code> wp_register_style( 'myPluginStylesheet', WP_PLUGIN_URL . '/myPlugin/stylesheet.css' ); </code> ..then call it when needed.. <code> wp_enqueue_style( 'myPluginStylesheet' ); </code> If you're using this on one plugin page, the registration part is a little pointless, and it's probably easier to declare the path straight inside the enqueue.. (you really only need register a script or style if it's going to be called in more than one place). Hope that's the information you're looking for... ;)
wp_enqueue_style built in styles
wordpress
I am writing a plugin that depends on modal dialogs for screen space. Right now I am using jQuery to create the dialogs, but I want a way that integrates better into the admin theme. Obviously WP has to have some sort of native dialog system (it's used for uploads). How do I access it?
The WordPress admin area uses Thickbox , which is still a jQuery plugin (jQuery is used all over the admin area). You need to enqueue the script and style ( <code> add_thickbox() </code> does this for you), and then all links that have class <code> thickbox </code> will be converted. You need to add some URL parameters too, for example the image upload link looks like this: <code> media-upload.php?post_id=735&amp;type=image&amp;TB_iframe=1&amp;width=640&amp;height=285 </code> . <code> post_id </code> and <code> type </code> are WordPress-specific, but <code> TB_iframe </code> , <code> width </code> and <code> height </code> are needed for Thickbox, and you should use them in your own links too.
Creating a modal dialog without jQuery
wordpress
i need some help how can i display custom taxonomies on selected pages? i mean i have 3 custom taxonomies location,duration &amp; courses i have created three pages where i want to display the terms of these custom taxonomies, i have displayed it on my posts by using function <code> &lt;?php echo do_shortcode("[terms]"); ?&gt; </code> but same thing i want to make display on my pages also, how can i do that??????
If you want to display a list of all terms in a taxonomy, you can call <code> wp_list_categories() </code> and pass the <code> taxonomy </code> argument to get anything other than the categories: <code> wp_list_categories( array( 'taxonomy' =&gt; 'your-taxonomy' ) ); </code> If you want to use a shortcode for this, so you can use it in your post content, use <code> add_shortcode() </code> . This untested example code allows you to use <code> [taxonomy_terms] </code> or <code> [taxonomy_terms taxonomy=my-taxonomy] </code> in your content: <code> add_shortcode( 'taxonomy_terms', 'wpse4668_taxonomies' ); function wpse4668_taxonomies( $atts ) { // Sanitize our input $atts = shortcode_atts( array( 'taxonomy' =&gt; 'your-default-taxonomy', ), $atts ); // Don't echo the output, just return it $atts['echo'] = 0; return wp_list_categories( $atts ); } </code>
custom taxonomies on pages
wordpress
I hired a sysadmin to set up a VPS server for me and, unfortunately, it looks like things were not set up correctly. When trying to install and update plugins, I run into permissions errors all the time. WP Super Cache is the main issue as it causing my readers to run into 502 errors. Currently, my site does not load pagination (no Page 2, Page 3, etc..). 12/1 Update: The apache server has restarted itself multiple times today and in the past 3 hours since my request to the host provider, all I've got so far is that they are monitoring it. And it has restarted since they began monitoring too... The sysadmin that set up the server mentioned that in order for it to work properly under DSO mode, wp-admin, wp-content and wp-plugins folders would need to be changed to 777 permissions. The only problem is that I still couldn't get a 3.0.2 upgrade to work under those settings today (504 timeout nginx error this time) so I'm still concerned about running it that way for many reasons. I've been told that if I run under PHP mode though (think that's right?), that I will hog up more RAM with queries, etc and I'm already at 60% usage in DSO mode. This doesn't make any sense to me because my blog ran a little slow but still ok without any downtime on shared hosting. I'm now on a very reputable VPS w/ 512MB ram and my site only gets 10-12k pageviews a day. The host said that they have tweaked the config to optimize ram so I don't think anything is set incorrectly. Still trying to figure out what is going on here. Developing.....
It's a very loaded question, I'll try my best here, keep in mind it's 4am, so I'm just giving you highlights, not detailed explanations. Linux I'm assuming you're using a recent version of Ubuntu Change the default SSH port from 22, to something else (/etc/ssh/sshd_config). Either enable AllowGroups or AllowUser in the sshd_config, Install fail2ban (apt-get install fail2ban) Install apache2, php5, and mysql-server Edit /etc/apache2/conf.d/security.conf and make appropriate changes for a production server. Disable the slow query log in MySQL (you don't want this on in production, especially on a VPS) Configure your system timezone (dpkg-reconfigure tzdata) Make sure your php.ini reflects the same time zone Add a new virtualhost in /etc/apache2/sites-available/ (leave the default one alone) Enable this virtual host by: a2ensite nameofnewvhostfile Enable mod-rewrite (a2enmod rewrite) Restart apache2 /etc/init.d/apache2 restart You can do some other things as well, like install Shorewall, or UFW for better firewall management, install Nginx as a reverse proxy to apache, tweaking the query cache, but this really depends on a whole bunch of other things, and you should tweak mysql settings after being in production mode for a few days.
What are best practices for configuring a server for Wordpress sites?
wordpress
I've seen some tutorials showing how to create custom post types - the process seems straightforward enough. The issue I have with this is that the custom type information is part of the theme, and not handled by the WP core. So if the theme is switched for another, they custom type information is lost, and must be ported to the new theme. I've seen some plugins that handle the custom types for you. It seems to me that this is kept separate from the theme, and would thus be more portable, provided the plugin is kept activated. There would of course be a need for the theme to template and style the custom type, but it wouldn't have to maintain the type itself. Is it worthwhile to use a plugin for this purpose?
Hi @Grant Palin: The <code> register_post_type() </code> function is really agnostic to theme or plugin ; you can use it in an <code> 'init' </code> hook in either place, it really depends on what you are trying to accomplish. For example, if I'm setting up a custom site for a specific client I'll probably just register the post types in the theme . On the other hand, if I'm trying to create a reusable custom post type ("Event" might be an example) then I might register the Event post type in an Event-specific plugin . However be aware that unless your post type is similar to a standard Post you'll likely still need specific theme support for it anyway . And with the pending release of Post Formats in v3.1, there really aren't many good reasons to define custom post types that are similar in use-case to a standard Post so you really have six of one, half dozen of the other. Also, I frequently put custom post type registrations for a new site in an include file called by the theme's <code> functions.php </code> file unless and until I get to the point of a fully generic feature in which case I'll move to a plugin (most of my clients have me writing reusable functionality that they then sell to their clients, and most of my work is related to custom post types. I rarely do work on code that will only run on a single website FWIW, JMMV.) One thing I will say, I would avoid using plugins that provide a UI for creating custom post types and custom taxonomies like Custom Post Type UI and similar except for: When you want to do some proof-of-concept prototyping or When you want to empower an end-user that you don't want to give FTP access. Why? Because these plugins all store their custom post type and taxonomy registrations in the database which makes it very difficult to version control them and also makes it much harder to launch a new version of the site from existing source code. Those UI plugins are really only best used when learning, tinkering, exploring, and/or doing a quick and dirty "what-if" / "proof-of-concept" . (Of course the UI plugins are wonderful those those uses.) What's more, the code to register a custom post type and a custom taxonomy is so easy to learn that there's really no reason for a WordPress professional to develop and deliver a system that doesn't hardcode its custom post types and custom taxonomies into PHP code, either in the theme or in a plugin, your choice. Matter of fact, I'm about to extract the CPT-UI plugin from a client project and replace with hardcoded PHP registrations this coming week. Hope this helps. (If not, ask for more.)
Use a plugin to handle custom post types?
wordpress
I currently have some custom post types "shops" (actually more like pages than posts) and a custom taxonomy "products" linked to those post types. I'm attempting to create a form (via shortcode) that allows the user to select one (or potentially more in the future) products that when submitted, shows a page listing shops (title and other post meta) related to the chosen product(s). I have the form, just not sure what the best way is to handle the submission and subsequent display page. I noticed the codex page for add_rewrite_endpoint() states This can be used for all sorts of things: ajax handler form submission handler alternative notification handler however there's no further information about how to achieve this. Any pointers on handling form submissions would be great. Thanks. Edit : Further on this, I want the form submission page to redirect to a nice URL representing the selected term. For example User selects product "books", hits submit Form submits to handling URL or some kind of hook catches the submission The browser is redirected to "shops/books" Something displays the "shop" pages tagged with "books" products My question can be broken down to... What URL do I use in the form's <code> action </code> attribute? Is this even necessary? Where do I handle the form submission? Do I create a specific file or can I register some kind of action hook. Keep in mind that I'm wanting to send a <code> Location </code> header to redirect to another URL so this needs to happen prior to any output sent to the browser. How do I configure something to accept the "shops/%product%" request and show results accordingly Sorry for the long-winded query but I'm struggling to get to grips with the Wordpress API and documentation.
Hi @Phil Brown: This is actually really easy (at least #1 and #2 are): You can use any URL that loads a theme template file. For example, you could create a WordPress " Page " and in your Page Template you can use PHP's <code> $_POST </code> array to capture your <code> &lt;form&gt; </code> values. Unless you've got a good reason, you really don't need to do a redirect. You can, but I don't see that you need to and it just makes your task more complicated. If you really want to <a href="stackexchange-url this answer will show you how. I'm confused by what you are trying to accomplish with your " <code> shops/%product% </code> " URL. At first blush your choice of "shops" for a custom post type and "products" for a taxonomy seems wrong to me (unless you are trying to represent many different shops; i.e. if your site is trying to be a marketplace for many different merchants. Is that the case? Even then, I still don't see why you'd use a taxonomy for your products.) So it seems to me you'd instead want to create a custom post type of "Product" *(though I'm not sure about the taxonomy)*, and then you'll get URLs of the type <code> products/%product% </code> when you register you custom post type. Or maybe I misunderstand what you are trying to do for #3?
Create page to handle form submission
wordpress
(Please note this is not a wordpress.org question) Hi everyone, I want every new post on my blog automatically broadcasted on twitter - the same thing is beautifully supproted with facebook. But I cannot find how to activate it on my blog at namgivu.wordpress.com. Please help if you know how to. Thank you!
Hi @Nam Gi VU: In general, this is not really a WordPress question. I'll answer it because I tend to be lenient about how related questions need to be but there's a good change another moderator will close the question and if they do I'll agree. Basically since WordPress.com does not provide this feature you need to use a 3rd party service that will read your RSS feed and send tweets to your Twitter account: TwitterFeed Auto Tweet Feedburner Socialize ( Also ) -Mike P.S. One more thing. I do not recommend auto-tweeting blog posts. Most Twitter users (myself included) will unfollow people who auto-tweet if they recognize them doing it. I want to hear from the person, not something they've set up to run automatically. FWIW.
How to intergrate wordpress.com with twitter like the way it is with facebook?
wordpress
I'm using the <code> comments_popup_link() </code> function to show the number of comments for each post in a loop. <code> &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;?php if ( get_post_meta($post-&gt;ID, 'thumb_value', true) ) : ?&gt; //something &lt;?php else: ?&gt; //something else &lt;?php endif; ?&gt; &lt;h2&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" title="&lt;?php the_title(); ?&gt;" rel="bookmark"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;?php the_content(__('Read more'));?&gt; &lt;div class="post-meta"&gt; &lt;?php the_time('F j, Y'); ?&gt; &lt;p&gt;Category: &lt;?php the_category(', '); ?&gt;&lt;/p&gt; &lt;p&gt;&lt;?php the_tags(); ?&gt;&lt;/p&gt; &lt;p&gt;&lt;?php comments_popup_link('Post Comment', '1 Comment', '% Comments'); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php $wpdb-&gt;show_errors(); $wpdb-&gt;print_error(); ?&gt; &lt;?php else: ?&gt; &lt;p&gt;&lt;strong&gt;There has been an error.&lt;/strong&gt;&lt;/p&gt; &lt;?php $wpdb-&gt;show_errors(); ?&gt; &lt;?php $wpdb-&gt;print_error(); ?&gt; &lt;/p&gt; &lt;?php endif; ?&gt; </code> Everything displays fine but I get WordPress database error: [] SELECT * FROM wp_comments WHERE comment_post_ID = 216 AND comment_approved = '1' ORDER BY comment_date_gmt DESC I'm just curios why I get that..
Your template code includes <code> $wpdb-&gt;print_error() </code> . This function prints the last database error between <code> [ </code> and <code> ] </code> brackets, and the executed SQL code. But if there is no error, you just see the empty brackets and the SQL. <code> $wpdb-&gt;show_errors() </code> is used to enable displaying of database errors . If you want to see all database errors, you can just call this function somewhere higher in your code (in your <code> functions.php </code> , or in a plugin). You probably only want to do this when you are in debug mode, so it would look like this: <code> if ( WP_DEBUG ) { $wpdb-&gt;show_errors(); } </code>
WP database error for comments_popup_link()
wordpress
After reviewing plugins that deal with user roles and capabilities I concluded that I might be better off just hardcoding my settings into my functions.php file. This actually worked out well for me in end effect but I kept running into an issues while I was finalizing the code. As I am sure many of you know (and I ended up finding out the hard way) any new capabilities added through code to an existing role which has been assigned to a user won't work. Rather it seems the role and associating capabilities are written into the database the first time the new role is assigned to a user. If I am incorrect with this assumption please let me know. In any case... I have been getting frustrated with dealing with things manually and although I don't like the idea of plugins, this specific situations has be believing a GUI might actually work very well. What I am looking for is a plugin or some non bloated code which essentially is just capable of reading the roles and their associating capabilities from the default wordpress database and outputs these values into a checkbox list. So, basically the ability to just select a role which in turn displays every default capability from wordpress as well as any custom capability which is assigned to any user... Then just a checkbox next to every capability assigned to that role. The admin could update the values by checking/unchecking applicable capabilities and one should have the ability to just enter a new capability by pasting the capabilities name into a text field. My logic here is that if this existed then your NOT adding ANY additional custom code to the database or anything that requires more resources. The key benefit here is that you finally have a simple way to deal with updating roles. What I am not sure about is if this same logic would apply to being able to manually change the capabilities for individual users... If anyone also knows the answer to this question pleaseclet me know.
The plugin Members is your solution, clean code for read, change and create roles and capabilities; easy and fast. No custom tables and normaly WordPress standard.
Roles & capabilities GUI that does not create separate table
wordpress
I've created a custom taxonomy "foo" with rewrite slug "foo" and query_var "foo". Say for example, I also have terms "bar" and "baz" in the "foo" taxonomy. At the moment, permalinks like <code> /foo/bar </code> and <code> /foo/baz </code> work fine, using my <code> taxonomy-foo.php </code> template. What I'd like to do is be able to hit <code> /foo </code> and retrieve all posts with a link to any "foo" taxonomy. Currently, this URL shows a 404. How can I achieve this? If I can somehow hook into the rewrite code and set a default term value ( <code> 'all' </code> for example) if missing, that might be a way to move forward but I'm not sure if this is possible. I'd preferably like to use the <code> taxonomy-foo.php </code> template file for the "catch all", dealing with the logic of showing posts from one or all terms in there. Cheers Edit : I've figured how to catch a request for <code> /foo </code> and set some defaults using <code> add_filter('request', ...) </code> though I had to use an existing term as using anything else generates a 404. Is there any way to avoid this limitation?
What you want is an index page for custom taxonomies . There is a ticket for that , but it's not clear what is the most obvious thing to show on this page: 1) a list of all posts attached to any term of that taxonomy, or 2) a list of all terms of this taxonomy? Remember that <code> category </code> is also a taxonomy, but it is assumed that all posts fall under at least one category (with <code> Uncategorized </code> as the default). In that case, option 1 would be the same as the regular post query, and option 2 might make more sense. The related issue of an index page for custom post types will be fixed in the upcoming 3.1 release . I tried something myself, and instead of interfering with the <code> request </code> hook, I think the better way to do this is adding a new rewrite rule and modifying the query: <code> add_action( 'init', 'wpse4663_init' ); function wpse4663_init() { // The custom taxonomy rewrite rules end up at the top of the rewrite array register_taxonomy( 'wpse4663', array( 'post' ), array( 'label' =&gt; 'WPSE 4663', ) ); // So there probably is no danger in adding this specific rewrite rule there too // We re-use the existing `taxonomy` query var, but with no `term` // We clean this up in `parse_query`, otherwise get_posts() complains // You could make this work for all taxonomies (categories, tags, ...) by doing this repeatedly // But then it's probably better to do this in the `rewrite_rules_array` filter add_rewrite_rule( 'wpse4663(/page/([0-9]+))?/?$', 'index.php?taxonomy=wpse4663&amp;paged=$matches[2]', 'top' ); } add_filter( 'parse_query', 'wpse4663_parse_query' ); function wpse4663_parse_query( &amp;$wp_query ) { // is_tax is only true if both a taxonomy and a term are set, otherwise is_home is true // But we don't want that: is_tax and is_archive should be true, is_home should be false if ( !$wp_query-&gt;is_tax &amp;&amp; $taxonomy_query = $wp_query-&gt;get( 'taxonomy' ) ) { foreach ( $GLOBALS['wp_taxonomies'] as $taxonomy =&gt; $t ) { if ( $t-&gt;query_var &amp;&amp; $taxonomy_query == $t-&gt;query_var ) { // Make sure the conditional tags work, so the right template is loaded $wp_query-&gt;is_tax = true; $wp_query-&gt;is_archive = true; $wp_query-&gt;is_home = false; // Make is_tax($taxonomy) work $wp_query-&gt;queried_object = $t; $wp_query-&gt;queried_object-&gt;taxonomy = $taxonomy; // If term is null, get_terms (query.php line 2043) will get all terms of this taxonomy $wp_query-&gt;set( 'term', null ); break; } } } } </code>
Custom taxonomy listing page when no term set (all terms)
wordpress
I've never used version control before, but I'm starting to work more collaboratively on WordPress plugins and themes and I think it would be a good idea to have a record of versions and updates. WordPress seems to favour SVN, but Git seems to be the new, cooler alternative. Which version control do you use currently? And which system would you choose today if you were starting out in WP theme and plugin dev?
I use Git for all my projects since it lets me work offline and that happens fairly often for me. Git can interface with SVN if you'd still like to use Git then push your plugins to WordPress.org. http://www.nkuttler.de/post/using-git-for-wordpress-development/ http://hakre.wordpress.com/2010/09/28/git-rocks/
Should I use SVN or Git?
wordpress
i'm looking around for a solution since weeks and can't make anything work yet. the problem is that my server is running debian/lenny and it's not supporting the bundled gd_lib which i need for thumbnailing/cropping stuff. but i could make use of imagick or imagemagick (package vs plugin). my question is: is there any way to replace the gd functions in media.php with the ones from imagick? AND is there a smarter way then modiyfing the media.php to do so? thanks
Yes! Orangelab has built a plugin which can replace WP's use of GD with Imagemagick (provided it's already installed on your server - it's not included) for creation of all image sizes and thumbs, and even regenerate existing images too! For anyone who cares about image fidelity, this is huge deal, as GD does not handle color profile preservation or conversion (resulting in horrible desaturation), and also ends up softening any image it converts... http://wordpress.org/extend/plugins/imagemagick-engine/
is it possible to replace the use of gd_lib with imagick or ImageMagick?
wordpress
I have a post having different links. I have to show number of clicks on each link. Is there any link to show number of clicks on the link?
WP-Click-Track http://wordpress.org/extend/plugins/wp-click-track/ The click tracker works in 2 modes: Scans posts and rewrites them to include a tracking element Enables users to create stand alone trackable links that can be embedded in posts or offsite.
Is there any plugin to show number of clicks on the link?
wordpress
I am currently building a plugin and it doesn't know when a user is logged in. <code> global $current_user; echo $current_user-&gt;ID; </code> It works when embedded on a template but not on a plugin? I have a custom database that depends on user_id, whenever I insert a record, user_id field always has a zero value while others have the correct one.
The $current_user global isn't setup until right before the 'init' action is called. So any code using it shouldn't be fired until that action or later. I would also suggest using the get_current_user_id() method instead of getting the global directly.
Will a plugin able to know is_user_logged_in?
wordpress
I'm using the Multisite functionality of WordPress 3.0, and I have a network of sites built where I display one random post from one of the subsites on the main site's front page. I accomplish this, in part, by using the <code> switch_to_blog </code> function from the old WPMU function list. Up until yesterday I could call a function that called <code> switch_to_blog </code> , created an array, added the blog's name, the post details, the post thumbnail, etc. to the array, and then used <code> restore_current_blog </code> to jump back to the main blog's context. Then I used that array to echo out the things I needed for that post I grabbed. It worked fine. All of a sudden, when I call <code> switch_to_blog </code> and then from within that block I call <code> bloginfo() </code> just to test it, it still echoes the name of the top level blog, and NOT the switched to blog. Is that function completely deprecated and unworkable due to random bugs? Anyone have any insight or ideas to get around it, or do I need to write a custom <code> $wpdb-&gt;get_results(); </code> query to get around this? Thanks!
It appears that switch_to_blog might be too unpredictable to rely on for major site design. Here's my first attempt at a SQL-based solution. <code> function get_intro_post($blogid, $thumb_size='') { global $wpdb, $post; // Get the system defined table prefix $prefix = $wpdb-&gt;prefix; // Create a full table prefix by combining the system prefix with the blogid $tbl = $prefix . $blogid; // First query selects posts with the 'Introduction' category $sql = "SELECT `ID` FROM {$tbl}_posts as p"; $sql .= " JOIN {$tbl}_term_relationships tr ON p.ID = tr.object_id"; $sql .= " JOIN {$tbl}_terms t ON tr.term_taxonomy_id = t.term_id"; $sql .= " WHERE t.name = 'Introduction'"; // Only want/expect one result row, so use get_row() $intro = $wpdb-&gt;get_row($sql); $postid = $intro-&gt;ID; // Second query joins the postmeta table to itself so that I can find // the row whose post_id matches the _thumbnail_id, found in meta_value, // for the post whose post_id matches the one I found in the previous query. $sql = "SELECT p2.meta_key, p2.meta_value FROM `{$tbl}_postmeta` p1"; $sql .= " JOIN `{$tbl}_postmeta` p2 ON p1.meta_value = p2.post_id"; $sql .= " WHERE p1.meta_key = '_thumbnail_id'"; $sql .= " AND p1.post_id = '{$postid}'"; $sql .= " LIMIT 0 , 30"; // Expecting 2 result rows, so use get_results() $thumb_meta = $wpdb-&gt;get_results($sql); // Set $src to FALSE as the default $src = FALSE; // Make sure the query returned results if(!empty($thumb_meta)) { foreach($thumb_meta as $row) { // We just want to find the row where meta_key is the attached file // and then set our $src var to that value, which is the image path if ($row-&gt;meta_key == "_wp_attached_file") $src = $row-&gt;meta_value; } } // If we found an image path above, I'll append the rest of the path to the front if($src) { $src = "/wp-content/blogs.dir/{$blogid}/files/{$src}"; } // Handy core function to grab the blogname of another network's blog, by ID $blogname = get_blog_details( $blogid )-&gt;blogname; // Make an associative array holding the elements we need, // some pulled from the global $post context $p = array( 'title' =&gt; get_the_title(), 'content' =&gt; get_the_content(), 'excerpt' =&gt; get_the_excerpt(), 'permalink' =&gt; get_permalink(), 'blogname' =&gt; $blogname, 'thumbnail' =&gt; $src ); // Return an object with the post details mentioned above return (object) $p; } </code>
Why would switch_to_blog stop working?
wordpress
I created an author's page using: <code> &lt;?php if(isset($_GET['author_name'])) : $curauth = get_userdatabylogin($author_name); else : $curauth = get_userdata(intval($author)); endif; ?&gt; </code> and then a standard loop, which displays all posts' titles published by that author. I'm trying to separate the display of the posts, according to the category they belong to (1, 2 or 3), so I tried using <code> &lt;?php query_posts('cat=1'); ?&gt; </code> but then all my blog posts are displayed, not just that author's. Something is certainly wrong. I know I have to use a custom query when there is more than one loop per post, but given that just using a single standard query, with the "cat" filter isn't working, I'm a bit lost.
If you're using an author template there's absolutely no need to setup(set) the author query parameters, they'll be setup ready in the query object present on the author page.. You could additionally avoid the need to create numerous queries(one per category currently), by iterating over the query you have, extracting the categories, and storing post IDs associated with given categories inside an array. First iteration you use to build the array of IDs divided by category name/ID(whatever you like), then rewind the query, iterate over the posts, continuing(skipping) results that don't match the first category in your newly built array of category IDs(or names). Again you follow by rewinding the loop, then iterating over it again for each category you have in the new array, continuing(skipping) posts when they don't match the current category iteration. It's not something that will really make much sense until you see it, and gets a little more complex if you categorize your posts into multiple categories(where the categories can intersect across posts), but it will work(without any additional queries) for the current page(it obviously won't sort the full result set, so whilst a given page will sort, that overall sort won't carry across the sum of all pages for the result set). If you think the above method sounds useful and you're not fussed about the aforementioned problem i don't mind providing an example.
Display posts separated by Category in Author's page
wordpress
I created a custom URL parameter for sorting posts by their vote scores. I have a "most voted" link that sends a <code> ?sort=most_voted </code> URL paramater and using a query posts filter I display posts with most votes. If for instance I want to display most voted posts in category 5, I'll need a URL like this <code> ?cat=5&amp;sort=most_votes </code> How do I preserve/attach the <code> sort </code> parameter in the URL when browsing categories (or even by tag name, search, etc)?
You will need to intercept the links generated by WordPress and append the query var onto the relevant URLs. You can do this quite easily with a filter on category URLs with something like... <code> function add_my_query_var( $link ) { $link = add_query_arg( 'sort', 'most_voted', $link ); return $link; } add_filter('category_link','add_my_query_var'); </code> I also spotted this handy list of filters on stackexchange-url ("Mike's post on SO"), it should cover all the possible URLs you'd want to tweak the query vars for... <code> add_filter('page_link','add_my_query_var'); add_filter('post_link','add_my_query_var'); add_filter('term_link','add_my_query_var'); add_filter('tag_link','add_my_query_var'); add_filter('category_link','add_my_query_var'); add_filter('post_type_link','add_my_query_var'); add_filter('attachment_link','add_my_query_var'); add_filter('year_link','add_my_query_var'); add_filter('month_link','add_my_query_var'); add_filter('day_link','add_my_query_var'); add_filter('search_link','add_my_query_var'); add_filter('feed_link','add_my_query_var'); add_filter('post_comments_feed_link','add_my_query_var'); add_filter('author_feed_link','add_my_query_var'); add_filter('category_feed_link','add_my_query_var'); add_filter('taxonomy_feed_link','add_my_query_var'); add_filter('search_feed_link','add_my_query_var'); add_filter('get_edit_tag_link','add_my_query_var'); add_filter('get_edit_post_link','add_my_query_var'); add_filter('get_delete_post_link','add_my_query_var'); add_filter('get_edit_comment_link','add_my_query_var'); add_filter('get_edit_bookmark_link','add_my_query_var'); add_filter('index_rel_link','add_my_query_var'); add_filter('parent_post_rel_link','add_my_query_var'); add_filter('previous_post_rel_link','add_my_query_var'); add_filter('next_post_rel_link','add_my_query_var'); add_filter('start_post_rel_link','add_my_query_var'); add_filter('end_post_rel_link','add_my_query_var'); add_filter('previous_post_link','add_my_query_var'); add_filter('next_post_link','add_my_query_var'); add_filter('get_pagenum_link','add_my_query_var'); add_filter('get_comments_pagenum_link','add_my_query_var'); add_filter('shortcut_link','add_my_query_var'); add_filter('get_shortlink','add_my_query_var'); add_filter('home_url','add_my_query_var'); add_filter('site_url','add_my_query_var'); add_filter('admin_url','add_my_query_var'); add_filter('includes_url','add_my_query_var'); add_filter('content_url','add_my_query_var'); add_filter('plugins_url','add_my_query_var'); add_filter('network_site_url','add_my_query_var'); add_filter('network_home_url','add_my_query_var'); add_filter('network_admin_url','add_my_query_var'); </code> Hope that helps..
Preserve custom URL parameter on more pages
wordpress
I've got a plugin that needs to interogate the post preview (the contents of the rendered page that's presented when the user clicks "Preview Post". To attempt to obtain this input stream into a code variable, I'm using wp_remote_get like so: <code> $response = wp_remote_retrieve_body( wp_remote_get( 'http://localhost/mysite/test-post/?preview=true&amp;preview_id=28&amp;preview_nonce=640bc54ca4')); $post-&gt;post_content = $response; </code> (I'm just replacing the post content with the results of the get for easy previewing during code testing). My problem is that since I'm not passing any authentication parameters in the wp_remote_get, the preview action fails. Is it possible to pass a parameter that authenticates the current user and returns the preview to the script?
Have you checked out the following plugin? http://wordpress.org/extend/plugins/public-post-preview/
How can I call "preview post" from wp_remote_get with authentication?
wordpress
I'm seeing a lot of visits in my Analytics to my home page with the query string "?cat=2-5-results". These pages are getting a lot of traffic. To the best of my knowledge, I'm not using this parameter on my site anywhere. If I google "wordpress ?cat=2-5-results" I find a lot of other sites with the same phantom pages. Anyone know what this means? My site: http://www.barbadospropertylist.com Here are how the pages appear in GA:
It's used (together with the search query) to measure number of results for a search query, it's not supposed to show up in Analytics like this, this could only happen due to people scraping your site and clicking through to the actual URL...
What does ?cat=2-5-results mean at the end of URLs?
wordpress
I'm making my own comment template (stackexchange-url ("like this")) and I need to know how can I get the comment and ping count for the current post, maybe using a fast database query or something like that? Note that I can't use <code> count($comments) </code> or anything like that, because I'm not running the default <code> comments_template() </code> function which gets all the comments from the database. Instead I'm pulling only the newest 10 comments using <code> get_comments() </code> . <code> $post-&gt;comment_count </code> (apparently initialized by get_post ) is close to what I'm looking for, but it counts both comments and pings :(
you can use this custom function in the functions.php of the theme: <code> /** * count for trackback, pingback, comment, pings * * embed like this: * fb_comment_type_count('pings'); * fb_comment_type_count('comment'); */ if ( !function_exists('fb_comment_type_count') ) { function fb_get_comment_type_count( $type='all', $zero = false, $one = false, $more = false, $post_id = 0) { global $cjd_comment_count_cache, $id, $post; if ( !$post_id ) $post_id = $post-&gt;ID; if ( !$post_id ) return; if ( !isset($cjd_comment_count_cache[$post_id]) ) { $p = get_post($post_id); $p = array($p); fb_update_comment_type_cache($p); } ; if ( $type == 'pingback' || $type == 'trackback' || $type == 'comment' ) $count = $cjd_comment_count_cache[$post_id][$type]; elseif ( $type == 'pings' ) $count = $cjd_comment_count_cache[$post_id]['pingback'] + $cjd_comment_count_cache[$post_id]['trackback']; else $count = array_sum((array) $cjd_comment_count_cache[$post_id]); return apply_filters('fb_get_comment_type_count', $count); } // comment, trackback, pingback, pings, all function fb_comment_type_count( $type='all', $zero = false, $one = false, $more = false, $post_id = 0 ) { $number = fb_get_comment_type_count( $type, $zero, $one, $more, $post_id ); if ($type == 'all') { $type_string_single = __('Kommentar', FB_BASIS_TEXTDOMAIN); $type_string_plural = __('Kommentare', FB_BASIS_TEXTDOMAIN); } elseif ($type == 'pings') { $type_string_single = __('Ping und Trackback', FB_BASIS_TEXTDOMAIN); $type_string_plural = __('Pings und Trackbacks', FB_BASIS_TEXTDOMAIN); } elseif ($type == 'pingback') { $type_string_single = __('Pingback', FB_BASIS_TEXTDOMAIN); $type_string_plural = __('Pingbacks', FB_BASIS_TEXTDOMAIN); } elseif ($type == 'trackback') { $type_string_single = __('Trackback', FB_BASIS_TEXTDOMAIN); $type_string_plural = __('Trackbacks', FB_BASIS_TEXTDOMAIN); } elseif ($type == 'comment') { $type_string_single = __('Kommentar', FB_BASIS_TEXTDOMAIN); $type_string_plural = __('Kommentare', FB_BASIS_TEXTDOMAIN); } if ( $number &gt; 1 ) $output = str_replace('%', number_format_i18n($number), ( false === $more ) ? __('%', FB_BASIS_TEXTDOMAIN) . ' ' . $type_string_plural : $more); elseif ( $number == 0 ) $output = ( false === $zero ) ? __('Keine', FB_BASIS_TEXTDOMAIN) . ' ' . $type_string_plural : $zero; else // must be one $output = ( false === $one ) ? __('Ein', FB_BASIS_TEXTDOMAIN) . ' ' . $type_string_single : $one; echo apply_filters('fb_comment_type_count', $output, $number); } } </code> this function give you the count of pingback, trackback, comments or all, example: <code> &lt;h2 class="comments"&gt;&lt;?php fb_comment_type_count( 'comment' ); ?&gt;&lt;/h2&gt; </code> you can use the follow parameter for return the counter: comment, trackback, pingback, pings or all
Fastest way to get the comment and ping total count for a post
wordpress
I'm adding voting features to a theme. Visitors can vote posts Up or Down. I created a table for storing number of votes for each post and that works fine. Now I'm trying to sort posts by their votes. I have "voted up" and "voted down" links. For instance, when you click on "voted up" a new parameter <code> sort=up </code> is passed in the URL. In the loop if the parameter exists and is = "up" I want to loop posts with votes up. <code> wpdb-&gt;get_results("SELECT post_id, FROM $wpdb-&gt;votes WHERE up &gt; 5"); </code> This is where I want to use something like <code> query_posts('sort=up') </code> before the loop. My question is, how to I create the custom "sort" parameter?
If you have your data in separate table adding support for it in query is somewhat messy. Basically you will need to filter <code> posts_where </code> and <code> posts_join </code> to modify raw SQL query so that your custom table is joined and checked against your custom values. As per [faster :)] anu's suggestion it would make sense to store values in Custom Fields and use Custom Field Parameters (related to Orderby, but not same thing) in query.
Custom query_posts() parameter
wordpress
Using a WordPress multisite network with Buddypress. In order to modify the top nav bar, I've written a function to replace part of the menu. Calling it thus: <code> add_action('bp_adminbar_menus', 'new_adminbar_blogs_menu', 6); remove_action('bp_adminbar_menus', 'bp_adminbar_blogs_menu', 6); </code> Works perfectly in my functions.php, but when I try to move the above code to the plugin file, the remove_action fails to fire, but the add_action works as expected. As a temporary solution, renaming the function folder to something appearing after Buddypress alphabetically solved the issue.
I am not sure about BuddyPress specifics. In general case remove doesn't work when it is firing before function is actually added to the hook. Between core, plugins, parent and child themes there are a lot of relative combinations of add/remove possible. In such case to make remove fire properly you need to wrap it into function and hook that wrapper function to some point later, after add.
Why doesn't remove_action work in my plugin?
wordpress
Warning: Invalid argument supplied for foreach() in /.../ipn_res.php on line 28 Warning: Invalid argument supplied for foreach() in /.../ipn_cls.php on line 30 From line 28 is a foreach loop: <code> foreach ($paypal_ipn-&gt;paypal_post_vars as $key=&gt;$value) { if (getType($key)=="string") { eval("\$$key=\$value;"); } } </code> From line 30 is also a foreach loop: <code> foreach($this-&gt;paypal_post_vars AS $key =&gt; $value) { if (@get_magic_quotes_gpc()) { $value = stripslashes($value); } $values[] = "$key" . "=" . urlencode($value); } </code> And I think the root cause of the errors is this: <code> //This is located before foreach loop in ipn_res.php require_once("ipn_cls.php"); $paypal_info = $HTTP_POST_VARS; $paypal_ipn = new paypal_ipn($paypal_info); </code> The constructor of class paypal_ipn is passed with a non-array var because nothing has been sent yet that would fill out <code> $HTTP_POST_VARS </code> . Wordpress runs the code which is not the case when not in it. How do I get away from this?
Contact plugin's developer and ask him to fix?.. But I guess that is probably not an option if plugin is broken badly and remains that way. For a quick band-aid try this right after object is created, to handle case of constructor not setting up field properly: <code> if( !isset( $paypal_ipn-&gt;paypal_post_vars ) ) $paypal_ipn-&gt;paypal_post_vars = array(); </code>
Plugin could not be activated because it triggered a fatal error?
wordpress
I'm displaying the comments for a post my way, using <code> $comm = get_comments() </code> and then passing <code> $comm </code> to <code> wp_list_comments() </code> (stackexchange-url ("this is the reason why")). How to disable WordPress from loading comments from the database into <code> $wp_query </code> , when the comment template is being displayed ? I'm asking this because I want to avoid this extra database call, since I'm getting the comments myself using the above method. PS: I also noticed the <code> $comments </code> global variable is a array containing ALL the comments for a post, not just the ones from the current comment page. If I have a post with 10K comments, WP will load all these at once? Seems ridiculous...
You can't prevent <code> comments_template() </code> from making an SQL query. Well, you could maybe hook into the DB layer to prevent just that specific query, but that would be very cumbersome to do. If this is for a theme, you could just remove the call to <code> comments_template() </code> and replace it with your own function. <code> comments_template() </code> doesn't do that much : just load all the comments, maybe also the just-submitted comment if it isn't approved yet, separate them into pings, trackbacks and regular comments if needed, and load the comments template file. Comments paging is relatively young in WordPress, so it's probably not as efficient as it could be yet.
Prevent WordPress from loading comments
wordpress
I have a ajax request hooked on "template_redirect" (the ajax requests the post's url), and I want to display only the comment template: <code> function get_comm(){ if(isset($_GET['get_my_comments'])): $offset = intval($_GET['get_my_comments']); echo $offset; // offset will be the same as "cpage" global $comments, $wp_query, $post, $id; print_r($comments); // nothing ? print_r($wp_query-&gt;comments); // nothing ?? wp_list_comments('type=comment', $comments); // same :( exit(); endif; } add_action('template_redirect', 'get_comm'); </code> the javascript part works and it's like this: <code> $("a.show-more-comments").live("click", function(){ var offset = $(this).attr('rel'); var list = $(this).closest("#comments"); $.ajax({ url: "&lt;?php echo get_permalink($post-&gt;ID); ?&gt;", type: "GET", data: ({ get_my_comments: offset }), success: function(data){ list.append(data); } }); }); </code> The problem is that <code> $comments </code> or <code> $wp_query-&gt;comments </code> don't seem to be initialized. What am I doing wrong here?
<code> $comments </code> , or <code> $wp_query-&gt;comments </code> , is initialized by <code> comments_template() </code> , which you call in your template file when you want to load the comment sub-template file. So at the time of <code> template_redirect </code> it is not yet initialized. As Chris said, you should call <code> get_comments() </code> and pass it the <code> post_id </code> of your current post. If you're doing AJAX calls, even not from the admin side, wp-admin/admin-ajax.php </code> and use special actions hooks . This shortcuts the usual post queries, which you don't need anyway.
Getting $comments outside the comment template
wordpress
I'm trying to create a custom post query for sorting posts that have been voted "thumbs up". I'm joining my custom "wp_post_votes" table (which stores the number of votes each post received) with the default "wp_posts" table and displaying posts <code> WHERE votes &gt; 1 </code> . The WHERE cause is causing an SQL error. When I remove the <code> posts_where </code> filter I get no errors but all my posts are displayed regardless of their vote number. <code> add_filter('posts_join', 'vote_join' ); add_filter('posts_where', 'vote_where' ); function vp_join( $join ) { global $wpdb; if (isset($_GET['vote_sort'])) { //when visitor browses voted posts $join .= " LEFT JOIN wp_post_votes ON " . $wpdb-&gt;posts . ".ID = wp_vote_posts.vote_post_id "; } return $join; } function vp_where( $where ) { if (isset($_GET['vp_sort'])) { $where = "voted &gt; 1"; } return $where; } //custom permalinks code follows... </code> The SQL error I get in index is.. WordPress database error: [] SELECT t. , tt. FROM wp_terms AS t INNER JOIN wp_term_taxonomy AS tt ON tt.term_id = t.term_id INNER JOIN wp_term_relationships AS tr ON tr.term_taxonomy_id = tt.term_taxonomy_id WHERE tt.taxonomy IN ('category') AND tr.object_id IN (0) ORDER BY t.name ASC ..and in my sidebar I have a recent posts widget. In that I get via <code> $wpdb-&gt;show_errors(); </code> WordPress database error: [You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'voted > 1 ORDER BY wp_posts.post_date DESC LIMIT 0, 5' at line 1] SELECT SQL_CALC_FOUND_ROWS wp_posts.* FROM wp_posts LEFT JOIN wp_vote_posts ON wp_posts.ID = wp_vote_posts.vote_post_id WHERE 1=1 voted > 1 ORDER BY wp_posts.post_date DESC LIMIT 0, 5 I noticed <code> WHERE 1=1 voted &gt; 1 </code> .. not sure if that's causing the error and how to fix it.
Should be: <code> $where .= " AND voted &gt; 1"; </code> Other notes: instead of hardcoding table names you should use <code> $wpdb-&gt;prefix . 'post_votes' </code> ; instead of checking in global <code> $_GET </code> you should declare your filters as accepting two arguments and code functions accordingly, these filters pass as second argument object that contains all of query data. Like: <code> add_filter('posts_where', 'vote_where', 10, 2 ); function vote_where( $where, $query ) { if( isset( $query-&gt;query_vars['vp_sort'] ) ); $where .= ' AND voted &gt; 1'; return $where; } </code>
SQL error with custom query
wordpress
Hi I have a website like www.shankpress.com, it is wordpress v3, and i want my users to have blogs hosted in my site and have url like: blogs.shaknpress.com...and I can show who got the most popular blog entry etc... users can openly register, create a blog, start blogging and so on ... I am willing to buy solutions if no free stuff is available...
To run multiple blogs on single installation of WordPress you need to enable and configure <code> multisite </code> functionality, see Create a Network . While that will take care of basics, managing network of blogs controlled by users (rather than single admin/team) reliably and securely will likely require much more research and work.
Host a blog engine in my wordpress site
wordpress
I am in the process of developing a new theme for my blog and am making a featured content slider. The issue that I am having is getting wordpress to force the image to the dimensions that I want it to be. The exact dimensions are 494px x 168px. I've tried simple using <code> the_post_thumbnail( array(494, 168) ); </code> , but that didn't work. I also tried adding a custom image size to my functions file. This would sometimes get the height right (but not always), but didn't get the width right a single time. Could somebody please give me a way to force the dang image to be 494px X 168px?
For post thumbnails you can either crop and image to the thumbnail size or scale the image. To enable crop you can call the thumbnail 1 of 2 ways. Name a size in the functions.php file like so: <code> &lt;?php add_image_size( 'my-post-thumbnail', 494, 168, true ); ?&gt; </code> and then call it in the theme file <code> &lt;?php the_post_thumbnail('my-post-thumbnail'); ?&gt; </code> The true tells wordpress to crop the image rather than scale, to scale leave true out. Call the size just in the theme file <code> &lt;?php the_post_thumbnail(494, 168, true); ?&gt; </code> Also, the_post_thumbnail doesn't work on images already uploaded. To test if the sizes truly aren't working upload a new file after adding the new thumbnail size/calling it in your theme file. Mark on Wordpress has a good tutorial on Post Thumbnails http://markjaquith.wordpress.com/2009/12/23/new-in-wordpress-2-9-post-thumbnail-images/
Featured Image Size
wordpress
I've just installed Wordpress here at arun.sanspace.in But, don't know why, it doesn't display any images. I want to know why? I have another Wordpress installation on the same server which works great. What exactly is the problem here? Am I doing something wrong? While I copy the image location from the placeholder and open it alone, it displays the picture. It happens on IE and FF both.
I've figured it out. I had enabled hotlink protection. I installed the new blog in a new subdomain which was not added to the hotlink protection. So, it prevented the image requests. Now I added to the list and everything's fine. Silly me. :-(
Why no images on a fresh Wordpress installation?
wordpress
I am creating my first ever plugin for a membership site. I have a custom table named <code> subscription </code> with a <code> subscr_user_id </code> column whose values are taken from <code> $current_user-&gt;ID </code> . So when a current user subscribes, a new record is inserted into the table where <code> subscr_user_id </code> gets the value of the current user's ID. How do I query(INSERT AND SELECT) the table from a template(I don't know of any other means to test queries)? I have this SELECT query: Note that I have preinserted one record into table subscription with subscr_user_id = 1 which means the user is an administrator. I did that thru sql console. <code> //Somewhere in between the body of the template. //This query will be used for a code that checks if a user ID is already subscribed to avoid duplicate records. global $current_user; global $wpdb; $user_id = $wpdb-&gt;get_row("SELECT * FROM $wpdb-&gt;subscription WHERE subscr_user_id = $current_user-&gt;ID"); echo '&lt;p&gt; Current user ID is:'.$user_id-&gt;subscr_user_id. '&lt;/p&gt;'; </code> Before I viewed the page that uses that template, I logged in as an administrator to make sure the ID is <code> 1 </code> . Unfortunately I didn't get any result? Could anyone also please show me a sample of INSERT statement?
You need to tell $wpdb what subscriptions when initializing your plugin: <code> $wpdb-&gt;subscriptions = $wpdb-&gt;prefix . 'subscriptions'; </code>
How to query custom db table?
wordpress
I'm working on a site which has a fully customized front page. Now I'm asked to add a more classic looking blog type page which will be reacheable at <code> http://domain/blog </code> . I tried creating a custom (empty) page called <code> blog </code> and put some code into <code> page-blog.php </code> , but the problem is that I can't get The Loop to work in there: the page render aborts right where the display of The Loop should start. Is a custom page the wrong way to do it?
Hi @Kemp: Assuming you are using WordPress v3.x (as I don't remember how this works in earlier versions) this is what you need to do if starting from scratch: Create a " Page " and call it "Home Page" (or whatever.) Create another Page and call it "Blog" (or whatever.) In the admin console select the "Settings" > "Reading" option. Select "A static page" for the "Front Page Displays" radio button. Assign "Front Page" to be "Home Page" (or whatever from #1) Assign "Posts Page" to be "Blog" (or whatever from #2) Click "Save Changes" You're done. Here's a screenshot showing the admin console options:
How can I create an alternative home page?
wordpress
I am not sure which solution here would work best as a solution but what I am looking for is just a simple way to enter an optional domain through a metabox on the page edit screen and then just select a template from the default page templates wordpress uses. I am assuming there must be a simple way to accomplish this by manually adding an A name record for the new domain and pointing it to the same IP the main website is using and then through some code allow requests to this new domain to load a specific post ID while utilizing the specific page template you selected. I would like for the page to be accessible for both domains and just the new domain would utilize the defined template. How can this be done? updated I guess the other way would be to first setup a single page so it can have its own subdomain by using some built in wordpress code used for multisite? In other words, if a custom subdomain could be assigned to a specific post id then a cname record to this subdomain could be set for the new domain... Not sure the best way to accomplish this.
This code will allow you to set a custom meta value, and if the domain name (or subdomain if you edit the code) matches it, the query will be changed to match that post. The page template will only be used for that request, not for requests via the "normal" URL. This does not change links on that page: should they go to the "normal" site or stay in the subdomain? How you solve this on the DNS side is probably a Server Fault question. <code> define( 'WPSE4558_STANDARD_SERVER', 'www.example.com' ); define( 'WPSE4558_META_KEY', 'domainname' ); add_filter( 'request', 'wpse4558_request' ); function wpse4558_request( $query_vars ) { $query_vars['is_subdomain_request'] = false; if ( WPSE4558_STANDARD_SERVER != $_SERVER['SERVER_NAME'] ) { $query_vars['meta_key'] = WPSE4558_META_KEY; // This can also be just the subdomain, if you edit it $query_vars['meta_value'] = $_SERVER['SERVER_NAME']; $query_vars['is_subdomain_request'] = true; } return $query_vars; } add_action( 'parse_query', 'wpse4558_parse_query' ); function wpse4558_parse_query( &amp;$wp_query ) { if ( $wp_query-&gt;get( 'is_subdomain_request' ) ) { $wp_query-&gt;is_home = false; $wp_query-&gt;is_page = true; $wp_query-&gt;is_singular = true; } } add_filter( 'page_template', 'wpse4558_page_template' ); function wpse4558_page_template( $template ) { global $wp_query; $id = $wp_query-&gt;get_queried_object_id(); if( ! $wp_query-&gt;get( 'is_subdomain_request' ) &amp;&amp; get_post_meta( $id, WPSE4558_META_KEY ) ) { // This is a page that has a subdomain attached, but the current request is not via that subdomain // So use the normal template hierarchy, ignore the page template $templates = array(); $pagename = $wp_query-&gt;get_queried_object()-&gt;post_name; if ( $pagename ) { $templates[] = "page-$pagename.php"; } if ( $id ) { $templates[] = "page-$id.php"; } $templates[] = "page.php"; $template = locate_template( $templates ); } return $template; } </code>
How to let a single post have its own domain name
wordpress
How can I add a page to the menu and define for the menu item that all subpages should be included by means of a simple checkbox?
you might be interested in one of my threads. Here: stackexchange-url ("How to Hard Code Custom menu items") Thanks!
Default menu editor with automatic page list
wordpress
(Satisfying minimum text requirement)
Here is a code I used to do it: <code> // make category use parent category template function load_cat_parent_template($template) { $cat_ID = absint( get_query_var('cat') ); $category = get_category( $cat_ID ); $templates = array(); if ( !is_wp_error($category) ) $templates[] = "category-{$category-&gt;slug}.php"; $templates[] = "category-$cat_ID.php"; // trace back the parent hierarchy and locate a template if ( !is_wp_error($category) ) { $category = $category-&gt;parent ? get_category($category-&gt;parent) : ''; if( !empty($category) ) { if ( !is_wp_error($category) ) $templates[] = "category-{$category-&gt;slug}.php"; $templates[] = "category-{$category-&gt;term_id}.php"; } } $templates[] = "category.php"; $template = locate_template($templates); return $template; } add_action('category_template', 'load_cat_parent_template'); </code>
How can I make all subcategories use the template of its category parent?
wordpress
I am using multipress, but users with small screens cannot access the HTML tab as the Publish meta box has a div that slides above it, disabling the ability to click it. One idea is to force a single column layout, but there are no options for this in screen options. Is there another way to do it?
You can use the filter <code> screen_layout_columns </code> to set only one column for the post screen <code> get_user_option_screen_layout_post </code> to force the user option to 1. The following code will do it: <code> function so_screen_layout_columns( $columns ) { $columns['post'] = 1; return $columns; } add_filter( 'screen_layout_columns', 'so_screen_layout_columns' ); function so_screen_layout_post() { return 1; } add_filter( 'get_user_option_screen_layout_post', 'so_screen_layout_post' ); </code>
how do I force a single column layout in screen layout
wordpress
Can you recommend a plugin that enables notification on multiple email addresses on posted comments? Looking for a plugin that both notifies a global list of email addresses and the author of the post.
Use this plugin: comment notifier http://wordpress.org/extend/plugins/comments-notifier/
Notify multiple email addresses on comments
wordpress
I want the links widget in my sidebar to display links based on the page the user is on. For example, if the user is on the home page I want it to display link1, link2 and link3. But if the user goes to the 'About' page I want the links widget to display link4 and link5. Is there a way to specify conditional display of links depending on the page id? Thanks
Widget Logic http://wordpress.org/extend/plugins/widget-logic/ Also Query Posts Widget is very useful http://justintadlock.com/archives/2009/03/15/query-posts-widget-wordpress-plugin
Conditional Display of Links in Widgets
wordpress
I'm making a custom query for posts using something like: <code> $p = new WP_Query(); $p-&gt;query(array('offset' =&gt; 30, 'posts_per_page' =&gt; 10)); </code> If I have 36 posts on the entire blog, <code> $p-&gt;post_count </code> will return the number of posts that were retrieved, 6 in this case. I need to get the post count just like I would if I omitted this 2 arguments (so I can calculate the remaining post count). How can I do that, without making another query?
The found_posts property <code> $p-&gt;found_posts </code> will return it.
WP_Query with the "offset" argument
wordpress
( Moderator's Note: Original title was: "Steps to move multiple wordpress installations to a WP MU installation") Any tips on moving multiple WordPress installations to a single Multisite[1] installation? [1] Multisite is the new name for WPMU.
For the record MU functionality was merged into core and is now referred to as <code> multisite </code> . Codex has guide at Migrating Multiple Blogs into WordPress 3.0 Multisite
Steps for Moving Multiple WordPress Installs to a Multisite Install?
wordpress
I have a php file with some variables which I would like to use. When I include it in the header.php the variables in that file are not recognized at footer.php and some other places. Where is the best place to include this file so its content will be shared all over the wp files.
Variables have a certain scope. The PHP Manual explains that in detail . So when you set a variable you should know in which scope those are set. This depends on where you set them and how that file gets included. As Rarst already suggested, the function.php file is an ideal place as it gets included on the global space whenever your theme is active. Next to that, scope still applies. The <code> footer.php </code> file for example normally is not included on the global scope. To access your variables therein - if you have set them globally - you can refer to the <code> $GLOBALS </code> superglobal array . This normally does it for some variables. If you have multiple, you might consider to attach all your variables to an array instead, so you have only one variable name in the global scope you need to refer to. This keeps things a bit more apart from each other which makes it easier in the long run. Because if you name your variables the same as existing variables, you will overwrite them. That can break things that are hard to debug. Example: in function.php <code> $mytheme_config = array(); $mytheme_config['extra_footer_display'] = true; </code> in footer.php <code> if ($GLOBALS['mytheme_config']['extra_footer_display']) { // executed when extra_footer_display is true } </code> This is just a very basic example, but it probably already does the job for you. I don't know your level of experience with PHP, but as you're starting probably, the links provided above you give you the basic understanding how this is working. Just keep in mind, that template parts are not loaded within the global scope so you need to reference global variables with the <code> $GLOBALS </code> superglobal array to access them. <code> $GLOBALS </code> is always referring to global variables regardless of the scope where it is accessed.
where to include a php file
wordpress
Is it possible to remove a broken theme from WordPress using only the WordPress dashboard? i.e, without using cpanel or FTP? Background: When you are doing customer support, its rare that you have access to the user's FTP or cpanel, but its pretty simple for them to set you up as a temporary user to troubleshoot their site.
You can use <code> Appearance &gt; Editor </code> to kill theme's header in <code> style.css </code> . Won't really remove it, but will prevent it from showing up as available in WP.
How do you remove a broken theme from WordPress Admin (without FTP or Cpanel)
wordpress
How can I customise the the new user welcome email ? I tried 'http://www.sean-barton.co.uk/wordpress-welcome-email-editor/' however it conflicts with some of the other plugins I need to use, Cimy Extra Fields. There is one other plugin that is to old for wordpress 3.0.1. Will
SB Welcome Email Editor works by replacing <code> wp_new_user_notification() </code> with an own version. The original version can be found in <code> wp-includes/pluggable.php </code> , the plugin uses an elaborate replacement with all kinds of options. You can do this to: create a new plugin (just a PHP file in <code> wp-content/plugins/ </code> ), and define <code> wp_new_user_notification($user_id, $plaintext_pass = '') </code> there. This will then be used instead of the regular WordPress version.
How do I customise the new user welcome email
wordpress
I'm getting 3 very similar phpMyAdmin errors on one of my WordPress databases. <code> More than one INDEX key was created for column `comment_approved` More than one FULLTEXT key was created for column `post_title` More than one INDEX key was created for column `lead_id` </code> Anyone know how to resolve these?
As it writes, a problem with the indexes definitions of those tables. Please try a repair on the reported table and see if that helps. Have you activated a specific add-on lately or did you alter tables?
What do these phpMyAdmin errors mean on my WordPress databaes?
wordpress
For a plugin, I need to build my own very early post content and comment content filter. Post content/text changing works, i.e. the modifications end up in the client's browser. But my comment content/text modifications somehow are not persistent, i.e. the client receives the original comment text. The point in time I "hook in" is defined by the template_redirect hook. I then execute something like this: <code> global $wp_query; // Iterate over all posts in this query. foreach ($wp_query-&gt;posts as $post) { // Edit post text $post-&gt;post_content = "foo"; // works: ends up at the client // Iterate over all approved comments belonging to this post $comments = get_approved_comments($post-&gt;ID); foreach ($comments as $comment) { // Edit comment text $comment-&gt;comment_content = "bar"; // this one is lost } } </code> As indicated via the source comments above, <code> $post-&gt;post_content = "foo"; </code> has effect in this context, but <code> $comment-&gt;comment_content = "bar"; </code> doesn't. To track this down at least a bit more, I applied a debug filter to the post content and to the comment content: <code> add_filter('the_content', 'var_dump'); add_filter('comment_text', 'var_dump'); </code> After the content modification routine above, these filters print "foo" in case of post content, but the comment content is printed unchanged (the original content is printed). Hence, <code> $comment-&gt;comment_content = "bar"; </code> seems to be a local modification, while <code> $post-&gt;post_content = "foo"; </code> works as desired: globally. Or is the database even queried two times for comments so that my modification somehow gets overwritten at some point? I've tried to work with <code> $wp_query-&gt;comments </code> , too. But this variable is <code> NULL </code> at the point in time I want and need to hook in. The final and primary question is: In my loop above, what do I have to do, to modify the comment content persistently? FYI: I am using WordPress 3.0.1
The function that includes the comments template also (re)loads the comments . This means that whatever you do before that point, if you don't save it to the database it will not be used. There is no way to prevent this SQL query from happening, but you can override the results by hooking into the <code> comments_array </code> filter. I would save your modifications in an array keyed by the comment ID, so you can do quick lookups and replace contents if needed. <code> $wpse4522_comments = array(); // Somewhere in your template_redirect (why not wp_head?) hook: foreach ($wp_query-&gt;posts as $post) { // Edit post text $post-&gt;post_content = "foo"; // works: ends up at the client // Iterate over all approved comments belonging to this post $comments = get_approved_comments($post-&gt;ID); foreach ($comments as $comment) { // Edit comment text $GLOBALS['wpse4522_comments'][$comment-&gt;comment_ID] = 'bar'; } } // And this loads the content back into the array from comments_template() add_filter( 'comments_array', 'wpse4522_set_comments_content' ); function wpse5422_set_comments_content( $comments, $post_id ) { global $wpse4522_comments; foreach ( $comments as &amp;$comment_data ) { if ( array_key_exists( $comment_data-&gt;comment_ID, $wpse4522_comments ) ) { $comment_data-&gt;comment_content = $wpse4522_comments[$comment_data-&gt;comment_ID]; } } return $comments; } </code>
How modify the comment content persistently based on $wp_query?
wordpress
What causes this error (generated while uploading any theme to this WP site) <code> Unpacking the package… Incompatible Archive. PCLZIP_ERR_BAD_FORMAT (-10) : Unable to find End of Central Dir Record signature </code> I've tried to upload several different popular themes to the site.
This error comes from the library that manages ZIP formatted archives: http://www.phpconcept.net/pclzip/user-guide/19?showall=1 After a quick web search, two solutions came up: 1) Which version of WordPress are you using? For version 2.8 this seems to be a known and fixed issue. Hence, an update of WordPress could help. 2) You perhaps have to increase your available hosting space. If it's nothing of this, searching for your error message + WordPress yields many many results!
Incompatible Archive. PCLZIP_ERR_BAD_FORMAT (-10)
wordpress
I have WP Multisite and now I want to track the different sites. I'm using Multisite Domain Mapping to map <code> www.mysite.com </code> to <code> http://subsite.mysite.com </code> My questions is: a) Do I need to add the same google analytics script to all themes? b) when creating the script at GA, I have the following choices: A single domain (default) One domain with multiple subdomains Multiple top-level domains Do I use nr 2 or 3? I know there are plugins I can use. But I still have to create the scripts at GA, right?
Hook the script into the footer, which is easy enough. http://wpmututorials.com/plugins/how-to-hook-into-the-footer/ As stated in the post, toss that into mu-plugins, it will track all your site, regardless of domain. GA can sort it out on their end. totally do-able.
What type of Google tracking should I use?
wordpress
Because it's not working for me. This code checks if a user has just registered. I want to redirect him to a custom page if so. Otherwise, redirect him to the homepage or admin page. <code> function mylogin_redirect($redirect_to, $url_redirect_to = '', $user = null) { if( $user-&gt;ID ) { $user_info = get_userdata( $user-&gt;ID ); // If user_registered date/time is less than 48hrs from now // Message will show for 48hrs after registration if ( strtotime( $user_info-&gt;user_registered ) &gt; ( time() - 172800 ) ) { return get_bloginfo('url') . "/custompage/"; } elseif( current_user_can( 'manage_options' )) { return admin_url(); } else { return get_bloginfo('url'); } } } add_filter('login_redirect', 'mylogin_redirect'); </code> I get the expected results for the two options but the admin. <code> elseif( current_user_can( 'manage_options' )) { return admin_url(); } </code> doesn't seem to get parsed.
Probably because the global <code> $current_user </code> isn't valid yet, which is used by <code> current_user_can() </code> . However, you can use this instead; <code> if ($user-&gt;has_cap('manage_options')) { return admin_url(); } </code>
How to use current_user_can()?
wordpress
In the code below, I'm attempting to get a reference to the body content of the current post's fully rendered preview... <code> $response = wp_remote_retrieve_body(wp_remote_get('http://localhost/mysite/test-post/?preview=true&amp;preview_id=28&amp;preview_nonce=640bc54ca4')); $post-&gt;post_content = $response; </code> I'm just sending it to $post-> post_content so that I can easily see it. Here's part of what it returns... <code> &lt;body id="error-page"&gt; &lt;p&gt;You do not have permission to preview drafts.&lt;/p&gt;&lt;/body&gt; &lt;/html&gt; </code> I'm logged in as the administrator, so obviously I'm calling the preview wrong. How can I pass the URL in wp_remote_get to obtain the body section of the preview stream? When I use... <code> $post-&gt;post_content = "&lt;pre&gt;".$response['body']."&lt;/pre&gt;"; </code> I get <code> &lt;pre&gt;&lt;&lt;/pre&gt; </code>
The URL is okay, what you need to add are cookies that authenticate you as the user who is allowed to see the preview. That is basically sending headers. I would start with the HTTP API (Wordpress Codex) looking for a method to add additional HTTP headers and set your cookies. Otherwise - because probably this is somewhat complicated - you could take a look inside the preview code so to see if you can provide a hook to control access to previews. If possible, you can add some secret parameter to the URL which would allow you to preview any page w/o the need of being logged in (and the need of a nonce as it needs to be provided for preview as well). The result of either the first or the second approach is quite the same, the only difference would be how to trigger it.
What URL do you pass to wp_remote_get to load the body of the current post's preview?
wordpress
The code below resides in my theme's functions.php and creates a custom upload icon on top of the WordPress content editor, alongside the default upload icon. Images uploaded via this icon get a special flag in wp_postmeta called _imageTop to differentiate them from standard attached images (to allow me to do special things to them as a separate collection of "attached" images). I've got 3 problems occuring that I'm sure are simple fixes. 1) The attachment_fields_to_save filter does not get applied, even though I can see the echo'd text inside the media-upload.php window. I know this because the _imageTop meta only gets written to the database when I comment out the if(isset) check 2) After the images have been uploaded, I have to click on "Save all changes" to get the _imageTop meta to save to the database. Ideally, I'd like the data saved immediately after the upload, without having to click "Save all changes". This is probably due to the fact that the attachment_fields_to_save handler only fires on the "Save all changes" hook. Nevertheless, I'd like to figure out how to get it to fire when the images have been uploaded. 3) I want to remove the "insert into post" link from the screen. <code> //Upload custom images function my_customImages($initcontext) { global $post; ?&gt; &lt;script type="text/javascript"&gt; jQuery(document).ready(function() { var fileInput = ''; jQuery('#wpe-uploadAttachments').click(function() { fileInput = jQuery(this).prev('input'); formfield = jQuery('#upload_image').attr('name'); post_id = jQuery('#post_ID').val(); tb_show('my Product Images', 'media-upload.php?post_id='+post_id+'&amp;type=image&amp;my_idCustomAttachment=true&amp;TB_iframe=true'); return false; }); }); &lt;/script&gt; &lt;?php return $initcontext. '&lt;input type="hidden" id="post_ID" value="'. $post-&gt;ID .'" /&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;Product Images:&lt;a id="wpe-uploadAttachments" href="javascript:;" class="mceButton mceButtonEnabled" onmousedown="return false;" onclick="return false;" title="Click here to upload your product images for this post"&gt;&lt;img src="'.get_bloginfo('template_directory') .'/img/upload-icon.gif"" /&gt;&lt;/a&gt;'; } add_filter('media_buttons_context', 'my_customImages'); function my_image_attachment_fields_to_save($post, $attachment) { update_post_meta($post['ID'], '_imageTop', true); return $post; } if(isset($_GET['my_idCustomAttachment'])){ echo "This is true"; add_filter("attachment_fields_to_save", "my_image_attachment_fields_to_save", null , 2); } </code>
1) The attachment_fields_to_save filter does not get applied, even though I can see the echo'd text inside the media-upload.php window. I know this because the _imageTop meta only gets written to the database when I comment out the if(isset) check Try to exchange $_GET with $_POST and see if it works. If so, you need to check for $_POST as well. 2) After the images have been uploaded, I have to click on "Save all changes" to get the _imageTop meta to save to the database. Ideally, I'd like the data saved immediately after the upload, without having to click "Save all changes". This is probably due to the fact that the attachment_fields_to_save handler only fires on the "Save all changes" hook. Nevertheless, I'd like to figure out how to get it to fire when the images have been uploaded. If it does not get fired, the only thing you can do is to fire it your own, e.g. call the hook function directly. If that is not possible (e.g. you have not code that is executed so you can't execute your additional code then), you need to look for another action you can hook into, e.g. one that get's fired after the upload. There probably is some hook when the image get's saved in the media library. You could then store your custom post field as well (!) into the database. Just to have it saved. I dunno if WP is able to handle that with it's revision system, so you need to try. 3) I want to remove the "insert into post" link from the screen. I do not know how this can be done from the top of my head, you should check the core code if there is something you can override with/by a hook.
Custom attachments uploader code. Almost there!
wordpress
I have problems to checkout the wordpress.org plugin repository via SVN on <code> https://plugins.svn.wordpress.org/ </code> . First it starts all looking well: <code> &gt;svn --force checkout https://plugins.svn.wordpress.org/ A plugins.svn.wordpress.org\lumberjack ... </code> But while it progresses, it gets stuck: <code> ... A plugins.svn.wordpress.org\gbs-ad-shopping\readme.txt A plugins.svn.wordpress.org\gbs-ad-shopping\SaveButton.png svn: In directory 'plugins.svn.wordpress.org\gbs-ad-shopping' svn: Can't open file 'plugins.svn.wordpress.org\gbs-ad-shopping\.svn\tmp\text-base\readme.txt.svn-base': Das System kann die angegebene Datei nicht finden. </code> ( Das System kann die angegebene Datei nicht finden. is German for a file not found error) So now the working copy is broken. First thing to do I thought is to run a cleanup, but see what happens: <code> &gt;svn cleanup plugins.svn.wordpress.org svn: In directory 'plugins.svn.wordpress.org\gbs-ad-shopping' svn: Error processing command 'modify-wcprop' in 'plugins.svn.wordpress.org\gbs-ad- shopping' svn: 'plugins.svn.wordpress.org\gbs-ad-shopping\format' is not under version control </code> It looks a bit to me that this plugin is has some weird settings that prevent to checkout it. So any hints on this? Better ask that question over at SE?
Okay, looks like this is a problem with windows. I tested this now under linux and it worked like a charm. I have no idea what is causing this, but that specific plugin which is problematic is looking wired in svn anyway. So solution is to use a SVN client on linux. It just works.
How to checkout the wordpress.org plugin repository?
wordpress
Off Topic? Maybe, point me to where this would be On Topic! Hi All, My daughter attends a private school. Recently their wordpress website was hacked and they need some help cleaning it up. I don't have the experience with wordpress to help. Are there services or websites that they could use to find the expertise to help with this? Of course they would be compensated. Here is a description of the problem: Thanks! -DF5 Thank you for getting back to me. We are trying to detect any possible back door vulnerabilities in our Wordpress installation that may be allowing scripts or bots to place malicious code on our website. We have been hit by a specific drug company. This code seems to turn up in our pHp files. The original problem was that people who clicked twice on any page of our site were redirected to this drug website!! We have cleaned the installation manually, but there may still be scripts running in the database or remaining vulnerabilities because we did not want a re-installation of a clean version of Wordpress. We have scanned the database and there appear to be no known rogue files, but we are concerned that there may still be scripts running that are very well hidden. We basically need someone to start by looking through our files to see if there is something we and the scan missed. There is a lot of customization we did on our website and are trying to avoid a clean install. We are also in contact with Dream Host (our hosting company) to see if it is a server issue as we are uncertain if this is a Wordpress vulnerability via a plugin or a server issue that Dream Host can resolve. The website seems to be functioning well now, we are mainly trying to prevent another problem and to eradicate any malicious code so we are not penalized in the search engines.
See FAQ: My site was hacked « WordPress Codex and How to completely clean your hacked wordpress installation and How to find a backdoor in a hacked WordPress and Hardening WordPress « WordPress Codex
Need help cleaning up a wordpress site after being hacked
wordpress
Hello I am wandering if anyone can recommend, from first hand experience, a reasonably simple CRM or project management plugin for wordpress. I have read stackexchange-url ("this question on the topic.") But am looking for slightly more detail and if possible someone who has actually used one of these. The functionality I am looking for is to be able to store contacts, share files, have a forum/message board or even chat type area and some simple task/project management functions such as assigning cases to team members. One more thing, if possible users should be able to select their preferred language, preferably at least with English and Simplified Chinese, although I accept this may not be possible or may require manual translation. I have used both sugarcrm and vtiger, but have found that them to be a bit bloated and was wondering if any of the wordpress option available would be suitable for our needs. Thanks.
The only project I know that is viable is rolopress, download it and see what you can adjust. FYI I have a related question open here: stackexchange-url ("stackexchange-url but for a PRM. But the thing you are looking for is I think not a CRM system but a PM/software project system, all your requirements are met with RTC ( http://www.jazz.net ), free for 10 users. It has chat, users, projects, projectmanagement, tickets, version control, reports, your (agile/RUP/UP/whatever) planning and project approach etc... and all integrated. You can have rss feeds on everything and it has a REST, etc.. possibilites and an API. I have not tried version 3 yet: http://jazz.net/blog/index.php/2010/11/23/rational-team-concert-3-0-released/
Can anyone recommend a wordpress based CRM/Project Management system or plugin?
wordpress
Part of a voting script I'm working on: I'm checking a custom table in my WP database to see if a user already voted for a post by checking the IP address and the post id. If the user's IP already exists for the post they voted, I want to echo "Already voted!" otherwise add the IP. This is what I came up with.. <code> global $wpdb; $voter_ip = $_SERVER['REMOTE_ADDR']; $post_id = $_POST['post_id']; if (!($wpdb-&gt;get_row("SELECT voter_ip FROM wp_voter_ips WHERE post_id = $post_id AND voter_ip = $voter_ip") ) ) { //if IP address for matching post id not found in wp_voter_ips table $wpdb-&gt;insert( $wpdb-&gt;prefix . 'voter_ips', array( 'post_id' =&gt; $post_id, 'voter_ip' =&gt; $voter_ip ) ); //add IP and post_id echo "voted!"; } else //if IP already exists { echo "Already voted!"; } </code> I triple checked to make sure the variables and column names are correct. Regardless of the if statement, it inserts the voters IP even when it already exists.
On your <code> if() </code> , it should be like this: <code> if (!($wpdb-&gt;get_row("SELECT voter_ip FROM " . $wpdb-&gt;prefix . "voter_ips WHERE post_id = $post_id AND voter_ip = '$voter_ip'") </code> Notice the quotation mark added on <code> $voter_ip </code> .
if statement on database query
wordpress
The code below if from my WP plugin which gives a filtered listing of categories excluding the "uncategorized" category from display. However, when the user chooses "Show Hierarchy" from the widget setup options, the resulting display includes "uncategorized". Given that I've placed 'exclude_tree' => 1 into the $cat_args array. What am I missing? <code> class My_Widget_Categories extends WP_Widget { function My_Widget_Categories() { $widget_ops = array( 'classname' =&gt; 'widget_categories', 'description' =&gt; __( "filters out uncategorized categories" ) ); $this-&gt;WP_Widget('my_categories', __('my Categories'), $widget_ops); } function widget( $args, $instance ) { extract( $args ); $title = apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Categories' ) : $instance['title']); $c = $instance['count'] ? '1' : '0'; $h = $instance['hierarchical'] ? '1' : '0'; $d = $instance['dropdown'] ? '1' : '0'; echo $before_widget; if ( $title ) echo $before_title . $title . $after_title; $cat_args = array('orderby' =&gt; 'name', 'show_count' =&gt; $c, 'hierarchical' =&gt; $h, 'exclude_tree' =&gt; 1); if ( $d ) { $cat_args['show_option_none'] = __('Select Category'); wp_dropdown_categories(apply_filters('widget_categories_dropdown_args', $cat_args)); </code>
It's hard to say from your code. The <code> exclude_tree </code> parameter of wp_dropdown_categories() is pretty undocumented in codex. It's making use of get_categories() which does not list it at all. If you don't have children within that category, you can consider to use the <code> exclude </code> parameter instead / additional. Just give it a test if that works. This might save you the hassle to deal with some bugs in wordpress in the end. Wordpress is not very well in handling hierarchy over the last years. Some background info: Beta 2.8.2 - wp_list_categories buggy hierarchy - Ticket #9999 ; With wp_list_categories child categories not excluded when parents are excluded - Ticket #8614
How to exclude "uncategorized" from custom categories widget?
wordpress
I'm working on my wordpress site, and I want to have a page that shows all posts from the category 'portfolio' on a separate site. I'm using the following technique: http://codex.wordpress.org/Pages#A_Page_of_Posts However, on my testblog this works fine ( http://dev.litso.com/portfolio-2/ ) but on my live blog it doesn't seem to load the custom pagetemplate portfolio.php ( http://www.stephanmuller.nl/portfolio-2/ ). Instead, it uses the regular page.php template. Both are pages (not posts), use the exact same theme (not even a copy, the same physical theme in a multisite installation), the same custom field 'category' with a value of 'portfolio' and both blogs have at least one entry with the 'portfolio' category. The only difference between the two is that the dev blog does not have the option to choose the page's template (yet it does use the custom Portfolio template). The live site does have this option and it's set to Portfolio of course but when I view the page it uses Page. I can't find out why this is either. Anyone who can help?
So, apparently I accidently copied the comment <code> Template Name: Portfolio </code> to my page.php as well, so when I selected the 'portfolio' template wordpress just picked page.php out of the two possible templates. May be a warning for other people that have this problem :)
Page with posts from category doesn't work
wordpress
This div element is causing a big gap on my wordpress page, specifically on the single post page. It's nowhere in the themes, I can't seem to find where this div element is coming from. Have you encountered this before (the highlighted element)? PS : Happens on chrome only. UPDATE: Still having this problem even with the stable chrome. Help anybody? UPDATE2 : I think its the syntax highlighter plugin. And I also found out all other wordpress blogs (that I've checked) have this div. And the code's height in the post adds to the height of the div.
It looks to me like JavaScript for your lightbox. edit If this only happens in Chrome, there is a rendering bug that has gone unfixed for quite some time. Add height:100%; to the body or html element in your css.
Where's did this div element come from?
wordpress
My theme options save routine is below. I'm finding that if the $value['id'] being passed from my options array has a period in it, the data does not get passed and the options appear to break at that point. Should I opt for another character or is there a workaround for using the period character in an option name? For example, this works fine: <code> "id" =&gt; "myTheme_color|sidebar", </code> but this does not (no data is passed for the value): <code> "id" =&gt; "myTheme_color.sidebar", </code> The save function is: <code> function mytheme_add_admin(){ global $themename, $shortname, $options; if ( $_GET['page'] == basename(__FILE__) ) { if ( 'save' == $_REQUEST['action'] ) { foreach ($options as $value) { update_option( $value['id'], stripslashes($_REQUEST[$value['id']]) ); } foreach ($options as $value) { if( isset( $_REQUEST[ $value['id'] ] ) ) { update_option( $value['id'], stripslashes($_REQUEST[ $value['id'] ]) ); echo $value['id'].": ".$_REQUEST[$value['id']]."&lt;br&gt;"; echo $value['id'].": ".stripslashes($_REQUEST[$value['id']])."&lt;br&gt;"; } } } } </code>
Dots and spaces are replaced by PHP for array indexes via POST and GET. That may cause your problem.
Dot "." in option value foobars save options function
wordpress
While I've typically used include or require on their own to save long term code maintenance I've started to use get_template_part and locate_template as using built in WordPress stuff is always best. My question is are you supposed to be able to pass variables through to the results of either get_template_part or locate_template? <code> &lt;?php $var = get_option( 'my-custom-option' ); get_template_part( 'custom-template-part' ); ?&gt; </code> In the code above the $var would be printed inside the custom template but the variable doesn't seem to work. Am I missing something or is this expected behaviour? I've found that they don't pass in the instance above or when using locate_template <code> &lt;?php locate_template( 'custom-template-part.php', true ); ?&gt; </code>
Like stackexchange-url ("MathSmath wrote"), get_template() does not support the re-use of your variables. But locate_template() infact does no inclusion at all. It just locates a file for inclusion. So you can make use of include to have this working just like you expect it: <code> include(locate_template('custom-template-part.php')); </code> <code> $var </code> from your example can be used in the template part then. A related question with a more technical explanation of the variable scope and get_template(): stackexchange-url ("Form Submitting Error with get_template_part()")
Passing Variables through locate_template
wordpress
I am using Breadcrumb NavXT plug-in in my pages but now I am facing a problem I need to hide the "Home" link in some pages. I can do that either by hiding it in CSS or by not creating it at all. in PHP If I want to use CSS - I dont have any indication for first link and its "> > " separator - there is no id or special class for it If I go for the PHP solution of not creating it at all in those cases - my problem is I can't send any parameters to the "bcn_display()" function Can I do it with my current plug-in or there is a better one? thanks!
Update stackexchange-url ("Mtekk's answer") does basically what I was suggesting w/o the need to touch the plugin itself, so my answer is of quite theoretical nature. stackexchange-url ("He describes how to do that easily"). I think the easiest thing for doing so as you're mainly confident with the plugin (saying something minor to change), it would be to hack the plugin and insert a filter hook. Then you can filter based on your needs. If you share the code this might it make even into the original plugin, so you can benefit of updates. Example: See file <code> breadcrumb_navxt_class.php </code> . I've slightly changed a single function to create a filter: <code> /** * add * * Adds a breadcrumb to the breadcrumb trail * * @return pointer to the just added Breadcrumb * @param bcn_breadcrumb $object Breadcrumb to add to the trail */ function &amp;add(bcn_breadcrumb $object) { $doAdd = true; $doAdd = do_filter('_bcn_breadcrumb_trail_add_filter', $doAdd, $object); if ($doAdd) { $this-&gt;trail[] = $object; return $this-&gt;trail[count($this-&gt;trail) - 1]; } else { return $object; // NOTE: violates function return spec but prevents errors later on. } } </code> The introduced filter is named <code> _bcn_breadcrumb_trail_add_filter </code> . You now can hook to that filter and return <code> FALSE </code> which will prevent adding <code> $object </code> to the breadcrumb trail. In you filter you can decide based on <code> $object </code> wether or not you want to have it added. That is a <code> bcn_breadcrumb </code> so you can check for it's <code> title </code> member to look for home or so: <code> $object-&gt;title </code> The only thing you need to do is to add some code: <code> add_filter('_bcn_breadcrumb_trail_add_filter', function($doAdd, $object) { if ($object-&gt;title === 'Home' &amp;&amp; /* this is a page I don't want to have it displayed */) { $doAdd = false; } return $doAdd; }); </code> BTW, the author of the plugin is around here from time to time, so probably he has some feedback on this as well.
recommended breadcrumb plugins with possibility for hiding "Home" link
wordpress
In the w3 total cache there is the option to set the time until the cache is flushed (and thus, recreated on the next time a visitor comes by). My question is, assuming I've got a lot of content on my site that doesn't change almost ever, why would I not just set the caching to stay for days (instead of getting flushed every hour or so)? Is there a problem with that strategy?
The one possibility is caching broken page. For example some database query fails (which is not uncommon in shared environment and/or under load) and some page gets displayed broken / with errors. Since caching doesn't assume integrity checking it can cache such page... And your cache interval is days - page is broken as long. It would work better if mechanism was manual - you explicitly make something static and it remains that way (plenty CMS enginges work completely like that - generate complete static page and serve it). But I am not aware of any WP plugins that implement that.
Should the page cache be refreshed often?
wordpress
I am writing a plugin where I have custom taxonomy (category). I want to prevent any user from deleting some of custom categories . Is there any way how to do so. Let's say that category with id1-id10 nobody (admin included) can delete.
If you want to prevent deleting a single or a list of category IDs within the admin, you can prevent so by blocking all requests that delete the category. There is no hook in wordpress you can make use of to use easily, but there's always a work-around. In my example I use the <code> check_admin_referer </code> and <code> check_ajax_referer </code> hooks (note the typo in the hook name) combined with a check if the request is actually one to delete a category (delete something within the <code> category </code> taxnonomy). Example Must-Use Plugin : Wordpress Block Category Deletion Example On deletion of a blocked category, you will get either a You do not have permission to do that. message (Ajax) or a This category is blocked for deletion. message and you need to go back with your browser.
can I prevent WP users (even admin) from deleting custom categories?
wordpress
Is there a way to change the default text paragraph style in WP without changing CSS by hand? I.e. I need GUI for that. In particular, I want to configure padding height between paragraphs.
It depends on your theme. With most themes you'll have to manually edit the CSS to do this. But some themes have control panels that allow you to make changes to the design without editing the code. If you'd rather not write code but would like to make changes to your site, I'd suggest using a theme with design options. Some are very simple, just a few color choices or layouts to choose from, but others have hundreds of options. There are some free ones in the theme directory like Constructor and Platform , check out the theme-options tag to see all the themes which should have control panels. Of course there are also commercial themes which have these features as well, like Builder and Prose .
Configure paragraph style without editing CSS
wordpress
This seems to be a Thematic theme bug becuase if I switch to other themes, everything is working as expected. This is not the first time I created a frontpage using a static page. I made sure I followed this: http://codex.wordpress.org/Creating_a_Static_Front_Page . Any idea pls?
You should definitely check this page : http://themeshaper.com/forums/topic/posts-inside-the-pages-and-subpages
Why does my Posts page only show a single post when using Thematic?
wordpress
I've installed a wordpress site for a client. The site resides on mttv.co.il For some reson I'm being locked out of the system most of the time with no error message displayed The system takes the login &amp; password and just redirecs me back to the login page. Any help would be much appreciated
If worpdress redirects you back to the login and password page (and not displaying any info that login/password was wrong), this is a sign that the login session is broken. Most often this is related to cookies. Wordpress needs cookies for you to login. If cookies are not properly set or deleted later or are just mis-configured (there are some configuration constants available to control those, see in codex here and here ). You can tackle cookie issues down by using your browser and check which cookies are set or not set. Compare that with the information provided in codex to verify if that is your issue or not. If cookies are properly created, transfered from server to browser and then back from the browser to the server on the next request, then this is not a cookie issue. Something else then prevents on your blog to keep the login session. As the wordpress login session relies heavily con cookies, most often such issues are cookie related, because there is not much more to break. But sure, incompatible add-ons can break everything, so as well for that issue. If you experience it only on one computer with one browser, give the computer a reboot. Probably you just had a hick-up somewhere and this solves stuff. Keep in mind that some firewalls block cookies or referrers. Blocking referrers can create problems to login: http://hakre.wordpress.com/2010/05/26/you-do-not-have-sufficient-permissions-to-access-this-page/ - But normally this creates a different behavior.
Why am I locked out of the system?
wordpress
I'm using an IFRAME to let multiple sites embed one interactive element. On the IFRAME's actual page it works fine, and it looks fine on another website I embedded it. But when I embed it in a WordPress blog, all my apostrophes show up as squares. I tried removing all smart quotes and apostrophes with "dumb" quotes, no luck. I tried replacing all the apostrophes with &#39; and, again, no luck Any clues what my cause this? The IFRAME code: <code> &lt;iframe src="http://necir-bu.org/wp/interactives/sheriffinteract/interactive.html" name="interactive" scrolling="no" frameborder="0" marginheight="5" align="center" vspace="5" widtha"590px" height="720px"&gt;&lt;/iframe&gt; </code> And you can see the interactive code by just viewing the first link
The apostrophs get translated in <code> &amp;#39; </code> for the apostrophs, i guess it is an xss security feature. Check settings > reading > encoding (UTF8) but im not sure. (maybe the theme sets another encoding fixed in the header instead of reading the global variable). In any case your embed show correct in my WP test post (so with an apostrophe). Maybe you can set in the code of the iframe also <code> &lt;meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /&gt; </code>
WordPress kills an IFRAME's apostrophes
wordpress
I'd like to insert some mysql data into every new blog that's created on my buddypress system. How can I hook up to the newly created blog data? ID, for example, would allow me to insert it right from the PHP. Is there a better way to do it? Thanks!
see: stackexchange-url ("How To Modify New Sub Blog Immediately When Super Administrator Creates It?") The code I wanted to post I unfortunately could not post beacause "body is limited to 30000 characters; you entered 62367" so ... the following filters are handy (from WordPressMU plugin for site admin to set defaults for new blogs, Deanna Schneider) : <code> function set_blog_defaults($blog_id, $user_id) { global $wp_rewrite, $wpdb, $current_site; switch_to_blog($blog_id); // do stuff } // When a new blog is created, set the options add_action('wpmu_new_blog', array(&amp;$cets_wpmubd, 'set_blog_defaults'), 100, 2); ?&gt; </code>
How to run scripts when a new blog is created in Buddypress?
wordpress
Edit I removed the original Question as this Q has far above 1.000 views now - which means it's important to a lot of people - to show you something that works a) without a custom Walker &amp; b) is easy. Note: I only removed to original Q, because it was pretty unspectacular. The Task Add css classes to all nav menu items inside a specific Nav Menu that was added via (admin UI) Appearance > Menu. The function <code> function wpse4388_navmenu_classes( $items, $menu, $args ) { // prevent crashing the appearance &gt; menu admin UI if ( is_admin() ) return; # &gt;&gt;&gt;&gt; start editing // Nav menu name you entered in the admin-UI &gt; Appearance &gt; Menus (Add menu). $target['name'] = 'Topnav'; // A targeted menu item that needs a special class - add the item number here $target['items'] = array( (int) 6 ); # &lt;&lt;&lt;&lt; stop editing // filter for child themes: "filter_nav_menu_{nav menu name}" // the nav menu name looses all empty spaces and is set to lower // if you want to use the filter, hook your child theme function into 'after_setup_theme' $target = apply_filters( 'filter_nav_menu_'.strtolower( str_replace( " ", "", $target['name'] ), $target ); // Abort if we're not with the named menu if ( $menu-&gt;name !== $target['name'] ) return; foreach ( $items as $item ) { // Add the class for each menu item $item-&gt;classes = 'classes for all items'; // Append this class if we are in one of the targeted items if ( in_array( (int) $item-&gt;menu_order, $target['items'] ) ) $item-&gt;classes .= ' only for a single item'; } return $items; } add_filter( 'wp_get_nav_menu_items', 'wpse4388_navmenu_classes', 10, 3 ); </code> Was it helpful? Don't forget to vote up! :)
I'm going to start by saying something similar to Horttcore.. Is there a reason you can't simply provide a differing container element for the given menu, it should provide enough specificity to style it uniquely. Although, you could do something like this to conditionalise menu args based on the menu's location.. <code> function my_wp_nav_menu_args( $args = '' ) { if( $args['theme_location'] == 'your-specific-location' ) $args = array_merge( array( 'container_class' =&gt; 'example', 'menu_class' =&gt; 'example2' ), $args ); return $args; } add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' ); </code> Above code is based on the example given on the codex page for <code> wp_nav_menu </code> , and could easily be extended to do any number of things. http://codex.wordpress.org/Function_Reference/wp_nav_menu Hope that helps..
How to add (css) classes to only one wp_nav_menu()?
wordpress
I've created some custom metaboxes for my post write screen. Is there any way to make some of them display collapsed by default? Just in case I'm not using the correct terms or not being clear in my question I will elaborate: The metaboxes on the post write screen have a toggle switch in the upper right hand corner of the box. If you mouse over this area, it shows a little downward arrow and the words "Click to toggle". When you click it, the metabox collapses, hiding the contents and only showing the metabox's title bar. I am not talking about the Screen Options which make the entire metaboxes disappear (only on the given account). I just want certain metaboxes to display in the collapsed mode by default for all WP users. UPDATE: After reading in Hakre's answer that they toggle state is stored for the user I wanted to add some clarification on how I'd like it to work. I'm not sure if this is possible but I'd like the metaboxes to default to collapased when the post is new, then as the user expands them they should expand, however I want those settings to stay local to the specific post, so when they create a new post all of the metaboxes are collapsed.
To display a metabox collapsed or closed by default, it is good to know that adding <code> closed </code> to it's class attribute will display it closed. All meta-boxes main divs that have <code> closed </code> in their classname, are displayed in the closed form. When the arrow is clicked it will be removed or added (toggled). This is done interactively on the post editor page. Manually adding the <code> closed </code> classname does only work if you do that in your browser with a developer tool like firebug or similar. As Wordpress normally tracks the status of the toggle state of each metabox, you should take care to only initially set the toggle state to close the first time a specific user is visiting the editor or is added to users. The data which of those metaboxes are closed is stored inside the users options, each time you toggle a box, there will be an ajax request that is storing it: <code> update_user_option($user-&gt;ID, "closedpostboxes_$page", $closed, true); </code> <code> $closed </code> is a comma-seperated list of all metaboxes IDs that are closed. <code> $page </code> is set to "post" for the post editor (the one you asked for). So when a new user is created (or the plugin is installed for all existing users), you can extend that setting with the ID of your metabox. This should do the job. The only thing you need to know is the ID of your metabox, but I'm pretty sure you know that one already. If not, check your code where you register the metabox. Additionally, next to the ones that are closed, you can also set those which are hidden btw, which would correspond to the checkboxes. It's the <code> hiddenpostboxes_$page </code> option then. Update Some code snipped on how to add the option: <code> function collapseBoxForUser($userId, $page, $boxId) { $optionName = "closedpostboxes_$page"; $close = get_user_option($optionName, $userId); $closeIds = explode(',', $close); $closeIds[] = $boxId; $closeIds = array_unique($clodeIds); // remove duplicate Ids $close = implode(',', $closeIds); update_user_option($userId, $optionName, $close); } </code> just call that function with the proper values and it will insert your boxId into the value. Next time the editor is loading that value for the screen (e.g. via an ajax request), it should display that box closed.
Make Custom Metaboxes Collapse by Default
wordpress
I have a multi lingual site. On the site I want to display youtube movies using fancybox (or any other equivalent solution) The plugin is installed and set. When checked on the He version - all works well. On En on the other side, it redirects to youtube. EN: http://www.mtbsuisse.com/en/category/videos/ HE: http://www.mtbsuisse.com/category/videos/ Any idea why this happens ? I am using qtranslate for the multilingual support *Changed site default to HE for now
Got a different solution. Just replaced wp-fancybox-easy with wp-lightpop . Wp-lightpop works wonderfully out of the box. 2 changed I needed to do were: 1. go to the setting page and change the links to be displayed as popup (otherwise it's open the language navigation links as overlay) 2. change box style (look&amp;feel) Problem solved :-)
Fancy-box Esay wordpress plugin fails to work on Multilingual site
wordpress
I'm getting the feeling that adding Widgets via MySQL query is not as simple as I thought. I was under the impression all data is stored in the <code> options </code> table, but it seems like I was wrong. Any idea how to place a widget via $wpdb? What data should be written down? And where? Thanks!
Placing widgets via a MySQL or something MySQL abstracted via the global variable <code> $wpdb </code> that is an instance of the WPDB class is not trivial. That's not because MySQL is something complicated or because <code> $wpdb </code> is useless at all but this has do something with the way the widget configuration is stored inside the mysql database options tables. But there is always a work around. The nature of the widget configuration is stored inside the mysql database options tables. Just read the widgets configuration out of the option ( get_option ), edit it as you wish (use var_dump to inspect how that array is used) and then store it back into mysql via update_option . That done you should be able to edit this "via mysql" (e.g. in the database) while making the settings of your wish. This is quite a quick answer but it probably solves your issue.
Placing a widget with $wpdb query
wordpress
Is there any filter which can be used in a plugin to process the content of the text widget before it is rendered?
Filter widget_text (for the text) widget_title (for the title) Example <code> function add_smiley($content) { $new_content = ''; $new_content.= $content . ':)'; return $new_content; } add_filter('widget_text', 'add_smiley'); </code> Note that this works only for the content so not if you have a widget with only a title. Reference http://codex.wordpress.org/WordPress_Widgets stackexchange-url ("stackexchange-url stackexchange-url ("stackexchange-url
Is There A Hook To Process The Content Of The Text Widget?
wordpress
Is there a WP plugin that allows user to edit in-page footnotes in WYSIWYG manner? No weird syntax. No HTML pane. Update: Perhaps I'm missing something, as I'm new to WP. All footnote plugins that I saw use custom syntax. Example: <code> Blah blah blah ((my footnote)) blah </code> Other: <code> Blah blah blah [ref]my footnote[/ref] </code> I need plugin that will allow user to edit footnotes visually, like Word does.
From all the footnote plugins that I'm aware of, they don't provide the functionality you're looking for. It's normally expected that a user edits the footnotes content in the place where the footnote is edited in the current plugins. But the list is pretty impressive. So probably you might want to look on your own: Footnote Wordpress Plugins .
WYSIWYG-able Footnote Plugin
wordpress
After i add these codes to functions.php: <code> add_editor_style(); function childtheme_mce_btns2($orig) { return array('formatselect','styleselect', 'underline', 'justifyfull', 'forecolor', '|', 'pastetext', 'pasteword', 'removeformat', '|', 'media', 'charmap', '|', 'outdent', 'indent', '|', 'undo', 'redo', 'wp_help' ); } add_filter( 'mce_buttons_2', 'childtheme_mce_btns2', 999 ); function childtheme_tiny_mce_before_init( $init_array ) { $init_array['theme_advanced_styles'] = "box note=box_note;box info=box_info;box warning=box_warning;box download=box_download"; return $init_array; } add_filter( 'tiny_mce_before_init', 'childtheme_tiny_mce_before_init' ); </code> I had a style drop down menu in Wordpress Visual Editor with "box note,box info,box warning,box download" options. I created editor-style.css so i got css support for those classes in visual editor. If i select "box note" style example, wordpress putting it as <code> &lt;p class="box_note"&gt;&lt;/p&gt; </code> Problem is when i push enter button for line breaking, wordpress putting <code> &lt;p&gt;&lt;/p&gt; </code> automatically. Basically how can i change those styles using <code> &lt;div&gt; &lt;span&gt; </code> or anything except <code> &lt;p&gt; </code> ? Update: I create some screenshots for you. This is when i select style from style list: http://www.unsalkorkmaz.com/sorun/sorun1.jpg This is when i push enter button for line breaking: http://www.unsalkorkmaz.com/sorun/sorun2.jpg Wordpress basically creating different <code> &lt;p&gt; </code> I tried; <code> remove_filter('the_content', 'wpautop'); remove_filter('the_content', 'wptexturize'); remove_filter('the_content', 'convert_smilies'); remove_filter('the_content', 'convert_chars'); </code> before i create this question but its not the solution seems. Update 2: Well.. I tried shift+enter to line-break and it works! So i dont know what is difference with enter vs shift+enter in TinyMCE but i want shift+enter function as default of enter button.
If you always want <code> &lt;br/&gt; </code> instead of <code> &lt;p&gt; </code> for newlines you can change the TinyMCE configuration : <code> forced_root_block: false, force_br_newlines: true, force_p_newlines : false, </code> I think you cannot do this based on the context (use <code> &lt;br/&gt; </code> when in <code> class="box_note" </code> , <code> &lt;p&gt; </code> otherwise), but it is an interesting question for the TinyMCE forum . Shift + Enter is indeed the standard way to differentiate between paragraph and line endings.
Theme Advanced Styles in Visual Editor and Paragraphs
wordpress
I'm working on a personal voting plugin, I don't intend to release it publicly because I'm still learning WP. In general, you can vote posts "up" or "down". I have 2 tables, one collects IPs (to disallow voting multiple times) and another table named "post_votes" collects the number of votes for each post. When I publish a new post its ID is stored in "post_votes" and I can update the "up", "down" for each post when people vote. This worked a few days ago. I did some modifications and I can't figure out why it's not working anymore.. This is the entire code so far.. I still need to implement some security precautions. <code> &lt;?php /* Plugin Name: Vote Posts */ global $vote_posts_version; $vote_posts_version = "1.0"; function vote_posts_install () { global $wpdb; global $vote_posts_version; $table_1 = $wpdb-&gt;prefix . "voter_ips"; $table_2 = $wpdb-&gt;prefix . "vote_posts"; if($wpdb-&gt;get_var("SHOW TABLES LIKE '$table_1 AND $table_2'") != $table_1 &amp;&amp; $table_2) { $sql = "CREATE TABLE " . $table_1 . " ( id bigint(20) NOT NULL AUTO_INCREMENT, vote_post_id bigint(20) NOT NULL, voter_ip varchar(100) NOT NULL, UNIQUE KEY id (id) );"; $sql2 = "CREATE TABLE " . $table_2 . " ( id bigint(20) NOT NULL AUTO_INCREMENT, vote_post_id bigint(20) NOT NULL, up int(11) NOT NULL, down int(11) NOT NULL, UNIQUE KEY id (id) );"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); dbDelta($sql2); add_option("vote_posts_version", $vote_posts_version); } } register_activation_hook(__FILE__,'vote_posts_install'); //add and delete votes function add_votes($post_ID) { global $wpdb; if (!($wpdb-&gt;get_row("SELECT vote_post_id FROM wp_vote_posts WHERE vote_post_id = $post_ID" ) ) ) { //if not exists add post ID to table $wpdb-&gt;insert( $wpdb-&gt;prefix . 'vote_posts', array( 'post_id' =&gt; $post_ID ) ); return $post_ID; } } add_action ( 'publish_post', 'add_votes' ); //should trigger function on publish post function delete_votes($post_ID) { global $wpdb; $wpdb-&gt;query("DELETE FROM wp_vote_posts WHERE vote_post_id = $post_ID"); return $post_ID; } add_action ( 'delete_post', 'delete_votes' ); //deletes row from post_votes table when a post is deleted from the WP panel ?&gt; </code> It successfully creates the 2 tables but doesn't insert the post ID on action
No offense, but I think I'm agreeing with a commenter from your other question... You really need to read PHP, MySQL, and regular expression tutorials before you get into any of this. More importantly, you need to learn how to search a code base using regular expressions in your favorite editor, and understand the code you're reading. Just to give you a few examples, this: <code> SHOW TABLES LIKE '$table_1 AND $table_2' </code> Is looking for a table called: <code> $wpdb-&gt;prefix . "voter_ips AND " . $wpdb-&gt;prefix . "vote_posts" </code> Bad, bad, bad... Along the same lines, while your tables both have a not null unique key, which technically amounts to a primary key, the MySQL rewrite engine and optimizer don't treat those in the same way as primary keys, so you should declare it as such instead. Then, there are the potential security holes: <code> SELECT vote_post_id FROM wp_vote_posts WHERE vote_post_id = $post_ID </code> ... without casting $post_ID to (int) beforehand... It also helps to var_dump() stuff if you're not using a PHP debugger. e.g. in your add_votes() call, how about this, to see what's happening?: <code> var_dump($post_ID);die; </code>
add_action for publish_post doesn't work
wordpress
How can I get the archive links for a custom post type? get_day_link() doesn't seem to work
From the top of my head, <code> get_day_link() </code> does not work for custom post types. This might work in 3.1 as you can add archives to your custom post types.
Custom post type - get_day_link()
wordpress
By default, Wordrpess sites have at least 2 URLs that can be used to reach the home page: <code> www.site.com/ www.site.com/hello-world </code> Both these URLs point to the same page, the default "hello world" post that WordPress creates. How can theme developer's specify a canoninical url meta tag to suggest to search agents which URL it should index in the above example? In your answer, please include an example for each choice: one in which site.com is preferred and one in which site.com/hello-world is preferred.
You might probably want to install Canonical URL’s for WordPress (Wordpress Plugin) . It allows you to specify a canonical URL for each post and page. So you can configure the way you want. The plugin is not big, you probably can integrate the functionality easily into your theme then.
How to use Canonical URL meta tag to avoid duplicate content issues with WP home pages
wordpress