question
stringlengths
0
34.8k
answer
stringlengths
0
28.3k
title
stringlengths
7
150
forum_tag
stringclasses
12 values
I'm trying to upload my plugin for the first time to the WordPress SVN. I've been granted access from the WordPress team. I am able to download the directory. Then I try to place my plugin files into the <code> trunk </code> folder, and then commit the changes. When I do this. I am prompted for my login credentials. I use the same ones that I use on the Wordpress.org website. However, it keeps re-prompting me to enter my credentials. I am not sure what I am doing wrong. I made a screencast of the process. http://www.screencast.com/t/3QCfSdyM
Try changing your password @ wordpress.org then retry. If still fails check your firewall log If it still fails ... ask Andrew Nacin :) http://twitter.com/#!/blamenacin :)
Commit changes to WordPress Plugin SVN with TortoiseSVN
wordpress
I have a php function that executes inside an add_meta_box() in the WP content editor (see below) that I would like to convert to javascript so that it executes on a button click (on demand vs automatic on load) to convert the post content in real time (without posting to the server). Is there an equivalent method set in javascript? <code> add_meta_box('mycontentfilter', __('My Content Filter'), 'my_content_filter', 'post', 'side', 'high'); function my_content_filter() { global $post; $mykeyword = 'find this phrase'; $post-&gt;post_content = preg_replace_callback("/\b($mykeyword)\b/","doReplace", $post-&gt;post_content); } // the callback function function doReplace($matches) { static $count = 0; switch($count++) { case 0: return '&lt;b&gt;'.$matches[1].'&lt;/b&gt;'; // 1st instance, wrap in bold case 1: return '&lt;em&gt;'.$matches[1].'&lt;/em&gt;'; // 2nd instance, wrap in italics case 2: return '&lt;u&gt;'.$matches[1].'&lt;/u&gt;'; // 3rd instance, wrap in underline default: return $matches[1]; // don't change others. } } </code>
Hi @Scott B : This is really more of a StackOverflow question than a WordPress Answers question. I'll take a stab at it but if this is not what you need I'd suggest deleting your question here and putting it up at SO. The <code> Replace() </code> function in Javascript can take a function as an argument. Ben Nadel (who is a bonafide jQuery/Javascript rockstar, at least in my book) has a great article covering how to use <code> Replace() </code> with a callback (look for the subhead "Javascript String Replace() - Function Replace" ): Using Regular Expressions In Javascript (A General Overview)
Does javascript have an equivalent to PHP's preg_replace_callback?
wordpress
I need to embed an iFrame into a post and it appears that tinyMCE or something is stripping it out when I go from HTML to Visual view while editing a post. I've found instructions for adding valid elements to tinyMCE but it only seems to apply to WordPress 2.8. No such file seems to exist under WordPress 3.0.1 (see stackexchange-url ("Make WordPress WYSIWYG not strip out iframe&#39;s")) None of the iFrame embedding plugins seem to support WP 3.0.1 either. Thanks for any tips.
Did you try this solution: stackexchange-url ("stackexchange-url
Embed iFrame in WordPress 3.0.1
wordpress
I was wondering if you really need to escape user submitted data (widget option fields) within the widget() and form() functions (from the widget class) ? I don't see a reason to do this, if the data is already escaped in the update() function. Or am I missing something?
Mm, they're not slashed, if that's what your meaning. However, they're definitely not xss-sanitized. Use kses before saving, or esc_attr() on display, if you're dealing with untrusted data.
Do widget options need to be escaped widget()?
wordpress
( Moderator's note: The original title was "Copy and Paste picture in post without linking to original") When I copy and paste a picture from another editor window it appears nicely but it links to the original location. Is there a plugin which lets me copy and paste images in a post (like it happens in Windows Live Writer) so that the image gets uploaded to the uploads dir? Or is that impossible in a web environment? Reason: the one thing why I keep returning to Windows Live Writer for initial postings is the image functionality. If I could somehow make this process easier I could write some posts in the WordPress backend instead. Update: If it does NOT exist yet, I probably will write a plugin on a hook that fires after a new or update of a post, goes through the_content, finds all image url's that are not the same as the preferred root domain (for multisite) and if not, does a cross-load of the image (as e.g. in the swift theme) and then replaces the url with the newly uploaded image. However... since this is a basic thought someone must already have made this I just cant find it in the plugin directory (yet). Update 2 : Let me try this one: http://blog.milandinic.com/wordpress/plugins/cache-images/ Update 3 : The above plugin works perfectly even in my WordPress Multisite environment.
@Jan: The cache images plugin: http://blog.milandinic.com/wordpress/plugins/cache-images/ helped me with this, it does not on demand replace the links but rather goes through all links but basically does the same. One note on this: when I ran it on a small blog it worked pretty well. On another blog (http://edward.de.leau.net) it did a lot of posts but then somewhere in the middle it began replacing ALL images so including the ones that were under http://edward.de.leau.net .... I havent investigated that one I just broke it off. So be careful when you run large batches with this one and keep checking the replace logging screen. update the new version of the plugin allows on-demand side loading, see: http://weblogtoolscollection.com/archives/2010/11/28/wordpress-plugin-releases-for-1128-2/#comments
Retrieving and Storing Images Linked from Other Domains on Local Server?
wordpress
I'm in the process of setting up a (potentially) large multisite network, and I'm looking to make it as easy as possible now to add and configure sites when needed. I'm currently at the phase where I'm dealing with plugins. With multisite I am aware of several different ways you can activate plugins Put the plugin in <code> /plugins </code> , activate it on every site invidually Put the plugin in <code> /plugins </code> , use 'network activate' to activate it on all sites Put the plugin in <code> /mu-plugins </code> , automatically activated on every site Now, I've been playing with the settings and I want to activate Akismet on all sites but one or two. I thought I would be able to network activate the plugin and then disable it on a single site, but I am unable to do so - if I use network activate then there is only the option to 'network deactivate' - which deactivates the plugin across all sites. Is there a way to have the handy functionality of network activate but yet still have the convenience of being able to deactivate plugins on a site-by-site basis?
You can use the filter <code> site_option_* </code> . E.g. the following will disable akismet on blog with id 2. <code> add_filter('site_option_active_sitewide_plugins', 'modify_sitewide_plugins'); function modify_sitewide_plugins($value) { global $current_blog; if( $current_blog-&gt;blog_id == 2 ) { unset($value['akismet/akismet.php']); } return $value; } </code>
How to disable a network enabled plugin for just one site?
wordpress
Trying to print my custom post type's taxonomy but without the link. Tried this, but doesn't seem to work, any suggestions? <code> $text = the_terms($post-&gt;ID,'type','','',''); echo strip_tags($text); </code> Any help would be greatly appreciated... I'm about to start punching babies.
You could use a filter and <code> strip_tags() </code> , as you suggested. Example using post tags, since that's the taxonomy I had available: <code> function my_remove_links( $term_links ) { return array_map('strip_tags', $term_links); } add_filter('term_links-post_tag', 'my_remove_links'); </code> Really though, I would just <code> get_the_terms() </code> and and craft the output yourself: <code> function the_simple_terms() { global $post; $terms = get_the_terms($post-&gt;ID,'post_tag','',', ',''); $terms = array_map('_simple_cb', $terms); return implode(', ', $terms); } function _simple_cb($t) { return $t-&gt;name; } echo the_simple_terms(); </code>
Strip tags from a the terms() function
wordpress
( Moderator's note: The original title was: "Shrink full size images in post") I built a WordPress site for someone and they entered a ton of posts with images that are wider than the content area. Is there a way to shrink all of the image attachements to use a max width? They are entered as "full size", not as thumbnail, medium, etc.
Hi @moettinger : Great question! WordPress lacks some of the higher level imaging management features that would make it file maintenance like you need so much easier. The core WordPress team has been threatening to add enhance image features for many versions; eventually they might actually do it! Until then you'll have to use a patchwork of plugins and/or custom code. More good news and bad news: The good news is WordPress combined with PHP has tons of lower level imaging handling features but the bad news is it has tons of lower level imaging handling features from which you have to decide which to use! A while back I posted a <a href="stackexchange-url list of image handling functions found in WordPress and if you'll scan it you'll probably see there are several different ways to skin this cat. That said, I picked one approach and it follows below with copious comments rather than explain here in the text. You can just copy it to the root of your website as something like <code> /downsize-images.php </code> and call it from your browser. If it times out, don't worry; I wrote it to keep track of what it had already done so just keep running it until you see it print "Done!" NOTE: You need to set the constant <code> MAX_RESIZE_IMAGE_TO </code> to whatever you want your maximum dimension to be; my example used <code> 640 </code> pixels. After it runs you'll have a bunch of image files with an extension of <code> .save </code> appended. Once you are happy that it ran like you wanted you can just delete those <code> .save </code> files. I didn't automatically delete them in case something went wrong with the script. ( IMPORTANT : Be SURE TO BACKUP both your database and your upload directory BEFORE you run this. It worked on my machine but you might have something I didn't test and it might cause corruption so backup! DO NOT come back later and say I didn't warn you!!!): <code> &lt;?php include "wp-load.php"; // Need this to load WordPress core include "wp-admin/includes/image.php"; // Needed for wp_create_thumbnail() define('MAX_RESIZE_IMAGE_TO',640); // SET YOUR MAX DIMENSION HERE!!!! // Check our "queue" to see if we've previously only run to partial competion. $attachment_ids = get_option('attachment_ids_to_resize'); if ($attachment_ids=='Done!') { // Make sure we don't do it again echo 'Already done.'; } else { if (empty($attachment_ids)) { // If this is the first time, this array will be empty. Get the IDs. global $wpdb; $attachment_ids = $wpdb-&gt;get_col("SELECT ID FROM {$wpdb-&gt;posts} WHERE post_type='attachment'"); } foreach($attachment_ids as $index =&gt; $attachment_id) { // Get metadata: [width,height,hwstring_small,file,sizes[file,width,height],image_meta[...]]: $metadata = wp_get_attachment_metadata($attachment_id); // Get upload_dir: [path,url,subdir,basedir,baseurl,error]: $upload_dir = wp_upload_dir(); // Get full path to original file $filepath = "{$upload_dir['basedir']}/{$metadata['file']}"; // Make a smaller version constrained by largest dimension to MAX_RESIZE_IMAGE_TO $smaller_file = wp_create_thumbnail( $filepath, MAX_RESIZE_IMAGE_TO); // If the file was really created if (@file_exists($smaller_file)) { // Append a ".save" to original file name, just in case (you can manually delete *.save) rename($filepath,"{$filepath}.save"); // Get this smaller files dimensions list($width,$height) = getimagesize($smaller_file); // Strip the base directory off the filename (i.e. '/Users/username/Sites/sitename/wp-content/uploads/') $metadata['file'] = str_replace("{$upload_dir['basedir']}/",'',$smaller_file); $metadata['height'] = $height; $metadata['width'] = $width; // Get the the small size, 128x96 or smaller if need be list($uwidth,$uheight) = wp_constrain_dimensions($metadata['width'], $metadata['height'], 128, 96); $metadata['hwstring_small'] = "height='$uheight' width='$uwidth'"; // Make sure none of the sizes are larger than the new size foreach($metadata['sizes'] as $size =&gt; $size_info) { if (intval($size_info['height'])&gt;intval($height) || intval($size_info['width'])&gt;intval($width)) { // If too large get the full file path of the sized image $old_file = "{$upload_dir['path']}/{$size_info['file']}"; // Tack a ".save" extension on it, just in case (you can manually delete *.save) rename($old_file,"{$old_file}.save"); // Remove it from the metadata since it's too large unset($metadata['sizes'][$size]); } } // Update the attachement metadata with the new smaller values wp_update_attachment_metadata($attachment_id,$metadata); // Update the name of the other place the orginal file name is stored update_attached_file($attachment_id,$metadata['file']); } // Remove this attachment from our "queue" unset($attachment_ids[$index]); // Save the new smaller "queue" in case we need to run this again. update_option('attachment_ids_to_resize',$attachment_ids); } // If we've actually processed them all if (count($attachment_ids)==0) { // Store a marker so we won't accidentally run this again update_option('attachment_ids_to_resize','Done!'); } echo 'Done!'; } </code>
Downsizing Many Large Images Attached to Posts, in Bulk?
wordpress
So what's the difference between these, and when should we use each one? Is esc_attr() safe enough to escape any type of data you get from the user ?
esc_attr() is, for the most part, an alias for a) kses (strips evil chars to prevent xss) and b) htmlspecialchars(), for use in HTML attributes. It can be used to display sanitized user input that cannot contain HTML. If you need only to sanitize strings before storing in the db, there are multiple variants of kses available. Also, don't miss the other esc_*() functions. There are quite a few. The other two you mention are self-explanatory.
difference between esc_attr(), strip_slashes(), strip_tags()?
wordpress
Is it possible to make custom page templates available from a plugin?
<code> get_page_template() </code> can be overridden via the <code> page_template </code> filter. If your plugin is a directory with the templates as files in them, it's just a matter of passing the names of these files. If you want to create them "on the fly" (edit them in the admin area and save them in the database?), you might want to write them to a cache directory and refer to them, or hook into <code> template_redirect </code> and do some crazy <code> eval() </code> stuff. A simple example for a plugin that "redirects" to a file in the same plugin directory if a certain criterium is true: <code> add_filter( 'page_template', 'wpa3396_page_template' ); function wpa3396_page_template( $page_template ) { if ( is_page( 'my-custom-page-slug' ) ) { $page_template = dirname( __FILE__ ) . '/custom-page-template.php'; } return $page_template; } </code>
Create custom page templates with plugins?
wordpress
I just decided to try using WordPress for a CMS (not a blog). The site will have some product information that I want the client to be able to update. Instead of creating an entire admin side just for them to update their products, is it possible to create a form in the WordPress admin so they can add products to a database? Is changing the WordPress admin side good practice?
Hi @drpcken : Absolutely! That's exactly what I've been doing for months now. ( There are some <a href="stackexchange-url screenshots here to show you what's possible.) Just create a Custom Post Type for your their products, and then use a plugin to allow to you create Custom Metaboxes with fields. Here's a list to consider: Plugins for Fields &amp; Metaboxes The plugin that I think is best at the moment is Simple Fields although I'd suggest you consider others: Simple Fields Easy Custom Fields Verve Meta Boxes Magic Fields (See Also) Plugins for Defining Post Types In addition you can simply define your custom post types with the <code> register_post_type() </code> function (which is how I prefer to do it, for many reasons not to least of which is it is easier to version control them with Subversion or Git if you do) or you can use one of these plugins which might be easier when you are new to custom post types: CMS Press Custom Post Type UI WP Easy Post Types (See Also) WP Post Type UI GD Custom Posts And Taxonomies Tools Ultimate Post Type Manager Note: Some of these plugins may actually let you define fields too and some of the fields plugins I mentioned above may let you manage custom post types as well. I've not had the time to research them all so if I need to move these around or embellish on my description, please let me know. Custom Post Type Archive Pages You'll also want to create archive pages for custom post types which will show up as a feature of WordPress 3.1 but until then these plugins might be useful (though I've not tried them): Simple Custom Post Type Archives Custom Post Type Archives Learning More About Custom Post Types There are getting to be a lot of references on custom post types, here are some I can suggest (I wrote the first two as answers where on WA) : On StackExchange <a href="stackexchange-url Tips for using WordPress as a CMS? <a href="stackexchange-url Implementing a CrunchBase.com Clone using WordPress? On WordPress Codex Custom Post Types "Supports" Reference for Custom Post Types Blog Posts Custom post types in WordPress 101 Techniques for a Powerful CMS using WordPress Rock-Solid WordPress 3.0 Themes using Custom Post Types WordPress Custom Post Types And Taxonomies The Right Way Custom Post Types in WordPress 3.0 Adding Custom Field GUI to Custom Post Types in WordPress 3.0 And here's some notes from a presentation I gave on Custom Post Types to the Atlanta WordPress Meetup group recently: Presentation Notes: Custom Post Types for WordPress
Creating my own Admin Forms in a WordPress CMS?
wordpress
I have 2 pages in my wordpress 3.0.1 site with 2 urls www.mysite.co.uk/sub-page/child-of-sub-page/accommodation/ and www.mysite.co.uk/accommodation/ however any link in my site to www.mysite.co.uk/accommodation/ goes to www.mysite.co.uk/sub-page/child-of-sub-page/accommodation/ instead is this a bug in wordpress 3.0.1? or is there a way round this?
I'm not seeing this behavior in my test install, using the page hierarchy you have described. I can access both the top-level accommodation page and the child page. Do you happen to have the Redirection plugin installed?
URL redirect problem
wordpress
I'm building a site where users log in to view content specific to them. I would like to display the last date and time they logged in. How would I get this information from wordpress? If it doesn't exist, how could I add it? Example: Welcome Back! Your last visit was on 10/25/2010 at 3:14pm. Thanks!
I don't see anything like it in the database, so you probably have to do this yourself. To save the last login time , you can hook into the <code> wp_login </code> action , and save a user meta value (like <code> [myprefix]_lastlogintime </code> ). You first read this value, so you get the previous login time, save this in the session, and then save the new login time. On the regular admin pages you check whether this session variable is set. If it is, you display the welcome text and clear the session variable so you don't display it on every page. If you want to save the last page visit time you have to write to the database on every (admin) page view. This is possible, but I would not recommend it. You can also save something once on logout ( action <code> wp_logout </code> ), but probably not everyone will remember to log out.
Last time a user logged in
wordpress
I'm making a list of suggestion here . I need to insert current date/time for each of my suggestions - they are added accumulatively. If you have any idea on doing that, please share.
You're on WordPress.com, so there's no way to add functionality that will allow you to do this. You could always type the date/time manually whenever you update it.
How to insert current date/time in the content of a post?
wordpress
I had this working a couple of weeks ago and the only thing I can think is that WordPress has updated and broken the functionality? I followed the tutorial here to add custom fields: http://net.tutsplus.com/tutorials/wordpress/rock-solid-wordpress-3-0-themes-using-custom-post-types/ It was working fine (I entered about 50 custom posts all with custom fields) but when I go to edit it today any changes I make to the custom fields are not being saved, although other changes work fine. Does anyone know if this is a known bug? Edit: Here is the code, added in functions.php to a brand new install (theme: twentyten) <code> add_action('init', 'testimonials_register'); add_action("admin_init", "admin_init"); add_action('save_post', 'save_testimonial'); function testimonials_register() { $args = array( 'label' =&gt; __('Testimonials'), 'singular_label' =&gt; __('Testimonial'), 'public' =&gt; true, 'show_ui' =&gt; true, 'capability_type' =&gt; 'post', 'menu_position' =&gt; 5, 'hierarchical' =&gt; false, 'rewrite' =&gt; true, 'supports' =&gt; array('title', 'editor', 'thumbnail','custom-fields', 'revisions', 'excerpt', 'page-attributes') ); register_post_type( 'testimonials' , $args ); } register_taxonomy( 'testimonial_project_type', array("testimonials") , array( 'hierarchical' =&gt; true, 'label' =&gt; 'Project Type', 'query_var' =&gt; true, 'rewrite' =&gt; true ) ); function admin_init(){ add_meta_box("testimonialInfo-meta", "Testimonial Options", "meta_options_testimonial", "testimonials", "advanced", "high"); } function meta_options_testimonial(){ global $post; $custom = get_post_custom($post-&gt;ID); $name = $custom["name"][0]; $position = $custom["position"][0]; $project_url = $custom["project_url"][0]; $website = $custom["website"][0]; ?&gt; &lt;label for="name" style="width:90px;display:inline-block"&gt;Name:&lt;/label&gt; &lt;input size="50" name="name" id="name" value="&lt;?php echo $name; ?&gt;" /&gt;&lt;br&gt; &lt;label for="position" style="width:90px;display:inline-block"&gt;Position:&lt;/label&gt; &lt;input size="50" name="position" id="position" value="&lt;?php echo $position; ?&gt;" /&gt;&lt;br&gt; &lt;label for="website" style="width:90px;display:inline-block"&gt;Website Name:&lt;/label&gt; &lt;input size="50" name="website" id="website" value="&lt;?php echo $website; ?&gt;" /&gt;&lt;br&gt; &lt;label for="project_url" style="width:90px;display:inline-block"&gt;Project slug:&lt;/label&gt; &lt;input size="50" name="project_url" id="project_url" value="&lt;?php echo $project_url; ?&gt;" /&gt; &lt;small&gt;E.g. 'parker-harris'&lt;/small&gt;&lt;br&gt; &lt;?php } function save_testimonial(){ $custom_meta_fields = array( 'project_url','name','position','website'); foreach( $custom_meta_fields as $custom_meta_field ): if(isset($_POST[$custom_meta_field]) &amp;&amp; $_POST[$custom_meta_field] != ""): update_post_meta($post-&gt;ID, $custom_meta_field, $_POST[$custom_meta_field]); endif; endforeach; } add_filter("manage_edit-testimonials_columns", "testimonials_edit_columns"); add_action("manage_posts_custom_column", "testimonials_custom_columns"); function testimonials_edit_columns($columns){ $columns = array( "cb" =&gt; "&lt;input type=\"checkbox\" /&gt;", "title" =&gt; "Testimonial Title", "name" =&gt; "Name", "description" =&gt; "Excerpt", "project_url" =&gt; "Project Slug" ); return $columns; } function testimonials_custom_columns($column){ global $post; switch ($column) { case "name": $custom = get_post_custom(); echo $custom["name"][0].", ".$custom["position"][0]."&lt;br&gt; ".$custom["website"][0]; break; case "description": the_excerpt(); break; case "project_url": $custom = get_post_custom(); echo "&lt;a target='_blank' href='/portfolio/".$custom["project_url"][0]."'&gt;".$custom["project_url"][0]."&lt;/a&gt;"; break; } } // This shows testimonials in blog and feed. add_filter( 'pre_get_posts', 'my_get_posts' ); function my_get_posts( $query ) { if ( is_home() &amp;&amp; false == $query-&gt;query_vars['suppress_filters'] || is_feed() ) $query-&gt;set( 'post_type', array( 'post', 'testimonials') ); return $query; } </code>
I put your code in a plugin and had to change two things to get it working: In <code> save_testimonial() </code> , you use <code> $post </code> but don't declare it as a global. So <code> $post-&gt;ID </code> will be empty, and <code> update_post_meta() </code> does not know what to save. Add <code> global $post; </code> at the beginning of the function. <code> register_taxonomy() </code> is not in your <code> init </code> handler, and is probably called too early (if it is a plugin, maybe you were lucky when you did this in <code> functions.php </code> ). Move it to the <code> testimonals_register() </code> function. Did you have <code> WP_DEBUG </code> set to <code> TRUE </code> when you were debugging it? Then you should have gotten the warnings that lead me to this solution.
Custom fields not saving in newest Wordpress 3.0.1
wordpress
Is there a way to show no gravatar in comment list for the commenters that are not registered at gravatar.com? As much as I saw, gravatar.com doesn't return a special code when no avatar is registered. The temporary, not so elegant solution I applied for the moment is displaying a transparent 1x1px gif but I'd like to return no image if possible. I've also tried 3-4 gravatar plugins but none does this properly.
This plugin hides all avatar images, and preloads them in Javascript, so client side, which should activate the browser cache. If the image exists, the avatar is replaced and made visible. If it does not exist, nothing happens and the avatar image stays hidden. Tested in Safari and Firefox on Mac. <code> &lt;?php /* Plugin Name: WPA 3366 Plugin URI: stackexchange-url How to display nothing (instead default) when no user gravatar is present? Version: 1.0 Author: Jan Fabry */ $avatar_collection = array(); function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) { if ( ! get_option('show_avatars') ) return false; if ( false === $alt) $safe_alt = ''; else $safe_alt = esc_attr( $alt ); if ( !is_numeric($size) ) $size = '96'; $email = ''; if ( is_numeric($id_or_email) ) { $id = (int) $id_or_email; $user = get_userdata($id); if ( $user ) $email = $user-&gt;user_email; } elseif ( is_object($id_or_email) ) { // No avatar for pingbacks or trackbacks $allowed_comment_types = apply_filters( 'get_avatar_comment_types', array( 'comment' ) ); if ( ! empty( $id_or_email-&gt;comment_type ) &amp;&amp; ! in_array( $id_or_email-&gt;comment_type, (array) $allowed_comment_types ) ) return false; if ( !empty($id_or_email-&gt;user_id) ) { $id = (int) $id_or_email-&gt;user_id; $user = get_userdata($id); if ( $user) $email = $user-&gt;user_email; } elseif ( !empty($id_or_email-&gt;comment_author_email) ) { $email = $id_or_email-&gt;comment_author_email; } } else { $email = $id_or_email; } /* if ( empty($default) ) { $avatar_default = get_option('avatar_default'); if ( empty($avatar_default) ) $default = 'mystery'; else $default = $avatar_default; } */ $default = '404'; if ( !empty($email) ) $email_hash = md5( strtolower( $email ) ); if ( is_ssl() ) { $host = 'https://secure.gravatar.com'; } else { if ( !empty($email) ) $host = sprintf( "http://%d.gravatar.com", ( hexdec( $email_hash{0} ) % 2 ) ); else $host = 'http://0.gravatar.com'; } if ( 'mystery' == $default ) $default = "$host/avatar/ad516503a11cd5ca435acc9bb6523536?s={$size}"; // ad516503a11cd5ca435acc9bb6523536 == md5('unknown@gravatar.com') elseif ( 'blank' == $default ) $default = includes_url('images/blank.gif'); elseif ( !empty($email) &amp;&amp; 'gravatar_default' == $default ) $default = ''; elseif ( 'gravatar_default' == $default ) $default = "$host/avatar/s={$size}"; elseif ( empty($email) ) $default = "$host/avatar/?d=$default&amp;s={$size}"; elseif ( strpos($default, 'http://') === 0 ) $default = add_query_arg( 's', $size, $default ); if ( !empty($email) ) { $out = "$host/avatar/"; $out .= $email_hash; $out .= '?s='.$size; $out .= '&amp;d=' . urlencode( $default ); $rating = get_option('avatar_rating'); if ( !empty( $rating ) ) $out .= "&amp;r={$rating}"; $comment_id = get_comment_ID(); $avatar = "&lt;img alt='{$safe_alt}' src='about:blank' class='avatar avatar-{$size} photo avatar-{$email_hash} avatar-hidden' height='{$size}' width='{$size}' style='display: none' id='avatar-{$comment_id}'/&gt;"; $GLOBALS['avatar_collection'][$out][] = $comment_id; } else { // Empty email: never show an avatar $avatar = ''; // $avatar = "&lt;img alt='{$safe_alt}' src='{$default}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' /&gt;"; } return apply_filters('get_avatar', $avatar, $id_or_email, $size, $default, $alt); } add_filter('wp_print_footer_scripts', 'add_avatar_footer_script'); function add_avatar_footer_script() { global $avatar_collection; if (empty($avatar_collection)) { return; } $avatar_data = json_encode($avatar_collection); echo &lt;&lt;&lt;EOF &lt;script type="text/javascript"&gt; (function (avatars) { for (var url in avatars) { var avatarImageObj = new Image(); avatarImageObj.onload = function(e) { var avatarIds = avatars[e.target.src]; for (var i = 0; i &lt; avatarIds.length; i++) { var avatarImageEl = document.getElementById('avatar-' + avatarIds[i]); avatarImageEl.src = e.target.src; avatarImageEl.style.display = "block"; } } avatarImageObj.src = url; } })({$avatar_data}); &lt;/script&gt; EOF; } </code>
How to display nothing (instead default) when no user gravatar is present?
wordpress
Picasa and Flickr provide Photo service. Is there any service for swf files so that i could share and use swf file in my blog? I don't like to upload swf on my wordpress hosting. I believe Google, Microsoft and Yahoo services only.
Would a generic file sharing and hosting site work? If you place the file in a public Dropbox folder and reference it from your site? See the Web Applications Stack Exchange for stackexchange-url ("more online file storage providers"). Make sure you check the Cross-domain policy : if the Flash file hosted on <code> dropbox.com </code> needs to access data from <code> yourdomain.com </code> , you need a <code> crossdomain.xml </code> file on <code> yourdomain.com </code> that specifies that Flash files from <code> dropbox.com </code> are allowed to access data.
Free swf files hosting for wordpress blog
wordpress
I am looking for what code one would need to add into the functions.php file which would allow specific metaboxes to show up in tags instead of within their individual metaboxes. Can anyone help with this?
Maybe you can inspect http://wordpress.org/extend/plugins/editor-tabs/
Placing Admin Post Metaboxes in Tabs
wordpress
I'm trying to show the latest posts using the <code> get_query_var </code> function. The function filters the posts according to their category. When I'm displaying the posts on the page they appear unsorted although I've added the <code> $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; </code> <code> $args=array( </code> <code> 'category__in'=&gt;array( $cat), </code> <code> 'order' =&gt; ASC, </code> <code> 'caller_get_posts' =&gt; 1, </code> <code> 'paged'=&gt;$paged, </code> <code> 'orderby' =&gt; date, </code> <code> ); </code> <code> query_posts($args); </code> How can I sort properly?
If something unexpected happens between <code> query_posts() </code> and <code> get_post() </code> , it is probably a plugin that hooks into the query and modifies it. Try disabling all plugins to see whether the problem disappears. Re-enable them one by one until you see the problem, that is the plugin that causes it.
blog posts sorting doesnt work while using get_query_var
wordpress
Hi I have made an sql query that gets several posts according the parameters that i've selected. I'm showing these posts but the inner paging within wordpress doesnt do anything. It shows me that there are more pages but when i select the page number it shows me the same results as before. That makes sense because it probably runs the sql query again. I'm using WordPress and BuddyPress. How can i page between these query results? UPDATE: here is the code im using <code> $sql = "SELECT post_title, post_date, post_excerpt, guid, ID FROM wp_posts,wp_term_taxonomy, wp_terms, wp_term_relationships WHERE (post_status = 'publish' or post_status = 'inherit') and wp_term_taxonomy.term_taxonomy_id = ".$cat." and wp_posts.ID = wp_term_relationships.object_id and wp_terms.term_id = wp_term_taxonomy.term_taxonomy_id and wp_term_relationships.term_taxonomy_id = wp_term_taxonomy.term_taxonomy_id and wp_term_taxonomy.taxonomy = 'category' ORDER by post_date DESC"; $matching_posts = $wpdb-&gt;get_results($sql,OBJECT); &lt;?php if ( have_posts() ) : ?&gt; &lt;?php foreach ($matching_posts as $post): ?&gt; &lt;?php setup_postdata($post); </code> then im showing the info i want like title.
You need to use get_posts(), have_posts(), and the_post() for the API functions to work.
mysql query paging
wordpress
I'm updating programmatically posts in a WP 3.01 install, using custom made tools. Sometimes I do change programmatically <code> post_status </code> from DRAFT to PUBLISHED using custom <code> SELECT </code> queries, however this seems spoiling posts permalinks. When in a DRAFT state, posts have the following link structure <code> http://myblog.com/?p=73006 </code> Could there be some "trick" to force a change in the link structure, generating the proper permalink?
You need to programmatically set the slug as you do so. An SQL trigger could do the trick. Don't forget to mind duplicate slugs as you write it. Else, instead of publishing using the database, write a php script that calls the WP API.
Create slugs programmatically
wordpress
I have a custom meta box which I would like to use to report on the markup of the current post or page (number of words, number of heading tags, etc). How can I obtain the post content into memory in order to parse and report on its content inside the meta box?
The callback for a meta box gets the current object (post, comment, link, ... depending on what you're editing) passed as the first parameter . So in your meta box handler you can read this first argument and access it's <code> post_content </code> to get the content.
How do I obtain the post content via a custom meta box inside the editor?
wordpress
I have a custom hierarchical taxonomy that is called 'Categories', but serves a different area of the site than the default "Categories" taxonomy. The problem I'm having is with selecting children terms in the interface while posting content. If the user selects and children terms, they move to the top of the Categories box and lose association and visual hierarchy with its parent. Here's an image showing what happens: I haven't set any unusual parameters that I know of, here's the register_taxonomy call: <code> register_taxonomy( "workshop_categories", 'workshop', array( "label" =&gt; "Categories", "singular_label" =&gt; "Category", "rewrite" =&gt; true, "show_ui" =&gt; "true", 'hierarchical' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'category') ) ); </code> Any input is appreciated!
This seems to be normal, it also happens for categories. The <code> wp_terms_checklist() </code> , which creates the checklist, has an argument <code> checked_ontop </code> , enabled by default. The metabox does not override this , so checked categories or custom terms always appear on top of the list. This does not affect their actual hierarchy, only how they are displayed there. It seems the remaining items of the hierarchy, that "lost" their parent, are added to the bottom. I do not think there is a sensible way to override this, unless you want to duplicate the whole meta box code.
Custom hierarchal taxonomy loses interface hierarchy when selecting parent & children
wordpress
I created a new blog using WordPress.com and obviously it got hosted on their server. But what I notice is that few features are not visible in this version as compared to the WordPress PHP script that I downloaded and hosted on my server. For example: the Plugins options is not visible anywhere from where I can upload any plugin. Is the online version a degraded editon of the original WordPress script?
WordPress.com is running the same code that you can download for free at WordPress.org ... the biggest difference is that .com is run by a for-profit company and .org is maintained by a non-profit community. WordPress.com, as a for-profit enterprise, has certain features disabled (for security purposes) and certain features limited so that users can buy in to "premium" packages. Specifically: You cannot upload or install custom themes (custom code could damage the multi-site environment You cannot upload or install custom plug-ins (for the same reasons as above) You must pay extra to direct traffic from your own domain to your WordPress.com site (a self-hosted site can use any domain you want) You cannon have an ad-free website on WordPress.com without paying extra (ad revenue supports the site) Some bonus features you get from WordPress.com You'll always be running the latest version of the software without the need to update Your site will be automatically backed up by WordPress.com's servers You can pay extra to use VideoPress for hosting your own videos (doing this yourself requires a separate server in addition to your custom website host) Akismet and stats are built-in to the site (though you can add these for free with your own site).
Feature Differences between WordPress.com and Hosting on your Own Server?
wordpress
I noticed that deleted users still show in the count of the users admin screen. On one blog I deleted 9 users only leaving the admin but it stil shows 9 in the count. In the physical database they are no longer present in the wp_users and wp_users_metadata so.... i guess that the counter is uhm... somewhere else in the database and I set it tot 1 manually in the database?? update / fix I notice that the records wp_capabilities and wp_user_level do not get deleted in the wp_usermeta table after deletion after I deleted those 2 records manually in the database the count was back to 1
Look no further, then. It's one of the joys of lack of referential integrity combined with workflow bugs. Please report this in the WP bug tracker.
deleted users still show in count?
wordpress
Is there an easy way to paginate the result set coming from $wpdb-> get_results()? I want to get a paginated list of a user's comments on the author_archive page - some of the users of the community have > 500 comments, so pagination is important. Is there an in-built way of doing this with WordPress, or do I need to build it myself? [Updated to add code] <code> &lt;!-- Show comments --&gt; &lt;?php $querystr = " SELECT comment_ID, comment_post_ID, post_title, LEFT(comment_content,100) as comment_content, comment_date_gmt FROM $wpdb-&gt;comments, $wpdb-&gt;posts WHERE user_id = $thisauthor-&gt;ID AND comment_post_id = ID AND comment_approved = 1 ORDER BY comment_ID DESC LIMIT 100 "; $comments_array = $wpdb-&gt;get_results($querystr, OBJECT); if ($comments_array): ?&gt; &lt;div id="author-comments-list"&gt; &lt;h2&gt;Recent Comments &lt;/h2&gt; &lt;ul&gt; &lt;? $odd_even = "odd"; foreach ($comments_array as $comment): echo "&lt;li class='$odd_even'&gt;&lt;a href='". get_bloginfo('url') ."/?p=".$comment-&gt;comment_post_ID."/#comment-". $comment-&gt;comment_ID ."'&gt;". $comment-&gt;post_title ."&lt;/a&gt; : ".mysql2date('l jS F, Y, g:ia',$comment-&gt;comment_date_gmt); echo "&lt;div class='author-comments-content'&gt;".$comment-&gt;comment_content."&lt;/li&gt;"; $odd_even = ($odd_even == "odd" ? "even" : "odd"); endforeach; ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;? endif; ?&gt; </code>
You can use the function paginate_links() for any pagination. For your specific case: <code> $total = $wpdb-&gt;get_var(" SELECT COUNT(comment_ID) FROM $wpdb-&gt;comments WHERE user_id = $thisauthor-&gt;ID AND comment_post_id = ID AND comment_approved = 1 "); $comments_per_page = 100; $page = isset( $_GET['cpage'] ) ? abs( (int) $_GET['cpage'] ) : 1; echo paginate_links( array( 'base' =&gt; add_query_arg( 'cpage', '%#%' ), 'format' =&gt; '', 'prev_text' =&gt; __('&amp;laquo;'), 'next_text' =&gt; __('&amp;raquo;'), 'total' =&gt; ceil($total / $comments_per_page), 'current' =&gt; $page )); </code>
Paginate result set from $wpdb-> get_results()
wordpress
I've tried three plugins to do this, non of them worked (I'm using WP 3.01): http://wordpress.org/extend/plugins/sem-external-links/ http://wordpress.org/extend/plugins/external-nofollow/ http://wordpress.org/extend/plugins/nofollow-external-links/
If you're experiencing bugs with my own plugin (sem-external-links), be so kind to say how it's not working...
Adding rel="nofollow" to external links in posts?
wordpress
I've used add_meta_box() to add a custom meta box to the WordPress edit window on both pages and posts. How can I make this meta box also show on the "Quick Edit" screen? Ideally, I'd like it to appear just to the right of the Categories selector.
There seems to be no easy way to do this, you must add all code yourself. <code> inline_edit_row() </code> , the function that draws the Quick Edit and Bulk Edit screens, seems to have only one action that you can hook into: <code> quick_edit_custom_box </code> or <code> bulk_edit_custom_box </code> . It gets called for all non-core columns that <code> wp_manage_posts_columns() </code> returns. There are some filters you can use to add a column, for example <code> manage_posts_columns </code> . Unfortunately, this function defines the column headers of the post table, so you should remove it again before <code> print_column_headers() </code> prints them. This can be done in the <code> get_column_headers() </code> function, with the <code> manage_[screen_id]_headers </code> filter . <code> edit-post </code> is the screen id for the Edit Posts screen. All together, this gives a hack like the following to add some code. Finding out where you can handle the form submission is (currently) left as a exercise to the reader. <code> // Add a dummy column for the `posts` post type add_filter('manage_posts_columns', 'add_dummy_column', 10, 2); function add_dummy_column($posts_columns, $post_type) { $posts_columns['dummy'] = 'Dummy column'; return $posts_columns; } // But remove it again on the edit screen (other screens to?) add_filter('manage_edit-post_columns', 'remove_dummy_column'); function remove_dummy_column($posts_columns) { unset($posts_columns['dummy']); return $posts_columns; } // Add our text to the quick edit box add_action('quick_edit_custom_box', 'on_quick_edit_custom_box', 10, 2); function on_quick_edit_custom_box($column_name, $post_type) { if ('dummy' == $column_name) { echo 'Extra content in the quick edit box'; } } // Add our text to the bulk edit box add_action('bulk_edit_custom_box', 'on_bulk_edit_custom_box', 10, 2); function on_bulk_edit_custom_box($column_name, $post_type) { if ('dummy' == $column_name) { echo 'Extra content in the bulk edit box'; } } </code>
How to show a custom meta box on the "Quick Edit" screen?
wordpress
I am presently trying to call the fields of a custom widget using get_option and loop through the array created from the get_option() call. The issue is that it is outputting a blank one at the end, resulting in one extra than what I have enabled. Here is the code I have at the moment: <code> $the_team = get_option('widget_jcMeetTeam'); $the_id = 1; //used for an ID increment for the jquery this will be used for print_r ($the_team); if (count($the_team) &gt; 1) { foreach ($the_team as $team_member) { extract($team_member); echo '&lt;div class="panel" id="'.$the_id.'"&gt; &lt;img src="'.get_bloginfo('template_url').'/images/about_lgplace.png"&gt; &lt;h2&gt;'.$team_member['jc_name'].'&lt;/h2&gt;; &lt;p&gt;Occupation: '.$team_member['jc_occupation'].'&lt;/p&gt; &lt;p&gt;Favorite Wine: '.$team_member['jc_favwine'].'&lt;/p&gt; &lt;p&gt;About: '.$team_member['jc_about'].'&lt;/p&gt; &lt;/div&gt; '; ++$the_id; //increment for next panel ID } } </code> I am presently trying to figure out how to get the loop to stop before the last blank one gets displayed, giving an accurate listing of active widget instances.
No further help is needed. unset($the_team['_multiwidget']); worked, and was the element in the array that was showing up at the end of the call. Will have to research what that part is exactly for future reference.
get_option returns undesired blank instance of a widget
wordpress
hey all! i have an odd problem with URL routing. when i request a URL that doesn't exist, e.g. http://localhost/foo , wordpress correctly returns a 404. however, if that URL is a prefix of a post or page name, it instead returns a 301 redirect to the post or page. for example, if i have a post on 10/1/2010 named Food Post, it will return a 301 with Location: http://localhost/2010-10-01_food_post (my permalink structure). likewise, if i have a page named Food Page, it will return a 301 with Location: http://localhost/food_page . you can see this in action on my live site, http://snarfed.org/ . e.g. http://snarfed.org/foo redirects to http://snarfed.org/2009-10-30_food_highlights . turning off permalinks (ie switching to "default") fixes it, for both posts and pages, but naturally i don't really want to do that. i see this on three different installations, all wordpress 3.0.1 and apache 2.2, two ubuntu lucid/mysql 5.1 and one freebsd 7.3/mysql 5.0. i've deactivated all plugins and removed everything from my .htaccess except the lines for wordpress below, verbatim, but no luck. <code> RewriteEngine On RewriteBase / RewriteRule ^wordpress/index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /wordpress/index.php [L] </code> thanks in advance...
This is normal, it is because <code> redirect_canonical() </code> , which makes sure you are always at a "canonical" URL (conforming to your permalink structure), executes <code> redirect_guess_404_permalink() </code> to make a best guess at a post when the URL is incomplete . If you want to prevent this, I think the best way is to hook into the <code> redirect_canonical </code> filter , and return false if it is a 404. Something like this: <code> add_filter('redirect_canonical', 'no_redirect_on_404'); function no_redirect_on_404($redirect_url) { if (is_404()) { return false; } return $redirect_url; } </code>
301 redirect instead of 404 when URL is a prefix of a post or page name?
wordpress
I was opened this idea 7 months ago: http://wordpress.org/extend/ideas/topic/non-latin-characters-need-love Still i couldnt find a solution for it. Simply what i want? Want to use "şŞ İı Ğğ Üü Öö çÇ" turkish characters in permalinks / slugs.
You must go about the language functions-interface. See my example for german users: http://wordpress-buch.bueltge.de/wp-content/uploads/2010/05/de_DE.phps We must also build differences on the permalinks for aour charachters in our language <code> /* define it global */ $umlaut_chars['in'] = array( chr(196), chr(228), chr(214), chr(246), chr(220), chr(252), chr(223) ); $umlaut_chars['ecto'] = array( 'Ä', 'ä', 'Ö', 'ö', 'Ü', 'ü', 'ß' ); $umlaut_chars['html'] = array( '&amp;Auml;', '&amp;auml;', '&amp;Ouml;', '&amp;ouml;', '&amp;Uuml;', '&amp;uuml;', '&amp;szlig;' ); $umlaut_chars['feed'] = array( '&amp;#196;', '&amp;#228;', '&amp;#214;', '&amp;#246;', '&amp;#220;', '&amp;#252;', '&amp;#223;' ); $umlaut_chars['utf8'] = array( utf8_encode( 'Ä' ), utf8_encode( 'ä' ), utf8_encode( 'Ö' ), utf8_encode( 'ö' ),utf8_encode( 'Ü' ), utf8_encode( 'ü' ), utf8_encode( 'ß' ) ); $umlaut_chars['perma'] = array( 'Ae', 'ae', 'Oe', 'oe', 'Ue', 'ue', 'ss' ); /* sanitizes the titles to get qualified german permalinks with correct transliteration */ function de_DE_umlaut_permalinks($title) { global $umlaut_chars; if ( seems_utf8($title) ) { $invalid_latin_chars = array( chr(197).chr(146) =&gt; 'OE', chr(197).chr(147) =&gt; 'oe', chr(197).chr(160) =&gt; 'S', chr(197).chr(189) =&gt; 'Z', chr(197).chr(161) =&gt; 's', chr(197).chr(190) =&gt; 'z', chr(226).chr(130).chr(172) =&gt; 'E' ); $title = utf8_decode( strtr($title, $invalid_latin_chars) ); } $title = str_replace($umlaut_chars['ecto'], $umlaut_chars['perma'], $title ); $title = str_replace($umlaut_chars['in'], $umlaut_chars['perma'], $title ); $title = str_replace($umlaut_chars['html'], $umlaut_chars['perma'], $title ); $title = sanitize_title_with_dashes($title); return $title; } add_filter( 'sanitize_title', 'de_DE_umlaut_permalinks' ); </code>
Non-Latin Characters in permalinks
wordpress
I'm building a site for a photographer who uploads pictures that are normally large for todays digital cameras. Images are quite memory intensive, especially the image operations like creating thumbnails. So I wanted to raise the memory limit in the admin above 256MB - how can this be done? I allowed CGI and PHP to use up to 1 Gigabyte but wordpress always decreases the memory to 256MB. Any idea how to fix that on a client side that needs to be able to auto-update? UPDATE: From Wordpress 3.2 ongoing the maximum memory limit in Wordpress will be configure-able again .
Theoretically, editing your config.php and add this line before wp-settings.php inclusion. <code> define('WP_MEMORY_LIMIT', '256M'); </code> should raise your memory limit for WordPress to 256MB or whatever value you set. And this will work sitewide. However, as stackexchange-url ("sorich87 pointed out"), there are few functions that will alter this setting with hard coded 256 MB limit. To Hack or Not To Hack A little concern about this, <code> WP_MEMORY_LIMIT </code> is one of the most strange WP setting I've encountered. if you check <code> /wp-includes/default-constants.php </code> you'll find this setting: <code> // set memory limits if ( !defined('WP_MEMORY_LIMIT') ) { if( is_multisite() ) { define('WP_MEMORY_LIMIT', '64M'); } else { define('WP_MEMORY_LIMIT', '32M'); } } </code> I never realize that WP will set it's default memory usage so low, until I find this in WP codex: WordPress will automatically check if PHP has been allocated less memory than the entered value before utilizing this function. For example, if PHP has been allocated 64MB, there is no need to set this value to 64M as WordPress will automatically use all 64MB if need be.( source ) That explanation was relieving. However, the usage of hard coded <code> @ini_set('memory_limit', '256M'); </code> everytime WP execute function that need more memory is never mentioned . In fact, I find no explanation about this vague behavior from WP codex. Since most of non user-related functions are either not documented or not clearly explained in codex. While this setting work nicely on most case, it will make those functions useless on server with lower max memory setting or on your case, higher memory usage. Until WP guys fix this, I think your only solution is to modify the core. You may find this post written by hakre interesting to read. He also submit a patch recommendation in Trac. Previous link to patch file may help you to find list of function that use this setting. edit: this is the most stupid answer I've ever give because I give a link to your own post (just realize that OP name was hakre after 2 days) :D edit 2: as mentioned on comment, this has been fixed by 3.2 release
How to use more than 256MB of memory in the admin?
wordpress
( Moderator's note: The original title was "Is it good to use picasa web album for images in wordpress blog?") Is it good to use Picasa web album for post's images in WordPress blog? What are pros and cons? Which one (Flickr or Picasa) is more suitable for blog post's images?
Hi @Brij : Both @George Wiscombe and @anu have good suggestions. To elaborate though, I'd say it depends on one of the following criteria: Do you plan to write programs using one of their API? If yes, review their APIs and pick the one you are most confortable with. Here are their APIs: Flickr's App Garden API Picasa Web Albums Data API Is Free important to you? - If free is important to you and you will be uploading more than 100Mb of images per month but not maintaining more than 1GB at any one time them go with Picasa. If you Free is not critical but As Cheap As Possible is important Google sells 5Gb additional for US$5/year, each 5Gb . Flickr doesn't limit storage but instead limits uploading bandwidth, and is $25/year for unlimited uploading. I'm pretty sure there are More 3rd Party Tools for Managing Photos for Flickr than for Picasa, so if you think 3rd party tools are a killer feature, go with Flickr. If none of those other issues are important and your are just going to grab the image URLs to link to them, just choose the one you like the most . BTW, if I were choosing I'd choose Flickr. I also wrote this to show up a few weeks ago to show someone How To Automate a Daily Picture Blog using Flickr . You might find it to be helpful too: stackexchange-url ("Automating a Daily Picture Blog")
Managing Images for a WordPress Blog: Picasa or Flickr?
wordpress
Typically in my theme function file I'll require other files to keep things neat. <code> require_once("foo.php"); </code> Now working in a child theme I'd like to do that same. I'm adding custom admin options and it seems impossible to include code. I've echoed out the path to make sure I'm calling the right file and it is calling the proper location but nothing inside that file seems to run. The code runs fine if placed inside the child theme functions file.
Child themes reference parent themes by directory name, and in a normal install all your themes live in <code> wp-content/themes/ </code> , so I'd say it's fine to reference those themes by their relative path: <code> include '../parent-theme/some-file.php'; </code> If that makes you uncomfortable, I observe the following constants in WordPress 3.0.1 with a twentyten child theme called tt-child : <code> TEMPLATEPATH /home/adam/public_html/wp3/wp-content/themes/twentyten STYLESHEETPATH /home/adam/public_html/wp3/wp-content/themes/tt-child </code> So you can do the following in your child theme to reference the parent theme directory: <code> include TEMPLATEPATH . '/some-file.php'; </code>
Include files in child theme functions file
wordpress
I have been tasked with creating a site for a large audience, and many of the audience will require some sort of sign up. They may require certain account controls (visual things, like theme colours for colour blind people) but largely it will just be a way to monitor the use of the contact features (so users can monitor their previous interactions like a ticket system) My question really is simply, where do I start? Is Wordpress the right tool for this job? If not, what is? If so, what methods should I be looking into to start the research going? Sorry for the broadness of the question, but I feel a little lost at the moment.
It's few months already and you probably have this solved by now but I'll try to do a little necromancing resume here anyway. We don't like unanswered questions right? ;) There's a recent topic dealing with the front-end login &amp; registration: stackexchange-url ("Front-end Register Form") You can change what WordPress displays to the users based on their capabilites by using the <code> current_user_can() </code> function. There's also a topic about loading alternate CSS: stackexchange-url ("How can I version the main CSS file?") Be sure to check related questions too. By using <code> body_class() </code> or <code> post_class() </code> you can change the CSS class of html body (or post) depending on the logged user. If those changes you want to achieve are intended to be more user based then role based then you can work with <code> update_user_meta() </code> and save some options in there. None of the above is hard to achieve. All mentioned functions are well documented. EDIT: Oh and the ticket system - You could use custom post types with front-end posting as a good starting point.
Advice on setting up a site with front end registration
wordpress
I have the following custom query written for a page- <code> $menu_loop = new WP_Query( array( 'post_type' => 'page', 'posts_per_page' => 50, 'post_parent' => 616, 'order_by' => 'post_title', 'order' => 'ASC' ) ); while ($menu_loop-> have_posts()) : $menu_loop-> the_post(); </code> The problem is, when the content is output to the page, it is NOT in alphabetical order by post_title. This has really been mystifying me because if I manually query the DB with- <code> SELECT * FROM wp_2_posts WHERE post_type = 'page' AND post_parent = 616 ORDER BY post_title ASC </code> then the results are returned correctly. Further, I print_r($menu_loop) and one of the array entries is the actual query sent to the DB and it is wrong and showing- <code> [request] => SELECT SQL_CALC_FOUND_ROWS wp_2_posts.* FROM wp_2_posts WHERE 1=1 AND wp_2_posts.post_parent = 616 AND wp_2_posts.post_type = 'page' AND (wp_2_posts.post_status = 'publish') ORDER BY wp_2_posts.post_date ASC LIMIT 0, 50 </code> which if you look you'll see the ORDER BY statement is sorting by the post date, not the post title. What am I doing wrong here?
Your sorting parameter should be: 'orderby' => 'title'
Problem with WP_Query sort
wordpress
I am looking for a way to do some conditional logic on terms associated with a post. Essentially I created my own custom taxonomy for "age groups" and have created three terms for them. Kids, Teens, Adults... In the admin area I want to check the terms which apply to a specific post and on the frontend of the site within my page template I want to show a specific image if the term was associated with the post or a different one if the term was not associated. Does anyone have a solution for this... I thought the following code example would work but it does not. (BTW - what I am doing here is changing the image based off css). <code> &lt;li id="kids-&lt;?php if ( is_term( 'Kids' , 'age_groups' ) ) { echo 'on'; } else {echo 'off';} ?&gt;"&gt;Kids Programs&lt;/li&gt; </code>
Hi @NetConstructor: First thing, assuming your logic worked you can use the ternary operator to simplify your example: <code> &lt;li id="kids-&lt;?php echo is_term('Kids','age_groups') ? 'on' : 'off'; ?&gt;"&gt;Kids Programs&lt;/li&gt; </code> The issue seems to be that <code> is_term() </code> is used to check if a term exists, not if it is associated with a particular post. I think what you really want is <code> is_object_in_term() </code> (which assumes that you are in The Loop, i.e. that <code> $post </code> has an appropriate value): <code> &lt;li id="kids-&lt;?php echo is_object_in_term($post-&gt;ID,'age_groups','Kids') ? 'on' : 'off'; ?&gt;"&gt;Kids Programs&lt;/li&gt; </code> P.S. Assuming <code> is_term() </code> had been the right function, it has actually been deprecated; <code> term_exists() </code> replaces <code> is_term() </code> ; just fyi.
Checking if a Page has an Associated Term?
wordpress
Hi I see a wordpress.co m blog and on the latest post there is a redirect for the external links via "http://go2.wordpress.com/" redirect. This redirect is obfuscated - on hovering the link it displays a "http://google.com/url?..." redirect instead. What is this and why is it suddenly on this post and not others? Also, I see the redirect type is a 302 - surely this is harmful in terms of SEO for the destination links?
It seems to be generated by API for affiliate service. See this topic Link redirection through go2.wordpress.com : The redirection is for a skimlinks ad service we are running.
What is the http://go2.wordpress.com/ redirect?
wordpress
As some of you know, there's an Easter Egg hidden in the WordPress post revision system that will display a message from the movie The Matrix if you perform a specific action (if you don't know, I won't spoil the surprise ... poke around with post revisions and see if you can find it). I love Easter Eggs, and this one was a thrilling find when I stumbled upon it. Some people, it seems, aren't really fans, though. I had a client recently discover this Easter Egg go into a panic attack because they thought someone had hacked their blog. They freaked out, flooded my inbox with panicked messages, and maxed out my voice mail quota with "please help!" messages. This leads me to believe that some Easter Eggs should be turned off when WordPress is deployed in certain situations - i.e. for high-maintenance clients. Enter my idea for the first ever WordPress Answers code challenge. The winner of this challenge will be awarded an extra 150 reputation points!!! Let's see how skilled you all are at coding ... what would you recommend as the simplest way to remove this Easter Egg from WordPress without hacking core? In other words, using only action hooks, filters, and custom enqueued JavaScript, how would you remove the Matrix Easter Egg? I'll select the "best" answer on October 31st based on: The completeness of the answer (a description of the code + example code + screenshots if applicable) The simplicity of the code (but remember, shorter isn't always better) Full descriptions of how you would install the code on a client site BTW, anyone who merely copy-pastes the solution I already posted on the WP-Hackers mailing list will be automatically disqualified. Let the games begin!
The following plugin dynamically hides the two offending radios using jQuery, and kills revision self-comparisons. <code> &lt;?php # Plugin Name: Pest Control # Plugin URI: http://www.semiologic.com/ # Description: Kills the Easter Bunny # Version: 1.0 # Author: Denis de Bernardy # License: Public Domain class PestControl { public static function bootstrap() { add_action('admin_head-revision.php', array(__CLASS__, 'mixomatosis')); add_action('load-revision.php', array(__CLASS__, 'plague')); } public static function mixomatosis() { echo &lt;&lt;&lt;EOD &lt;script type="text/javascript"&gt; // &lt;![CDATA[ jQuery(document).ready(function($) { var mixomatosis = function() { var left = $(':radio[name=left]:checked').val(), right = $(':radio[name=right]:checked').val(); $(':radio[name=left], :radio[name=right]').each(function() { var t = $(this); switch (true) { case t.attr('name') == 'left' &amp;&amp; t.attr('value') == right: case t.attr('name') == 'right' &amp;&amp; t.attr('value') == left: t.css('display', 'none'); break; default: t.css('display', ''); } }); }; mixomatosis(); $(':radio[name=left], :radio[name=right]').change(mixomatosis); }); // ]]&gt; &lt;/script&gt; EOD; } public static function plague() { if ($_GET['action'] == 'diff' &amp;&amp; $_GET['left'] == $_GET['right']) { wp_die("Can't compare a revision with itself."); } } } PestControl::bootstrap(); ?&gt; </code>
Coding Challenge - JavaScript Easter Egg
wordpress
I'm looking to do a custom import from a custom cms to wordpress. Looking at the export/import files in wordpress, I can get match most of the structure. Though, it is missing the relationships for custom taxonomies and posts when exporting/importing. Is there a fix for this or would it be easier to not use wordpress's import script? Rather, write custom SQL to handle it all. Also, as I am developing this new site the content in the old site (custom cms) is still being updated. There will be a freeze a few days before launch, where I can do another db dump and reimport. Though, the issue I'm foreseeing is that I will need to delete all posts and relationships and reimport the content. Is there an easy way to delete all posts and relationships to prevent any duplicates and reimport the content?
It shouldn't be hard to add handling for custom post types or taxonomies within a custom importer for WordPress. You'll just need to make sure that your custom post types and taxonomies are registered before the importer runs. Once registered, you can use wp_insert_post() and wp_set_object_terms() on these custom types. This will likely end up being a much better solution than trying to write custom SQL as it fills in a lot of the extra fields that aren't always obvious, like term object counts, etc. Whenever I'm working on a script to import data from another system, I've always created nuke functions, for the reason you mentioned, and just because importing data is always a bunch of trial and error. The function usually just consists of a single loop to call wp_delete_post() for each post. Depending on the import, I may also add another one to call wp_delete_term() on each term in the database. <code> $post_ids = $wpdb-&gt;get_col("SELECT ID FROM $wpdb-&gt;posts WHERE post_type in ('post', 'attachment', [...other post types])"); foreach($post_ids as $post_id) { wp_delete_post($post_id, true); } </code>
Custom Import with taxonomies
wordpress
I am almost completely happy with a new site I built - see http://www.fatasbutter.com.au/gallery/the-music/attachment/019/ As a final touch, I want to add <code> #content </code> to the end of the link location for each <code> previous_image_link() </code> and <code> next_image_link() </code> . Any ideas on how to do this?
This is kinda dirty, but I can't find a better hook: <code> function add_content_hash( $link ) { $link = str_replace("' title='", "#content' title='", $link); return $link; } add_filter( 'wp_get_attachment_link', 'add_content_hash' ); </code>
Add #content to next_image_link()
wordpress
I have a set of custom post types with the <code> capability_type </code> argument set to <code> 'page' </code> I want to include these in <code> wp_list_pages() </code> or similar so I can use the dynamic classes (such as <code> .current_page_item </code> and the like). I've read stackexchange-url ("this post") but I'm not sure it's exactly what I'm looking for, can anyone help me out with a code sample / more in-depth explanation.
The <code> wp_list_pages() </code> function calls <code> get_pages() </code> , which can't be easily overridden with a different post type. Here's a basic modification of that function which calls <code> get_posts() </code> instead. This takes basically the same arguments as wp_list_pages , with one additional: *post_type* (set as the name of your post type). <code> function wp_list_post_types( $args ) { $defaults = array( 'numberposts' =&gt; -1, 'offset' =&gt; 0, 'orderby' =&gt; 'menu_order, post_title', 'order' =&gt; 'ASC', 'post_type' =&gt; 'page', 'depth' =&gt; 0, 'show_date' =&gt; '', 'date_format' =&gt; get_option('date_format'), 'child_of' =&gt; 0, 'exclude' =&gt; '', 'include' =&gt; '', 'title_li' =&gt; __('Pages'), 'echo' =&gt; 1, 'link_before' =&gt; '', 'link_after' =&gt; '', 'exclude_tree' =&gt; '' ); $r = wp_parse_args( $args, $defaults ); extract( $r, EXTR_SKIP ); $output = ''; $current_page = 0; // sanitize, mostly to keep spaces out $r['exclude'] = preg_replace('/[^0-9,]/', '', $r['exclude']); // Allow plugins to filter an array of excluded pages (but don't put a nullstring into the array) $exclude_array = ( $r['exclude'] ) ? explode(',', $r['exclude']) : array(); $r['exclude'] = implode( ',', apply_filters('wp_list_post_types_excludes', $exclude_array) ); // Query pages. $r['hierarchical'] = 0; $pages = get_posts($r); if ( !empty($pages) ) { if ( $r['title_li'] ) $output .= '&lt;li class="pagenav"&gt;' . $r['title_li'] . '&lt;ul&gt;'; global $wp_query; if ( ($r['post_type'] == get_query_var('post_type')) || is_attachment() ) $current_page = $wp_query-&gt;get_queried_object_id(); $output .= walk_page_tree($pages, $r['depth'], $current_page, $r); if ( $r['title_li'] ) $output .= '&lt;/ul&gt;&lt;/li&gt;'; } $output = apply_filters('wp_list_pages', $output, $r); if ( $r['echo'] ) echo $output; else return $output; } </code> Note: its mostly copy-pasted from source. There's certainly a few arguments left in there that aren't doing anything and there might well be some use cases I haven't thought of that would break it. It works, surprisingly, though, with both hierarchical and non-hierarchical post types, though...
Dynamic navigation for custom post type (pages)
wordpress
I'm trying to figure out how to hook into the <code> /wp-admin/users.php </code> manage page to create custom columns for showing the number of posts users have for the custom post types on WPHonors.com . I created a trac ticket for this but @nacin explained why it's a job more for a plugin to do instead. I have been unable to find a way to manipulate the output of the users table, so I can add custom columns for CPTs post counts for each user. And that may have something to do with the question @nacin asked, what would the post count numbers link to. For the current 'post' post count a user has, it links to the post manage page, showing all posts for that user ( <code> /wp-admin/edit.php?author=%author_id% </code> ). If I were to link it somewhere, it would be to: <code> /wp-admin/edit.php?post_type=%post_type%&amp;author=%author_id% </code> If that were even somehow possible, I guess. But I don't even necessarily need to link it to anywhere. I mostly want to just show CPT post counts for each person, having <code> 600 </code> users and a combined total of <code> 300+ </code> posts across <code> 4 </code> custom post types. Admins are only one who can submit <code> 'post' </code> posts, so that column in the user's page is useless.
Here's an expansion of Mike's tutorial answer. I added links to the types listed so you can click on one and be taken right to a listing of all the posts in that type for that author, which required an additional variable for <code> $counts </code> and some extra output for <code> $custom_column[] </code> <code> add_action('manage_users_columns','yoursite_manage_users_columns'); function yoursite_manage_users_columns($column_headers) { unset($column_headers['posts']); $column_headers['custom_posts'] = 'Assets'; return $column_headers; } add_action('manage_users_custom_column','yoursite_manage_users_custom_column',10,3); function yoursite_manage_users_custom_column($custom_column,$column_name,$user_id) { if ($column_name=='custom_posts') { $counts = _yoursite_get_author_post_type_counts(); $custom_column = array(); if (isset($counts[$user_id]) &amp;&amp; is_array($counts[$user_id])) foreach($counts[$user_id] as $count) { $link = admin_url() . "edit.php?post_type=" . $count['type']. "&amp;author=".$user_id; // admin_url() . "edit.php?author=" . $user-&gt;ID; $custom_column[] = "\t&lt;tr&gt;&lt;th&gt;&lt;a href={$link}&gt;{$count['label']}&lt;/a&gt;&lt;/th&gt;&lt;td&gt;{$count['count']}&lt;/td&gt;&lt;/tr&gt;"; } $custom_column = implode("\n",$custom_column); if (empty($custom_column)) $custom_column = "&lt;th&gt;[none]&lt;/th&gt;"; $custom_column = "&lt;table&gt;\n{$custom_column}\n&lt;/table&gt;"; } return $custom_column; } function _yoursite_get_author_post_type_counts() { static $counts; if (!isset($counts)) { global $wpdb; global $wp_post_types; $sql = &lt;&lt;&lt;SQL SELECT post_type, post_author, COUNT(*) AS post_count FROM {$wpdb-&gt;posts} WHERE 1=1 AND post_type NOT IN ('revision','nav_menu_item') AND post_status IN ('publish','pending', 'draft') GROUP BY post_type, post_author SQL; $posts = $wpdb-&gt;get_results($sql); foreach($posts as $post) { $post_type_object = $wp_post_types[$post_type = $post-&gt;post_type]; if (!empty($post_type_object-&gt;label)) $label = $post_type_object-&gt;label; else if (!empty($post_type_object-&gt;labels-&gt;name)) $label = $post_type_object-&gt;labels-&gt;name; else $label = ucfirst(str_replace(array('-','_'),' ',$post_type)); if (!isset($counts[$post_author = $post-&gt;post_author])) $counts[$post_author] = array(); $counts[$post_author][] = array( 'label' =&gt; $label, 'count' =&gt; $post-&gt;post_count, 'type' =&gt; $post-&gt;post_type, ); } } return $counts; } </code>
Showing User's Post Counts by Custom Post Type in the Admin's User List?
wordpress
We have Wordpress 3.0 working as multi site, and we want all the blogs in the system to have the plugin " sexy bookmarks ". But it seems to be working only in the main blog. Does anyone know how to make it work in all blogs (what code to add to make it work that way)? Or is there a plugin like sexy bookmarks that adds social network icons to each post that works in a multi site version of Wordpress 3.0?
If the plugin is alreayd activated, then you cannot network activate it. because you already turned it on. Turn it off. Network activate it. You still have to configure it for each blog.
How to make sexy bookmarks plugin work in WPMU
wordpress
I need to retrieve the URLs for the images inside a gallery, what's the appropriate SQL query for this, based on the post ID? I currently have something like the following which I found on via google , but I don't know how to access the global WP variable from outside Wordpress - what do I need to do? <code> function getGallery($id) { global $wpdb; //SQL query to retrieve all attachment of mime type image/jpeg from the given post $querystr = " SELECT ID, post_name, guid, meta_value FROM $wpdb-&gt;posts wposts INNER JOIN $wpdb-&gt;postmeta meta ON meta.post_id = wposts.ID AND meta.meta_key = '_wp_attachment_metadata' WHERE wposts.post_type = 'attachment' AND wposts.post_parent = '".$id."' AND wposts.post_mime_type = 'image/jpeg' "; //get result set from the query $pictures = $wpdb-&gt;get_results($querystr, ARRAY_A); //return resultset return $pictures; } </code>
I believe the function is wp_get_attachment_url(). There also is one for thumbnails. See wp-includes/media.php.
Get urls of images in a gallery?
wordpress
( Moderator's note: The question's original title was: "Custom query: Show custom post types plus custom post type with post meta on blog homepage") I'm in need of help with a custom query. I have three custom post types: "News" , "Events" , "Stories" . On the main blog page, only News and Events will show. The client can choose to mark a Story as News using features of the plugin Verve Meta Boxes . If a Stories post has a post meta key of <code> 'mark-as-news' </code> then the that post should display on the main blog page as well. So what I need help with writing is this: If Stories has post meta <code> 'mark-as-news' </code> then the main blog page will display custom post types News and Events, as well as Stories, in descending order. Can someone please assist? Thanks! Edit: Perhaps a better way of wording this would be?: Show custom post types News and Events, and if there is the key <code> 'mark-as-news' </code> for <code> post_meta </code> , show Stories.
Hi @webcodeslinger: Here's what a basic MySQL query for loading News and Events would look like (this is greatly simplified from what WordPress actually does): <code> SELECT * FROM wp_posts WHERE post_type IN ('news','events') </code> What you want instead is something like this (there are more performant ways to do this in MySQL but they are more complex in WordPress and for most sites you'll never notice a difference): <code> SELECT * FROM wp_posts WHERE post_type IN ('news','events') OR (post_type='stories' AND ID IN (SELECT post_id FROM wp_postmeta WHERE meta_key='mark-as-news') ) </code> So...to add that extra SQL to your main loop's query use a <code> 'posts_where' </code> hook. You can put the following hook code into your theme's <code> functions.php </code> file (at the bottom of the file will do) or in one of the <code> .php </code> files of a plugin if you are creating a plugin: <code> add_action('posts_where','yoursite_posts_where',10,2); function yoursite_posts_where($where,$query) { global $wp_the_query; if (is_home() &amp;&amp; $query===$wp_the_query) { // This means home page and the main loop global $wpdb; $where .= " OR ({$wpdb-&gt;posts}.post_type='actor' AND " . "{$wpdb-&gt;posts}.ID IN (" . "SELECT post_id FROM {$wpdb-&gt;postmeta} " . "WHERE meta_key='mark-as-news')) "; } return $where; } </code>
Conditionally Query Custom Post Types by Post Meta for Blog Home Page?
wordpress
I have a custom post type, and in one of the custom meta-fields, I would like to present a drop-down list of the other (published) custom posts in order to link two custom posts. Specifically, I have a Film type, and some Films are screened as double features with other films. Currently, I just have a field for the other film's post ID, and my template manually handles the URL linking for that. But it would be much more user friendly to offer a drop-down list with titles of previously published Films. How would I do this?
The Post 2 Post plugin by Scribu is exactly what I needed.
Can I get an auto-populated dropdown list of other custom posts in a custom post edit page?
wordpress
I changed a custom post_type to a different name. Now when I view a single page with the post_type I receive a 404 page. How do I debug? Is there a WP log I can view the functions call?
Just try to update permalinks (i.e. Trigger a flush of the rewrite rules).
I changed post_type and now I receive 404 errors
wordpress
having trouble educating clients to compress their images, and would quite like wordpress to compress images to predefined size (normally, 800px long edge, 72dpi) and discard the original
Use http://wordpress.org/extend/plugins/auto-image-resizer/ Add this to your functions.php: <code> function prune_image_sizes($sizes) { // You can add other size like that for remove those sizes // unset($sizes['medium']); unset($sizes['large']); return $sizes; } add_filter('intermediate_image_sizes_advanced', 'prune_image_sizes'); </code> Set your large image option to 800px in media options panel. So what did you do? System will not create large size of image but will reduce original image size to large size ( 800px ) option. Most of developer dont like it but when client have to upload lots of image and dont have hosting space so much, this will helps. (Sorry for my english)
Can images be automatically compressed?
wordpress
I am trying to make a custom Category Display on my side bar and for that I need some way to get both, the category list and the child list in 2 different arrays or something alike... First, I tried the function <code> get_categories </code> , but it does not allow me to gather top-level categories only: <code> $args=array('orderby' =&gt; 'name', 'order' =&gt; 'ASC'); $categories=get_categories($args); </code> Then, I moved to <code> wp_list_categories </code> which does what I want. However, the return does not give me an array of data that I can query. It gives me a simple HTML-formatted list ready to print out: <code> $categories=wp_list_categories('echo=0&amp;style=none&amp;orderby=name&amp;order=ASC&amp;depth=1&amp;title_li='); </code> Is there a way to gather the top level categories list in a way I can personalize it as I wish ? For Example: <code> foreach($category_list as $category) { echo ' &lt;li&gt;'; echo ' &lt;a title="' . sprintf( __( "View all posts in %s" ), $category-&gt;cat_name ) . '" href="' . get_category_link($category-&gt;cat_ID) . '"&gt;' . $category-&gt;cat_name . ' (' . $category-&gt;cat_ID .') &lt;/a&gt;'; echo ' &lt;a onclick="s_toggleDisplay(document.getElementById('CHILD CATS'), this, '▼', '▲');" href="javascript:void(null);"&gt;▼&lt;/a&gt;'; echo ' &lt;/li&gt;'; } </code> Why do I want the top-level only ? Because, I wanted to make a show/hide function for the children of the top-level category. If you have another way to accomplish this or suggestion, let me know.
You can skip categories that have parent in your loop: <code> foreach($category_list as $category) { if( '0' != $category-&gt;parent ) continue; </code> I've looked through the source, but it seems <code> depth </code> is only taken in account in <code> wp_list_categories() </code> and you will probably need to extend <code> Walker_Category </code> class to custom walker there to make changes to output. Actually, this might be a good idea if you need a really complex categories output format.
Custom sidebar category listing?
wordpress
I have a site where posts get created and expired often. I want to add 410 status code to all posts that expire so that Search Engines remove them. I want to know if wordpress provides a provision to do this? or is this possible at all? Any suggestions how to achieve this would be very helpful. Thanks
Just did some testing and seems there is a bug here. Newly created draft posts are not accessible on front-end. Search bot (or anyone else not logged in and using special preview URL) gets 404 error on them. But if you publish and change back to draft then post remains available by direct link (does get removed from index). For this reason I would stay away from using draft for this purpose. I would try to use custom field to mark post as expired and filter <code> the_content </code> to show informational message and set headers with <code> status_header() </code> function.
Make posts 410 dynamically
wordpress
Considering stackexchange-url ("how often functions.php") is called, shouldn't all of its contents be hooked or filtered into core WP functions like init?
It can be used for much about anything that requires php... You'd only use hooks if you don't want to execute the php logic immediately. This is usually the case, but not always. Likewise, you'd typically use the WP API. But not always either...
Should everything in functions.php be hooked or filtered?
wordpress
Seems throughout the day my blog seems to show 404 page errors with no pattern. I have to manually change the permalinks from /blog/%scategory%/%postname%/ to default, then back to /blog/%scategory%/%postname%/ in order to fix the permalink issue. This has been a problem for us for the past six months, and our site gets 10k views a day. While that is not a lot, it does give us a huge problem when at certain periods of the day we have a huge issue where none of our Posts work, yet Pages continue to work fine. I have extensive conversation on this issue at this post (stackexchange-url where I have narrowed a few things down, and at this point I believe the sCategory Permalink is the issue. I need help understanding what is causing this issue, and more importantly fixing this so it never happens again. ANY help would be greatly appreciated.
I stopped using that plugin a long time ago. I don't think you really need it anymore honestly. I just remember it did the same thing that I was able to do when I disabled it, so I stopped using it. I don't think its still supported by the developer either, so may be out of date. I may be wrong, but then again I use the least amount of plugins as I can and build most things into my themes.
404 Error Problems with sCategory Permalink plugin
wordpress
I'm using WordPress 3.0.1 and I have made custom post-type called <code> 'dienasgramatas' </code> . My plugin also makes custom rewrite rules for displaying all posts from this post type and even custom permalink structure to query posts with this post type coming from defined author, but I can't create rule for pagination: This is the one that works: <code> $new_rules['dienasgramatas' . '/([^/]+)/?$'] = 'index.php?post_type=dienasgramata&amp;author_name=' . $wp_rewrite-&gt;preg_index(1); </code> It gives this rewrite rule: <code> [dienasgramatas/([^/]+)/?$] =&gt; index.php?post_type=dienasgramata&amp;author_name=$matches[1] </code> But this one: <code> $new_rules['dienasgramatas' . '/([^/]+)/page/?([0-9]{1,})/?$'] = 'index.php?post_type=dienasgramata&amp;author_name=' . $wp_rewrite-&gt;preg_index(1). '&amp;paged=' . $wp_rewrite-&gt;preg_index(2); </code> Outputs this (faulty) rewrite rule: <code> [dienasgramatas/([^/]+)/page/?([0-9]{1,})/?$] =&gt; index.php?dienasgramata=$matches[1]&amp;paged=$matches[2] </code> As you can see, <code> post_type </code> is ignored and this rewrite rule does not work as it should. Can someone tell me why it's not working or how to make it right? filter for funcion: <code> add_filter('generate_rewrite_rules', 'add_rewrite_rules'); </code> Full function is as follows: <code> function add_rewrite_rules($wp_rewrite) { $new_rules['dienasgramatas' . '/([^/]+)/?$'] = 'index.php?post_type=dienasgramata&amp;author_name=' . $wp_rewrite-&gt;preg_index(1); $new_rules['dienasgramatas' . '/([^/]+)/page/?([0-9]{1,})/?$'] = 'index.php?author_name=' . $wp_rewrite-&gt;preg_index(1) . '&amp;paged=' . $wp_rewrite-&gt;preg_index(2) . '&amp;post_type=dienasgramata'; $wp_rewrite-&gt;rules = array_merge($new_rules, $wp_rewrite-&gt;rules); return $wp_rewrite; </code> } Basic need is that i want to go to <code> www.example.com/dienasgramatas/admin/page/2 </code> and get posts by 'admin' with post_type = 'dienasgramata' and second page (e.g. 10 post offset). Rewrite rule without page/2 works fine. Maybe it's a regex issue or query vars issue or how rewrite rules are assigned. live site example: <code> http://dev.fiicha.lv/jb/dienasgramatas/juris/ </code> - works ok <code> http://dev.fiicha.lv/jb/dienasgramatas/juris/page/2/ </code> - does not work at the bottom there are all rewrite rules and query vars
Hi @banesto : I think the simple answer may be that you need your paged URL to be specified before your shorter URL, but since I didn't test it I'm not 100% sure. That said, I've always run into a lot of trouble with the <code> 'generate_rewrite_rules' </code> hook. I'm sure a better developer than me could make it work but for me it's been a lot cleaner to use the <code> add_rewrite_rule() </code> function so that's how I show you have to make your URLs route. Here's a plugin to do what you asked for (the <code> register_post_type() </code> call is only there to allow this plugin to work in my test install of WordPress; you can replace it with your own): <code> &lt;?php /* Plugin Name: Dienasgramatas Urls Version: 1.0 Author: Mike Schinkel Author URI: http://mikeschinkel.com/ */ if (!class_exists('Dienasgramatas_Urls')) { class Dienasgramatas_Urls { static function init() { $post_type = 'dienasgramatas' ; register_post_type($post_type, array( 'label' =&gt; 'Dienasgramatas', 'public' =&gt; true, 'show_ui' =&gt; true, 'query_var' =&gt; 'dienasgramatas', 'rewrite' =&gt; array('slug' =&gt; 'dienasgramatas'), 'hierarchical' =&gt; false, 'supports' =&gt; array('title','editor','custom-fields'), ) ); add_rewrite_rule("{$post_type}/([^/]+)/page/?([2-9][0-9]*)", "index.php?post_type={$post_type}&amp;author_name=\$matches[1]&amp;paged=\$matches[2]", 'top'); add_rewrite_rule("{$post_type}/([^/]+)", "index.php?post_type={$post_type}&amp;author_name=\$matches[1]", 'top'); } static function on_load() { add_action('init',array(__CLASS__,'init')); } static function register_activation_hook() { self::init(); flush_rewrite_rules(false); } } Dienasgramatas_Urls::on_load(); } </code> Of course whenever you add rewrite rules you need to flush the rewrite rules or they simply won't work. Ideally you don't want to flush rules for every page load so the standard way to do it is in a plugin's activation hook. So I created a plugin for you but feel free to just use the <code> add_rewrite_rule() </code> calls in your theme's <code> functions.php </code> file and manually flushing your URLs by clicking "Save Changes" in the "Settings > Permalinks" section of the admin console.
Custom Post Type Rewrite Rule for Author & Paging?
wordpress
( Moderator's note: Title was originally "What are all the variables in the wordpress post object?") Does anyone know the variables that are stored in the WordPress Post object?
Post object is mostly queried row of <code> wp_posts </code> database table with some extras. It is easy to dump content of one and see: <code> object(stdClass) public 'ID' =&gt; int public 'post_author' =&gt; string public 'post_date' =&gt; string public 'post_date_gmt' =&gt; string public 'post_content' =&gt; string public 'post_title' =&gt; string public 'post_excerpt' =&gt; string public 'post_status' =&gt; string public 'comment_status' =&gt; string public 'ping_status' =&gt; string public 'post_password' =&gt; string public 'post_name' =&gt; string public 'to_ping' =&gt; string public 'pinged' =&gt; string public 'post_modified' =&gt; string public 'post_modified_gmt' =&gt; string public 'post_content_filtered' =&gt; string public 'post_parent' =&gt; int public 'guid' =&gt; string public 'menu_order' =&gt; int public 'post_type' =&gt; string public 'post_mime_type' =&gt; string public 'comment_count' =&gt; string public 'filter' =&gt; string </code>
What are all the Properties of the WordPress Post Object?
wordpress
In an effort to combat comment spam, I'd like to hide or remove the "Website" field from the "Leave a Reply" section for page and site comments. I have no desire to increase others page rankings by having them embed their URLs in my sites comments, which seems to be what 99% of the comments on my site are wanting to do. I'm using the Twenty Ten theme if that makes any difference in the answer. Thanks!
Create a file in <code> wp-content/plugins/ </code> with this code: <code> &lt;?php /* Plugin Name: Get Rid of Comment Websites */ function my_custom_comment_fields( $fields ){ if(isset($fields['url'])) unset($fields['url']); return $fields; } add_filter( 'comment_form_default_fields', 'my_custom_comment_fields' ); </code> Normally, I'd say put it into your theme's functions.php file, but I wouldn't recommend doing that for a theme that could update like Twenty Ten. This way will let you add this functionality as a plugin which can be disabled.
Removing the "Website" Field from Comments and Replies?
wordpress
I was wondering if there is a simple way to replicate my configurations for all the subsites once i have activated a network plugin without having to go thru each and configure it manually ? Upgrade a set or single network plugin(s) with the same configuration to all subsites
I've had to write some custom stuff to copy settings across blogs. Currently I've got a plugin with two textareas: A read-only box with a base64 encoded serialized string of all the blog options ( <code> wp_options </code> ) I care about (in this case, widgets, sidebars, and options from a specific plugin ) A field that can accept the same encoded string copied from another blog So, I don't know of a good way besides dumping the data via WordPress's <code> get_option() </code> or SQL queries, and loading the data back in on another database.
Replicate network plugins without having to configure it for each subsite?
wordpress
So, for the thousands using WP as CMS, a typical approach is that of using the 'A Static Page' option from the Settings > Reading admin page. However, I'm in a different scenario: our front page is displaying static content ( home.php template drives that), and we have a secondary static page (called News ) which should display the list of most recent posts (what you usually find on an average blog's front page). I set up the News page to use a custom template ( page-NewsIndex.php ); based on TwentyTen's archive.php template, this file displays a header, calls rewind_posts() and then calls get_template_part('loop', 'newsindex') so that we end up in loop.php (or loop-newsindex.php, if it exists). Peachy. Loop.php has your typical loop structure (again, based on TwentyTen's loop.php template - tweaked to simplify since we don't need 3 type of loops): <code> &lt;?php while ( have_posts() ) : the_post(); ?&gt; </code> However, when we access the page, this loop seems to use the current URL to determine the posts to display, as if the News page was defining a category - which is not the case for us. What would be the appropriate query_posts for me to use to simulate the query_posts that WP usually runs for you when you get to the front-page of a typical blog?
The way I retrieve posts on my blog is to use the following: <code> &lt;?php $recentPosts = new WP_Query(); $recentPosts-&gt;query('showposts=5&amp;cat=CAT_ID_GOES_HERE'); while($recentPosts-&gt;have_posts()): $recentPosts-&gt;the_post(); ?&gt; </code> Then you would go and create the code to control the display of each post. So for a really simple example: <code> &lt;h1 class="title"&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt; </code> Then at the end of the posts you just have to end your while loop: <code> &lt;?php endwhile; ?&gt; </code>
How to get the list of posts in a static page other than front page?
wordpress
How can I attach images to a post which have already been attached to other posts without having to upload them twice? I don't want to insert the images into the post, I simply want to attach the same set of images to multiple posts. As of WP.3.0.1 it does not appear that this is possible, however, if the "Media Library" tab of the "Insert Image" wizard had a column labeled "Attach" with a checkbox next to each image in the media library, this could be easily done. How difficult a task would it be to add this functionality?
As you've noted it's not possible out of the box. The feature was supposed to make it into 2.9, got postponed until 3.2, and assuming they reject the post2post table mike and I crave for it'll probably be postponed again. You'll have better luck creating a custom taxonomy in the meanwhile, and "tagging" images tied to this or that post accordingly. That'll give you an n-n relationship. As for difficulty, I'd say not easy. Adding extra fields in the media upload/insert screens, in so far as I've experienced it (i.e. a huge media plugin) is a bloody mess.
Possible to "Attach" images to multiple posts without inserting or uploading twice?
wordpress
Trying to get my head round functions.php and am wondering how often it is loaded?
Simple answer is once. As any other PHP file otherwise it would likely cause crash because of function redefinitions. More complex answer is there can be actually two different <code> functions.php </code> loading - one for parent theme and one for child theme. Tricky part here is that child theme's loads before the parent's, which can at times be counter-intuitive for some purposes (like working with hooks).
How often is functions.php loaded?
wordpress
According with stackexchange-url ("Wordpress: category page not for post's"). I use wordpress to create web sites for flash games, so I don't have certain page for post's. I add each game by post-new.php?post_type=game and u can see it's not the regular post for wordpress. Now I try make the same for tags, but stuck again. what I have now: <code> &lt;?php if (is_page() ) { $tag = get_post_meta($posts[0]-&gt;ID, 'tag', true); } if ($tag) { $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $post_per_page = 4; // -1 shows all posts $do_not_show_stickies = 1; // 0 to show stickies $args=array( 'post_type' =&gt; 'game', 'tag__in' =&gt; array($tag), 'orderby' =&gt; 'date', 'order' =&gt; 'DESC', 'paged' =&gt; $paged, 'posts_per_page' =&gt; $post_per_page, ); $temp = $wp_query; // assign orginal query to temp variable for later use $wp_query = null; $wp_query = new WP_Query($args); if( have_posts() ) : while ($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post(); ?&gt; &lt;div &lt;?php post_class() ?&gt; id="post-&lt;?php the_ID(); ?&gt;"&gt; &lt;h2&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="Permanent Link to &lt;? php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;div class="entry"&gt; &lt;?php the_content('Read the rest of this entry »'); ?&gt; &lt;/div&gt; &lt;p class="postmetadata"&gt;&lt;?php the_tags('Tags: ', ', ', '&lt;br /&gt;'); ?&gt; Category in &lt;?php the_category(', ') ?&gt; |&lt;/p&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;div class="navigation"&gt; &lt;div class="alignleft"&gt;&lt;?php next_posts_link('« Older Entries') ?&gt;&lt;/div&gt; &lt;div class="alignright"&gt;&lt;?php previous_posts_link('Newer Entries »') ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php else : ?&gt; &lt;h2 class="center"&gt;Not Found&lt;/h2&gt; &lt;p class="center"&gt;Sorry, but you are looking for something that isn't here.&lt;/p&gt; &lt;?php get_search_form(); ?&gt; &lt;?php endif; $wp_query = $temp; //reset back to original query } // if ($tag) </code> Basicly, I've just change '$cat' for '$tag' according with codex, but I have only page with search form from here <code> &lt;h2 class="center"&gt;Not Found&lt;/h2&gt; &lt;p class="center"&gt;Sorry, but you are looking for something that isn't here.&lt;/p&gt; &lt;?php get_search_form(); ?&gt; </code> and don't nave any game for certain tags?
I've solved my task! 'begin_roundblock' and 'end_roundblock' are my functions for making blocks to games. 'cols' and 'rows' are number columns rows and rows for games. <code> if ($tag) { $cols = 9; $rows = 5; $paged = (('paged')) ? get_query_var('paged') : 1; $post_per_page = $cols * $rows; // -1 shows all posts $do_not_show_stickies = 1; // 0 to show stickies $args=array( 'post_type' =&gt; 'game', 'tag' =&gt; $tag, 'orderby' =&gt; 'date', 'order' =&gt; 'DESC', 'paged' =&gt; $paged, 'posts_per_page' =&gt; $post_per_page, 'caller_get_posts' =&gt; $do_not_show_stickies ); $wp_query = new WP_Query($args); begin_roundblock(urldecode($tag), 'games-pages-tag', null); if( have_posts()) : echo '&lt;div class="games-list-block-content"&gt;'; $i = 0; while (have_posts()) { the_post(); $class = 'game-info'; if ($i % $cols == 0) $class .= ' clear'; echo '&lt;div class="'.$class.'"&gt;&lt;a href="'.get_permalink().'"&gt;'; the_post_thumbnail(array(60, 60), array('class' =&gt; 'game-icon')); $title = get_the_title(); if (mb_strlen($title) &gt; 10) $title = mb_substr($title, 0, 7).'...'; echo '&lt;span class="game-title"&gt;'.$title.'&lt;/span&gt;&lt;/a&gt;&lt;/div&gt;'; $i++; } ?&gt; &lt;div class="navigation clear game-info-last-row"&gt; &lt;span class="alignleft"&gt;&lt;?php next_posts_link('« Older Entries') ?&gt;&lt;/span&gt; &lt;span class="alignright"&gt;&lt;?php previous_posts_link('Newer Entries »') ?&gt;&lt;/span&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php else: ?&gt; &lt;h2 class="center"&gt;Not Found&lt;/h2&gt; &lt;p class="center"&gt;Sorry, but you are looking for something that isn't here.&lt;/p&gt; &lt;?php get_search_form(); ?&gt; &lt;?php endif; end_roundblock(); } </code> ?>
Tags page not for post
wordpress
I'm pulling my hair out over this. In the Links manager, you can enter a description for the category (in addition to the link itself). However, in wp_list_bookmarks, there is no way to call this value anywhere. So how can I get it? I know it's in the term_taxonomy table, under link_category. So is there a function that could be written to retrieve this value dynamically (i.e. not having to declare each link category independently)
OK, with the help of a friend I was able to get this done. I ditched the wp_list_bookmarks and went with a combination of get_terms and get_bookmarks. <code> function blogroll_page( $args = array() ) { if(is_page('blogroll')) { if( $terms = get_terms( 'link_category', $args = array('exclude' =&gt; 16) ) ) { foreach( $terms as $c ) { printf( '&lt;h3&gt;%s&lt;/h3&gt;', $c-&gt;name ); printf( '&lt;p&gt;%s&lt;/p&gt;', $c-&gt;description ); if( $bookmarks = get_bookmarks( array( 'category' =&gt; $c-&gt;term_id ) ) ) { printf( '&lt;ul class="xoxo bookmarks"&gt;' ); foreach( $bookmarks as $bm ) printf( '&lt;li&gt;&lt;a href="%s" title="%s"&gt;%s&lt;/a&gt;&lt;/li&gt;', $bm-&gt;link_url, $bm-&gt;link_description, $bm-&gt;link_name ); printf( '&lt;/ul&gt;' ); } } } } } </code>
Link Category Description
wordpress
I'm trying to set up individual, one-time schedule events in a plugin. No matter what I do, I can't seem to get the events to fire. I'm using the Cron View plugin to see what's in queue, and the events are added and remove themselves totally on schedule. I never, however, receive the email I've set to send in the action's target function (simply in order to test the event, there will be more in there later). I have tested the function outside of scheduled events, it does work. Here's some code: <code> GLOBAL $new_workshop_id; $new_workshop_id = $wpdb-&gt;insert_id; function send_reminders() { GLOBAL $new_workshop_id; wp_mail('my@emailaddress.tld', 'Automatic ID: '.$new_workshop_id, 'here it is!'); } if (!wp_next_scheduled('send_reminder_emails_'.$new_workshop_id)) { wp_schedule_single_event( time()+30, 'send_reminder_emails_'.$new_workshop_id ); } do_action( 'send_reminder_emails_'.$new_workshop_id ); add_action( 'send_reminder_emails_'.$new_workshop_id, 'send_reminders' ); </code> One thing I'm suspicious is the placement of do_acton and the function itself, <code> send_reminders() </code> . The above code is within some if statements checking for POST vars, so it's possible that the function can't be accessed by the CRON job - so where should I put the function? I've tried right at the top of the plugin file. From what I've read, do_action should call the function and execute it wherever you have put do_action, but I guess I need to know where to put <code> send_reminders() </code> in the first place so that it's accessible, by either the cron job or do_action. Thanks in advance for any input!
The cron arg usage looks weird. The insert id will return garbage by the time your function is called. By the same token, I believe better schedule it always, with the id argument, on insert, if this if for logging. Else you'll be throttling your logs, basically. Lastly, are you sure that wp_mail() is working?
Scheduled event won't fire
wordpress
I'm trying to build a new WordPress theme using register_post_type to create a custom post type called listings. I would like each listing to have the following permalink structure: http://www.mysite.com/%author%/listing-title I'm not quite sure how to achieve this with the CPT controls listed in the Codex. Previously, I have a achieved a similar effect by creating a custom structure in Permalink Settings: <code> /%author%/%postname%/ </code> It has been stackexchange-url ("suggested on the main forum") that I use wp_rewrite, but wp_rewrite only seems to deal with incoming requests and does not change the way CPT posts are created. To illustrate further with an image, I want to change the /listings/ part of the permalink URL to the post author's name. See image below.
My plugin Custom Post Permalinks allows you to set permalink structures for custom post types and it supports post authors as part of a permastruct. However, while my plugin will enable you to set up that structure, I don't suggest using that structure. That structure will essentially make WordPress interpret all top-level pages as 404 errors (and second level pages, I think). You should be fine if you add the post type to anchor the beginning of the structure like this: <code> /%post_type%/%author%/%postname%/ </code>
In WordPress how do you create a custom post type with the author's name in the slug?
wordpress
I would like to alter the default categories widget code so that it does not show any categories which are children of the uncategorized (id=1) category. Can I do this via my sidebar.php or functions.php code?
If memory serves, there's an exclude argument, which isn't available in the widget but which should be around for the category list template tag. http://codex.wordpress.org/Template_Tags/wp_list_categories It should hide subcategories if you're listing them hierarchically.
How can I alter the display of category listings via sidebar.php?
wordpress
A client of mine has a VERY, VERY, VERY large WordPress site (over 1 million pages). Is there a sitemap plugin that can handle this (would need to create sitemap indexes)? Their site have very shallow crawldepth, so they figure a sitemap would help a lot.
Quick search shows that next major update of Google XML Sitemaps plugin will have index-based sitemap . Overall sitemap is not a guarantee that site will be crawled and I'd also look into other ways to improve (better and more extensive navigation, more internal links, etc).
Best Sitemap Plugin for 1M+ pages
wordpress
This is a pretty strange problem. I'm creating a WordPress custom post type in my themes functions.php file using the following format: <code> add_action('init', 'product_register'); function product_register() { $args = array( 'label' =&gt; __('Products'), 'singular_label' =&gt; __('Product'), 'public' =&gt; true, 'show_ui' =&gt; true, 'capability_type' =&gt; 'post', 'hierarchical' =&gt; false, 'rewrite' =&gt; true, 'supports' =&gt; array('title', 'editor', 'thumbnail') ); register_post_type( 'product' , $args ); } </code> This gives me the following url structure for my products: http://www.mywebsite.com/products/product-name . However, if I switch to another theme (TwentyTen) and then switch back WordPress forgets the permalink, now when I browse to the URL above I get my 404 page. The really strange thing I've noticed is that I can fix this issue by browsing to Settings -> Permalinks in admin. This temporarily fixes the problem until the next theme uninstall/ reinstall. Anyone else had a similar issue?
The new permalink structure is only saved when <code> WP_Rewrite::flush_rules() </code> is called. Because this is an expensive operation (calculating the new rules and saving them to the database), you should not do it on every <code> init </code> call, but only when you change the structure. The custom post type however must be registered at every <code> init </code> call, since it is saved in a PHP array in memory, not in the database (which is why it forgot the custom post when you switched themes: the permalink structure still existed but referred to a custom post type that was not loaded, giving an error).
WordPress custom post types breaks permalink on theme reinstall
wordpress
My blog design heavily relies on categories and sub-categories. I would like the url structure to be dependent on that. How can I make the url's support the same? I would like it to be like: <code> http://www.mywordpressblog.com/categoryname/subcategoryname/postname.html </code> It should also support further sub-categories if any. And if I have any pages, It should follow the same structure just that it should be substituted by the page name. Further info: I am using Wordpress 3.0.1 and hence am using the custom menu feature which allows me to combine my pages and categories into one awesome menu.
With the following as a permalink structure; <code> /%category%/%postname/ </code> The category slug is added to the URL. Subcategories, if any, appear as nested directories. So you end up with ; /category/your-post-slug/ And if subcategories are used /category/subcategory/your-post-slug
Create a url structure for my blogs based on categories and sub-cats
wordpress
Someone set me up with some custom work on top od another them and now I want to add a "what's new"/"blog"/"latest news" type page that is accessible from the main menu and is NOT the home page. How can I do that? It is not obvious to me how that is done. Thanks.
In the admin area, Go to Settings » Reading , Choose ' A Static Page ' from the first set of options &amp; select the two pages you would like to use as the front-page &amp; blog/news page. Hope this helps, G
How do I set up "blog" posts to a page other than the main/home page?
wordpress
Flushing rules is clearly an important part of creating themes with custom post types. See here and stackexchange-url ("here"). Does anyone have any example code of how to flush rules from functions.php? I'm a little surprised this isn't covered in the custom post type pages of the Codex. Update: I tried adding this to functions.php, but it didn't work: <code> register_deactivation_hook( __FILE__, array(&amp;$this,'deactivate' ) ); function deactivate() { global $wp_rewrite; $wp_rewrite-&gt;flush_rules(); } </code>
While the solutions provided here do still work, WordPress has evolved since and does now (since 3.3, I believe) provide direct hooks for theme activation. <code> after_switch_theme </code> will fire on theme activation and <code> switch_theme </code> before deactivating an old theme. Hence the up-to-date answer is: <code> function reflush_rules() { global $wp_rewrite; $wp_rewrite-&gt;flush_rules(); } add_action( 'after_switch_theme', 'reflush_rules' ); </code>
How does one flush rules on theme activation or deactivation only?
wordpress
I have this bit of code in my Meteor Slides plugin that loads a stylesheet on the admin pages of just the slides custom post type: <code> add_action('admin_head', 'meteorslides_admin_css'); function meteorslides_admin_css() { global $post_type; if (($_GET['post_type'] == 'slide') || ($post_type == 'slide')) : echo "&lt;link type='text/css' rel='stylesheet' href='" . plugins_url('/css/meteor-slides-admin.css', __FILE__) . "' /&gt;"; endif; } </code> This code works fine and hasn't cause any issues, but in debug mode, it does cause this error that I'd like to resolve: <code> // Notice: Undefined index: post_type in C:\Program Files\xampp\htdocs\slides\wp-content\plugins\meteor-slides-1.3\meteor-slides-plugin.php on line 476 </code> I haven't been able to fix this error, does anyone have any suggestions, or a different way to add a stylesheet to the admin pages of a certain post type?
You need to check for the presence of <code> 'post_type' </code> as an index of <code> $_GET </code> before using it: <code> if ((isset($_GET['post_type']) &amp;&amp; $_GET['post_type'] == 'slide') || (isset($post_type) &amp;&amp; $post_type == 'slide')) : </code> Also, you should be using the <code> wp_enqueue_style </code> function instead of echoing your stylesheet at <code> 'admin_head' </code> : <code> wp_enqueue_style( 'meteor-slides-admin', plugins_url('/css/meteor-slides-admin.css', __FILE__), array(), '1.0' ); </code> More information on wp_enqueue_style here .
Adding CSS to custom post type admin page causes error
wordpress
I've read a few books on building WP themes and I certainly understand the basics. I would like to know read up on advanced topics like hooks, wp_rewrite and how functions.php should be structured. Can anyone recommend any good resources?
The best resources available are: The Codex - Most of the functions and tools you'll want to use are documented there, as well as examples and code snippets that you can use in your own system. PHPXref - There are a lot of different systems out there, I just linked to the first one I found. But remember that the in-line documentation for WordPress is pretty much amazing and, in many cases, will be all you'll ever need. Justin Tadlock's Blog - During the theme development presentation at WordCamp Portland, the presenter actually said his first step to learning a new technique or using a new tool was to see if Justin had written a tutorial on it. Beyond those three references, I would also recommend that you take a very close look at the structure and composition of the TwentyTen theme that ships with WordPress. It's written by the same team who writes core, so it's your best bet for a "definitive" example of most things WordPress. I'd also suggest you invest in one of the nicer theme frameworks available - my personal recommendation would be Genesis . If you're using a framework for building your theme, most of the work is done for you. You'll also have more tools at your disposal, and some of the frameworks are incredibly advanced in their design. Looking at how someone has already done something and deciding how you'd improve on it can be one of the easiest ways to learn.
Advanced theme training?
wordpress
Currently I have a small amount of 100 categories and my MENU goes crazy big and I would like to be able to do 2 things if possible: First category menu with limited amount categories sorted by hits Second category menu with limited amount of categories choose by myself Is there any simple way to acomplish this either manually editing part of the code but yet allowing me to render the category by the wordpress code instead of having to type each by hand or a plugin with already such features ? PS: I was trying to use the search for this but even using "Category Menu too big" there were so many unrelated answer that it was hard to find anything good to my case.
I have moved away from looking for a plugin and adventured myself into making my own modifications, see stackexchange-url ("stackexchange-url In regards my question here I have found the follow: Yes, it is possible to limit the amount of items listed on the category by setting the number argument that can be used with wp_list_categories and get_categories . A personalized menu can be create with only the categories you wish to allow on it on the Menu that code can be re-used on the sidebar, only problem is that it will be manually updated/controlled.
My Category is too big on the Menu what can i do?
wordpress
Right, please excuse the stupid question. On my new blog I want the home page to be the "home" page I've created, and not the list of articles... that's fine, I go to <code> Settings -&gt; Reading -&gt; Front page displays </code> and change <code> Front page </code> to <code> Home </code> . But now I want <code> /blog/ </code> to list my articles, however I get a 404 :S I'm a bit stuck on this one, any help would be mucho appreciated.
This depends on how the index.php of your theme is coded. If it is a standard blog index page (as it is in 2010), all you need to do is: create a page named "blog" (or whatever you fancy), no need to add any content or select any template, in wp-dashboard > Settings > Reading: tick "static front page" select your "home" page as the Front Page select the "blog" page you created as the Posts Page, again, it depends on the default index.php of your WordPress theme. It may also help to regenerate the permalinks, go to wp-dashbaord > Settings > Permalinks and click "save changes" (no need to change anything). Watch for any warning messages on updating .htaccess (and update manually if required), then check again.
Blog page problems
wordpress
I have a client who has an annual complete makeover of their website design and content, but they still want their old sites available to view (each with that year's respective design/CSS). Once these blogs are "archived", I don't want to have to maintain them any more w.r.t. updating plugins and core files. Previously, when I have left plugins un-updated for too long, I have had some security issues (or at least, that's what my host blamed the last few hack attempts on). I know there are auto-updating plugins out there, but I don't know about you - I always have to check that nothing is broken with each update (whether auto-updated or manual). I've considered just generating an html mirror, but are there any other "maintenance free" way I can "archive" my old blogs?
I think HTML mirror is the way to go here. There is no point keeping dynamic site that doesn't need to be. And leaving it unmaintained is not really possible on auto-pilot - even if updates are automatic there is no guarantee some plugin won't get just dropped by developer. Alternatively you can build multi-design site. It's not that hard to load stylesheets and templates conditionally. Of course that would be considerable amount of work comparing to HTML mirror.
How can I permanently cache or "archive" a WP blog without needing future maintenance
wordpress
( Moderator's note: The original title was "Is there a way to get post comments by post ID on a custom loop using WP-Query()?") Hi! I'm running a custom loop using WP_Query , that only displays one post from a specific category on the home.php page, like so: <code> &lt;?php $pr_q = "cat=11&amp;posts_per_page=1"; $pregunta_q = new WP_Query($pr_q); ?&gt; &lt;?php while ($pregunta_q-&gt;have_posts()) : $pregunta_q-&gt;the_post(); ?&gt; &lt;!-- post stuff here --&gt; &lt;?php endwhile; ?&gt; </code> Is there any way to have it show comments for that specific post? I tried including the comments template inside the loop and nothing. Is there a function that loads the comments for a specific post that I can use inside home.php or anywhere else?
To be able to use the comments template in your loops, add <code> global $withcomments; $withcomments = true; </code>
Getting Post Comments for post ID using WP_Query() and a Custom Loop?
wordpress
The weirdest Wordpress problem ever I think. A clients site with a large database of posts has got a mind of it's own. One minute everything seems fine, the next posts, categories and tags are missing. At the minute the dashboard is telling me there's 2309 posts in 9 categories but when I click the categories link in admin there's none in the list. I can see all posts in admin but whereas they used to be assigned to categories and have tags listed, they're all now "Uncategorized" with "No Tags". Obviously the wordpress database is corrupt in some way but where to start to try fix it!? Here's what I've tested so far: Plugins – I turned off all current plugins. Theme – I tried a different theme/template. Wordpress Core – I re-uploaded the latest wordpress version. Updates – I updated all plugins and wordpress core. Repair Database - I checked and tried to repair the database in Cpanel but it timed out. Help!?
You're probably running into the joys of MySQL's MyISAM engine... From within MySQL (or PhpMyAdmin), use REPAIR TABLE xyz statements again, repeatedly, on each of your tables (or rather, your terms related tables, since these are the ones that sound corrupt) to see if this solves anything. If those fail, there are a few documented workarounds: http://www.google.com/search?q=recover+a+corrupt+mysql+database Once things are recovered, run OPTIMIZE TABLE xyz statements on each table, and then alter the engine of the database and each table to make it use InnoDB. InnoDB clutters the catalog somewhat (especially if you drop a database or large tables), but -- being ACID compliant -- it's a hell of a lot less error prone than MyISAM.
Corrupt Wordpress Database
wordpress
I have some PHP code that I would like to pull out of an existing page of a template, and put into a widget so I can move it around. What is the quickest way to create a widget?
The Widgets API is the quickest way to make a widget that's reusable. Example use: <code> class My_Widget extends WP_Widget { /** * PHP4 constructor */ function My_Widget() { My_Widget::__construct(); } /** * PHP5 constructor */ function __construct() { // actual widget processes } /** * Echo the settings update form * * @param array $instance Current settings */ function form($instance) { // outputs the options form on admin } /** * Update a particular instance * * @param array $new_instance New settings for this instance as input by the user via form() * @param array $old_instance Old settings for this instance * @return array Settings to save or bool (false) to cancel saving */ function update($new_instance, $old_instance) { // processes widget options to be saved } /** * Echo the widget content * * @param array $args Display arguments including before_title, after_title, before_widget, and after_widget * @param array $instance The settings for the particular instance of this widget */ function widget($args, $instance) { // outputs the content of the widget } } register_widget('My_Widget'); </code>
What is the quickest way to make a widget?
wordpress
I need to know if the 'Shopp' e-commerce plugin can be modified to display radio buttons instead of drop down menus for the product options. I don't need you to tell me how this can be done (though that would certainly be welcome), just if it is possible. I don't want to invest in Shopp unless it is something that has been done before and there is a thread or article on the Shopp board that explains the hack. EDIT: Seriously, I just need someone w/ access to the Shopp user forums to login and run a quick search for that kind of mod.
This example highlights the versatility of interface options you can create by using radio inputs to select a product variation rather than the default menus. This section of code could be used in place of the variations code block in either the product.php template file or the category.php template file (if you want variation inputs in your category products list). <code> &lt;?php if(shopp('product','has-variations')): ?&gt; &lt;ul class="variations"&gt; &lt;?php while(shopp('product','variations')): ?&gt; &lt;li&gt; &lt;label&gt; &lt;input type="radio" name="products[&lt;?php shopp('product','id'); ?&gt;][price]" value="&lt;?php shopp('product','variation','id'); ?&gt;" /&gt; &lt;?php shopp('product','variation','label'); ?&gt; &lt;/label&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; &lt;?php endif; ?&gt; </code> Warning Using this will make it able to add empty products to your cart (if the product has variations)
Can Shopp Commercial Plugin be hacked to display radio buttons instead of Dropdowns?
wordpress
I've been toying with the idea of developing a custom resume/portfolio theme for some time ... but just haven't gotten around to it. Lately, though, I've fallen in love with a few new site designs and feel that it's time we had a truly interactive and dynamic theme to power resumes and portfolios with WordPress. So here it is, your opportunity to participate in a WordPress crowdsourcing project: What features would you most like to see in a resume/portfolio theme for WordPress and why?
I would like to see dynamically expanding detail boxes, so you can provide optionally more details on specific areas of experience (such as a code snippet, or more complicated project information) should the interested party wish for more. That way you keep it simple and clean yet show them there is more under the hood should they wish to see it.
Feature Survey - What would you want in a resume theme?
wordpress
In my game website I would like to implement a Screenshot page where my registered users can upload images to it (it might be more then 1 screenshot page, 1 for the users and 1 for the game in question what I mean is users can upload and the staff will be using the game website available images so it would be 2 different categories or w/e). Once an image is uploaded it will be pending for approval before becoming available on the gallery page. I would like that the page that will display the list of images will be displaying it as thumbnail or resized images to a smaller size and the bigger image will show uppon click or something alike. What i would like to know is: Is there a plugin with such features ? What are my options here ? I've got a good programming background, if i were to make such changes what would be my best approch to it ? like creating a custom template page or what ?
I just found this plugin that entirelly fits my needs while I modificating the NextGen so I tought I should post it here in case some one was looking for something like this: http://wordpress.org/extend/plugins/nextgen-public-uploader/screenshots/ With this I can simple set the minimun access to subscribers and add a tag to a page and it will allow registered users to upload images to a pre-selected gallery.
Personalized Gallery what are my options?
wordpress
I need to have a bit of frequently changing content in a sidebar (the time and location of the next meeting of a club). What I'd really like is a nice widget that displays <code> the_content() </code> of a selected page or just has a rich text field and displays what's in that. I figured there would be something like this around, but I can't find it. (Maybe because the search terms are too cloudy and overloaded?) I wrote a widget that displays <code> the_content() </code> of a hardcoded page, but that's not an ideal solution.
How about the Rich Widget ?
Display some arbitrary HTML or content in a sidebar
wordpress
Im using a wfcart in my WordPress site but for some reason on certain pages WordPress drops the session I'm wondering if there is a way to enable sessions in WordPress 3?
If you need to manually enable the session globally, use this in your functions.php (I included a line for manually setting a session variable as an example, not required): <code> add_action('init', 'session_manager'); function session_manager() { if (!session_id()) { session_start(); } $_SESSION['foo'] = 'bar'; } </code> and if you wanted to manually clear the session on an event (like logging out): <code> add_action('wp_logout', 'session_logout'); function session_logout() { session_destroy(); } </code>
Enabling Sessions in WordPress 3.0
wordpress
Has anyone seen a drag&amp;drop plugin for files into the media library for WP? Would be very interested with such a plugin. Edit - Seems like Google will sponsor this project on GSoC 2011
It appears that this idea is being addressed in trac: http://core.trac.wordpress.org/ticket/13054
Drag & drop HTML5 file upload into the media library?
wordpress
A bit of a noob PHP question coming up. I am trying to create a generic archive style view for my custom post types. Ideally I want to create one generic template that can be used for all post-types. Currently I use this as my have_posts query to bring in all posts of 'custom-post-type' <code> &lt;?php $args=array( 'post_type' =&gt; 'custom-post-type.', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; -1, 'caller_get_posts'=&gt; 1 ); $my_query = null; $my_query = new WP_Query($args); if( $my_query-&gt;have_posts() ) { while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt; </code> What I want to do is swap out custom-post-type with the slug of the page so that whenever this template is assigned to a page, it will look for a custom-post-type of that name &amp; list them. Alternatively if you know of a better way of doing it - great! Cheers, George
As @Rarst mentioned in the previous comment this is going to be patched in WP3.1 The template hierarchy is "archive-customposttypename.php". WordPress 3.1 template hierarchy
Using wordpress template tags within an array
wordpress
I have several different sites running off WordPress, and the URLs tend to get fairly long and cumbersome (particularly when I try to publish them via Twitter). I recently purchased a very short domain name, and I'd like to use it as the root of a personal URL shortening service. So ... <code> http://www.eamann.com/portfolio </code> would become <code> http://eam.me/portfolio </code> <code> http://www.mindsharestrategy.com/wp-xmlrpc-movabletype/ </code> would become <code> http://eam.me/df3DF </code> <code> http://www.prosepainting.com/coffee-shop-part-1/ </code> would become <code> http://eam.me/csp1 </code> And custom things like <code> stackexchange-url </code> would become <code> http://eam.me/wpa3076 </code> Basically, I want to set up and manage my own TinyURL-like server ... but with some specific requirements: It should integrate fully with WordPress so I can dynamically create new short URLs whenever I create a page or a post (every piece of content I create on each site should have its own short URL). I can specify if I want the URL to be random (like <code> /df3Df </code> ) or I can choose a unique string instead (like <code> /wpa3076 </code> ) at the time of URL creation I should be able to view/edit/manage the URLs I have in the database from within WordPress At the moment, I'm leaning towards a standalone system like YOURLS that lives in its own database. The problem I'm facing (and I'll confess now that I haven't attempted it yet) is integrating the system fully with WordPress. I want each post to automatically suggest a short URL before I hit "publish" and then automatically create the URL when I finally do "publish" the post. I'd also like to administer all of my links from within each of the sites using the service. Is this even possible? Is there already a solution around to do this? If not, where do I start? (Cross-posted to stackexchange-url ("StackOverflow"))
I've set up YOURLS for and have been extremely pleased. With the wordpress plugin, it will automatically create a short url for you if there isn't one. And with the Admin of YOURLS you can create your own custom short url's to anything you want, granted it isn't in WP Admin. I don't believe you can set your own custom url at the post creation either, you would have to go into the YOURLS Admin to update it. The other one I looked into was http://wordpress.org/extend/plugins/short-url-plugin/ but I wanted the more powerful backend that YOURLS provided; plus the post to twitter was a bonus.
How do I set up a custom URL shortener for my posts?
wordpress
For example... <code> add_action('init', 'reg_tax'); function reg_tax() { register_taxonomy_for_object_type('category', 'attachment'); } </code> Adds a "Category" input field to the media manager and attachments editor. I'd like to know if its possible to alter this function to capture a "link destination" URL instead. The URL would be executed when the image is clicked. Also need to know how to retrieve the value for this new field. UPDATE: Thanks to Thomas Answer below, here is my final solution... <code> function my_image_attachment_fields_to_edit($form_fields, $post) { $form_fields["custom1"] = array( "label" =&gt; __("Image Links To"), "input" =&gt; "text", "value" =&gt; get_post_meta($post-&gt;ID, "_custom1", true) ); return $form_fields; } function my_image_attachment_fields_to_save($post, $attachment) { if( isset($attachment['custom1']) ){ update_post_meta($post['ID'], '_custom1', $attachment['custom1']); } return $post; } add_filter("attachment_fields_to_edit", "my_image_attachment_fields_to_edit", null, 2); add_filter("attachment_fields_to_save", "my_image_attachment_fields_to_save", null, 2); </code>
I use a very rough plugin to add information about the artist and a URL to media files. It needs some tweaking (and I need the time), but it works and may demonstrate how add the extra fields and how to use them in your theme: <code> &lt;?php /* Plugin Name: Toscho’s Media Artist Field Description: Adds two field to attachments – Artist and Artist URL – and adds this information to captions. Version: 0.1 Author: Thomas Scholz Author URI: http://toscho.de Created: 19.09.2010 */ $Toscho_Media_Artist = new Toscho_Media_Artist( array ( 'artist_name' =&gt; array ( 'public' =&gt; 'toscho_artist_name' , 'hidden' =&gt; '_toscho_artist_name' , 'label' =&gt; 'Fotograf (Name)' ) , 'artist_url' =&gt; array ( 'public' =&gt; 'toscho_artist_url' , 'hidden' =&gt; '_toscho_artist_url' , 'label' =&gt; 'Fotograf (URL)' ) ) , 'Foto: ' ); /** * Adds two fields for credits to any media file: name and URL. * * Based on the clear tutorial by Andy Blackwell: * @link http://net.tutsplus.com/?p=13076 * * @author "Thomas Scholz" * */ class Toscho_Media_Artist { public $fields = array ( 'artist_name' =&gt; array ( 'public' =&gt; 'toscho_artist_name' , 'hidden' =&gt; '_toscho_artist_name' , 'label' =&gt; 'Artist Name' ) , 'artist_url' =&gt; array ( 'public' =&gt; 'toscho_artist_url' , 'hidden' =&gt; '_toscho_artist_url' , 'label' =&gt; 'Artist URL' ) ) // Maybe its own field? , $caption_prefix , $br_before = TRUE; public function __construct( $fields = array() , $caption_prefix = 'Source: ' , $br_before = TRUE ) { $this-&gt;fields = array_merge($this-&gt;fields, $fields); $this-&gt;caption_prefix = $caption_prefix; $this-&gt;br_before = (bool) $br_before; $this-&gt;set_filter(); } public function set_filter() { add_filter( 'attachment_fields_to_edit' , array ( $this, 'add_fields' ) , 15 , 2 ); add_filter( 'attachment_fields_to_save' , array ( $this, 'save_fields' ) , 10 , 2 ); add_filter( 'img_caption_shortcode' , array ( $this, 'caption_filter' ) , 1 , 3 ); } public function add_fields($form_fields, $post) { foreach ( $this-&gt;fields as $field) { $form_fields[ $field['public'] ]['label'] = $field['label']; $form_fields[ $field['public'] ]['input'] = 'text'; $form_fields[ $field['public'] ]['value'] = get_post_meta( $post-&gt;ID , $field['hidden'] , TRUE ); } return $form_fields; } public function save_fields($post, $attachment) { foreach ( $this-&gt;fields as $field) { if ( isset ( $attachment[ $field['public'] ]) ) { update_post_meta( $post['ID'] , $field['hidden'] , $attachment[ $field['public'] ] ); } } return $post; } public function caption_filter($empty, $attr, $content = '') { /* Typical input: * [caption id="attachment_525" align="aligncenter" * width="300" caption="The caption."] * &lt;a href="http://example.com/2008/images-test/albeo-screengrab/" * rel="attachment wp-att-525"&gt;&lt;img * src="http://example.com/uploads/2010/08/albeo-screengrab4.jpg?w=300" * alt="" title="albeo-screengrab" width="300" height="276" * class="size-medium wp-image-525" /&gt;&lt;/a&gt;[/caption] */ extract( shortcode_atts( array ( 'id' =&gt; '' , 'align' =&gt; 'alignnone' , 'width' =&gt; '' , 'caption' =&gt; '' , 'nocredits' =&gt; '0' ) , $attr ) ); // Let WP handle these cases. if ( empty ($id ) or 1 == $nocredits ) { return ''; } if ( 1 &gt; (int) $width || empty ( $caption ) ) { return $content; } if ( ! empty ( $id ) ) { // Example: attachment_525 $html_id = 'id="' . esc_attr($id) . '" '; $tmp = explode('_', $id); $id = end($tmp); $sub_caption = ''; $artist_name = get_post_meta($id, $this-&gt;fields['artist_name']['hidden'], TRUE); $artist_url = get_post_meta($id, $this-&gt;fields['artist_url']['hidden'], TRUE); // Okay, at least one value. if ( '' != $artist_name . $artist_url ) { $sub_caption .= $this-&gt;br_before ? '&lt;br /&gt;' : ''; $sub_caption .= '&lt;span class="media-artist"&gt;' . $this-&gt;caption_prefix; // No name given. We use the shortened URL. if ( '' == $artist_name ) { $sub_caption .= '&lt;a rel="author" href="' . $artist_url . '"&gt;' . $this-&gt;short_url($artist_url) . '&lt;/a&gt;'; } // We have just the name. elseif ( '' == $artist_url ) { $sub_caption .= $artist_name; } // We have both. else { $sub_caption .= '&lt;a rel="author" href="' . $artist_url . '"&gt;' . $artist_name . '&lt;/a&gt;'; } $sub_caption .= '&lt;/span&gt;'; } $caption .= $sub_caption; } return '&lt;div ' . $html_id . 'class="wp-caption ' . esc_attr($align) . '" style="width: ' . (10 + (int) $width) . 'px"&gt;' . do_shortcode( $content ) . '&lt;p class="wp-caption-text"&gt;' . $caption . '&lt;/p&gt;&lt;/div&gt;'; } public function short_url($url, $max_length=20) { $real_length = mb_strlen($url, 'UTF-8'); if ( $real_length &lt;= $max_length ) { return $url; } $keep = round( $max_length / 2 ) - 1; return mb_substr($url, 0, $keep, 'UTF-8') . '…' . mb_substr($url, -$keep, $real_length, 'UTF-8'); } # @todo uninstall } </code>
How can I add a URL field to the attachments window?
wordpress
I have a post written in Microsoft Word with images, text and some formating. Is there some easy way to import this document into WordPress? Either a plugin for Word og perhaps a plugin inside WordPress? I'm looking for something simple that also converts images.
There are 3 ways you can import content from Word: Paste from Word There's a button in the editor that allows you to paste content directly from Word. This removes the special formatting Word uses to lay content out on the page and will make things work well on your site. (The button is in the "Kitchen Sink" on the Visual editor and is circled in the image below.) Drawback: you'll have to manually upload and re-add your images. HTML Editor You can also copy-paste your text into the HTML mode of the editor and it will automatically strip out the special formatting Word uses. Drawback: you'll have to manually upload and re-add your images, and you might lose some paragraph spacing in the transfer. Windows Live Writer The best option would be to use the free Live Writer application from Windows. This is a standalone desktop application that will take in content from Word almost perfectly (including images), allow you to tag, categorize, and set up your post, then remotely publish it on your site. Live Writer will also upload your images for you and automatically position them in the content just the way you had them laid out in the editor. Drawback: Live Writer only runs on Windows ... so if you're an Apple fan, you're out of luck :-(
Easy way to import a post from Word?
wordpress
The administration part for my plugin is divided into several pages and for some pages I would like to enqueue a JS source which would add jQuery functionality to various elements. Right now this is my approach: <code> function admin_register_init() { if ($_GET['page'] == 'worldexplorer_admin_location_hub') wp_enqueue_script('worldexplorer_admin_hub', WP_PLUGIN_URL.'/worldexplorer/admin/admin_hub.js'); } add_action('admin_init', 'admin_register_init'); </code> However, this requires me to check the page index of the $_GET array. Is there another way to achieve what I wish to do?
I believe there is a hook <code> admin_print_scripts-{$page} </code> which might fit. See this Load scripts only on plugin pages
Including a JS source with an admin page
wordpress
I have a blog that I often need to insert iframes into posts for various reasons (don't ask why just trust me!) When I use the "visual" view to edit my posts the WYSIWYG constatantly strips out my iframes ... I know I can keep the iframes in the post if I use the "html" view and only view/save from the "html" view ... however I'd really like to be able to use the normal WYSIWYG to edit my post without having to resort to the "html" view. Is there anything I can do to disable this behavior? I've see this post: http://wordpress.org/support/topic/wordpress-28-no-more-iframe Suggsting editing wp-includes/js/tinymce/tiny_mce_config.php but I'd really rather avoid doing something like that that would likely just break in a upgrade!
If you don't want to write your own code there is a plugin to allow embedding an <code> &lt;iframe&gt; </code> : Embed IFrame Plugin for WordPress Then just use the shortcode like this: <code> [iframe http://example.com 400 500] </code>
Make WordPress WYSIWYG not strip out iframe's
wordpress
I downloaded the free Wootheme Irrestible and if installed on a stand alone Wordpress , works very well . Now, if we enable Multiple Sites on 3.x and set this theme to be the theme of a new site it simply does not work out-of-the-box. As WooThemes Support is only for paid customers, and being this a free theme, I can ask for support directly, so I'm kindly ask here for any help. current site with IrrestibleTheme using WP 3.0.1 multi site enable is located at http://fortiusfitness.com/fblog website settings: As I don't know what might be wrong, here is all settings to this 2nd website: settings more settings and more and more and more
You really need to specify how it does not work. There are no multisite-specific theme tags. 99% of the themes out there for WordPress work in a network. If you're getting errors, check your error logs. If it's not grabbing image th8umbnails, that's a known issue - not with multisite or the timthumb script, but how the theme itself calls the images. http://www.binarymoon.co.uk/2009/10/timthumb-wordpress-mu/ Edit: actually, I have tested the Irresistible theme in mu. Worked for me. A quick checked reveals it's looking for images in a subfolder that is not there.
What changes we need to make to a theme so it can be installed as a MU Theme?
wordpress
Given a Vimeo ID, I can retrieve a thumbnail from the video via Vimeo Simple API. Rather than call the API every time my page loads I want to set the image as the post thumbnail using the <code> save_post </code> hook (similar to stackexchange-url ("this question")). My problem is that I am not familiar with URL calls in php. I would like to know: the benefits/drawbacks of using a method like curl compared to <code> WP_Http </code> . Is one "better" than the other? the order in which I should call functions to successfully set the post thumbnail. Any help would be greatly appreciated.
My favorite way of handling this problem has been to use a little documented function I discovered on another stack post: media_sideload_image </code> It works by fetching an image url to the WordPress upload dir and then associating the image to a post's attachments. You can try it like so: <code> // required libraries for media_sideload_image require_once(ABSPATH . 'wp-admin/includes/file.php'); require_once(ABSPATH . 'wp-admin/includes/media.php'); require_once(ABSPATH . 'wp-admin/includes/image.php'); // $post_id == the post you want the image to be attached to // $video_thumb_url == the vimeo video's thumb url // $description == optional description // load the image $result = media_sideload_image($video_thumb_url, $description); // then find the last image added to the post attachments $attachments = get_posts(array('numberposts' =&gt; '1', 'post_parent' =&gt; $post_id, 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'order' =&gt; 'ASC')); if(sizeof($attachments) &gt; 0){ // set image as the post thumbnail set_post_thumbnail($post_id, $attachments[0]-&gt;ID); } </code>
How to retrieve image from URL and set as featured image/post thumbnail
wordpress
hi can anyone recommend a good search engine plugin that allows the users to search for posts, blogs, forums, users, etc and shows the results as a combined result and not divided into categories? we need a good plugin in our site that will not override the normal wordpress search. we're using wordpress and buddypress. thanks
maybe this Premium Plugin can help you: http://codecanyon.net/item/relevant-search-wordpress-plugin/121503
plugin to search entire posts, blogs, forum, users
wordpress
I just wanna convert all links to no follow links which are being displayed in sidebar or footer or comments. How can i do this?
<code> wp_rel_nofollow() </code> does this for you. It is already called on <code> pre_comment_content </code> , so comments should be covered. For sidebars and footers, this depends on the widgets and other code you use there, but it should be possible to call that function there too.
How to convert all links to no follow links of particlular section of a webpage
wordpress
I am so happy that I found this site =) Well, here is my problem: I want to display the wp comments right after the post, but before the plugins content. What I have tried so far: in single-products.php file, the original code is: <code> &lt;?php the_content(); ?&gt; &lt;?php wp_link_pages(array('before' =&gt; '&lt;p&gt;&lt;strong&gt;'.__('Pages','eStore').':&lt;/strong&gt; ', 'after' =&gt; '&lt;/p&gt;', 'next_or_number' =&gt; 'number')); ?&gt; &lt;?php edit_post_link(__('Edit this page','eStore')); ?&gt; </code> I tried put the comments(comments_template()) before and after the "the_content()", but its not correct. If I put: Before the_content(), it displays the comments section before the real content After the_content(), the comments are displayed below others plugin (simple social and Five rate stars plugins) Is there anyway to insert in between them, I mean, between the post and plugins? FYI: The theme that I am using, didnt display comment, so I have to display/enable it by myself. I am using wp 3.0.1 Plugin I am using: Plugin Name: Five Star Rating (http://fsr.dingobytes.com) Plugin Name: Simple Social - Sharing Widgets &amp; Icons (Version: 0.2)
For Five Star Rating , the FAQ tells me you can leave out the shortcode from your articles (you added these to each article?), and then use <code> echo five_star_rating_func('star') </code> somewhere in your template. So this is a nice example of a plugin that offers both options. For Simple Social , you need to disable the regular hook to <code> the_content </code> , and then call the function yourself. That could be done with the following code, which you can place in your theme's <code> functions.php </code> (or at the top of your <code> single.php </code> , if you only want it gone on single pages): <code> remove_filter('the_content', 'simple_social'); </code> Then, to display it again where you want it, you call <code> simple_social() </code> with an empty content string (be sure to do this in The Loop, since it relies on the global <code> $post </code> variable): <code> echo simple_social(''); </code>
Display WordPress comments before the plugins?
wordpress
If someone comments on any post on my site, that comment gets displayed under another post. Moreover, if I login to my site. And click on logout link (under comment section) it redirects me to another article after log out. One possible reason as I read on many places, may be showing related posts. I am using following code for this <code> &lt;?php do_action('erp-show-related-posts', array('title'=&gt;'Most Related Post', 'num_to_display'=&gt;10, 'no_rp_text'=&gt;'No relevant article found.')); ?&gt; </code> Which is basically given by a wordpress plugin efficient related post .
It sounds to me like you mucked up the query and the comment form thinks the user's on the wrong post. Try adding <code> wp_reset_query(); </code> to your theme right before your theme adds the comment form. If that doesn't work, do this: <code> wp_reset_query(); global $post, wp_query; $post = $wp_query-&gt;post; setup_postdata($post); </code>
comments are coming on improper posts
wordpress
I'm just curious, because I love wordpress.
visit for demos http://wpmu.org/
Any amazing Wordpress MultiSite sites?
wordpress
I need a wordpress shopping cart that will produce 2 tier product variations. For example if you pick 'option 1' for a product, sub-options 'x' 'y' 'z' will be revealed and if you pick 'option 2', sub-options 'a' 'b' 'c' will be revealed. Im OK with a commercial cart, but I haven't found any that specifically list this functionality in their documentation and since they are commercial, I can't access their respective support forums to find out more with out first purchasing the cart. Is there a cart that supports this kind of functionality?
The e-commerce plugin Shopp for Wordpress seems to allow 2-tier product variation options. It used to be a bit buggy in the 2-tier product variation department, but I think that they've fixed those issues with the plugin now. Keep in mind that Shopp isn't free, but in my opinion it's worth every dollar. MarketPress is supposedly going to support this as well, but WPMU Dev might take a while to release a new version of it.
Wordpress shopping cart that supports 2 tier product variation options
wordpress
I want to add few custom fields to categories. So I am looking for something like <code> add_meta_box </code> but for categories. Is there any WP function like that for categories ?
You can add content to the category edit pages by hooking into the <code> edit_category_form_fields </code> (still in the form table) or <code> edit_category_form </code> (outside the table but before the submit button). Similar hooks exist for tags or custom taxonomies, check the source. To handle these extra values you need to find a good hook yourself, make sure you handle it before <code> editedtag </code> redirects you . There are no clean meta box handlers, you need to write most code yourself. But please let us know how you did it, it might be interesting for others!
anything like add_meta_box for categories?
wordpress
My WP query to fetch some custom posts should exclude private posts, but this query is returning all posts, not just public ones: <code> $wp_query = new WP_Query( 'post_type=listing&amp;post_status!=private&amp;posts_per_page=9&amp;meta_key=location_level1_value&amp;orderby=location_level1_value&amp;order=ASC&amp;paged='.$paged); </code> I've also tried using post_status=-private, but that didn't work either... What have I done wrong?
I have to wonder if post_status=public would successfully exclude. That way it's just targeting the public posts.
Why can't I exclude private posts from this query?
wordpress