question
stringlengths
0
34.8k
answer
stringlengths
0
28.3k
title
stringlengths
7
150
forum_tag
stringclasses
12 values
I'm messing with wp_rewrite and have spent the past few hours trying to figure regular expressions out again (i seem to have forgotten.) This is probably extremely easy for someone. Basically I'd like to match an alpha expression and stop at teh first occurance of a forward slash. Here's what i'm doing: I have a url http://www.mydomain.com/basename/uniquename/page/2/ I want to get uniquename out with the following <code> 'basename/(.*)/page/([0-9]{4})/?$' =&gt; 'index.php?post_type=basename&amp;uniquenametaxonomy='.$wp_rewrite-&gt;preg_index(1).'&amp;paged='.$wp_rewrite-&gt;preg_index(2), </code> obviously (.*) matches /page/ as well as uniquename and provides me with a query string looking like ?post_type=basname&amp;uniquenametaxonomy=uniquename%2Fpage%2F2 I'd like it to be ?post_type=basname&amp;uniquenametaxonomy=uniquename&amp;paged=2 I know it has to be extremely easy, I'd like to match uniquename and stop at the first occurance of a forward slash.
Replace <code> (.*) </code> with <code> (.*?) </code> . The question mark makes it 'lazy'. Also, replace <code> ([0-9]{4}) </code> with <code> (\d+) </code> . See http://www.regular-expressions.info/reference.html
Use Regular Expression to get tag from permalink url during wp_rewrite in generate_rewrite_rules
wordpress
My code is <code> if( $wpdb-&gt;update($tableName,array('opt_value'=&gt;$cInfo),array('opt_name'=&gt;'showWeatherWidget'))) //show success message else // show failure message </code> This is not correct, <code> $wpdb-&gt;update() </code> returns false if it doesn't change any data, but there were no errors. Can someone tell me the proper way to display a success message that a field was updated?
The correct way is with <code> === FALSE </code> which differentiates from equalling zero, which is what a succesful query with no results returns. <code> if( $wpdb-&gt;update($tableName,array('opt_value'=&gt;$cInfo),array('opt_name'=&gt;'showWeatherWidget')) === FALSE) //show failure message else // show success message </code>
Check for success of $wpdb-> update() correctly
wordpress
This feels like a fairly simple question, though I fear, may be a complicated answer. Is there an way (via plugin or code) to make a theme change some basic CSS elements based on a taxonomy term. So if you have camera brands, and you site is all about cameras. Can you have pages about Kodak use a CSS file where colors are blue, and if Cannon it uses a CSS file that is red, etc. Basically you sub-theme your theme based on a taxonomy term?
Yes, you can. In many ways. One way is to have custom templates based on tag or category slug . So, you just tag your posts appropriately and then WordPress will automatically select appropriate template. If the template difference are miniscule, you can use php includes or wordpress includes to keep common content in other files. Or you could do a custom include based on the value of the tag from the main theme file and provide CSS reference that way. Or have inline CSS again controlled by php code inside the template.
Sub-Theme (based on Taxonomies)
wordpress
Is it possible using WP_Query to return a filtered list of items based on the following criteria set? I seem to be struggling as there are numerous queries against custom fields. <code> Select all posts that are of type business_club (post_type) Where the post has a zone of 'Asia' (meta_value) Order by country ASC (meta_value) then by town ASC (meta_value) then by title (wp value) </code> Any help is greatly appreciated.
The way around it was to build a custom query. More information on this can be viewed on the Wordpress codex at http://codex.wordpress.org/Displaying_Posts_Using_a_Custom_Select_Query . My final code looked as follows <code> &lt;?php $row = 0; $zone = $_GET['zone']; if (!$zone) $zone = "United Kingdom"; ?&gt; &lt;table class="formattedTable" cellspacing="1" cellpadding="0"&gt; &lt;tr&gt; &lt;th width="140"&gt;Country&lt;/th&gt; &lt;th width="140"&gt;Town&lt;/th&gt; &lt;th&gt;Club&lt;/th&gt; &lt;/tr&gt; &lt;?php $query = " SELECT posts.* FROM $wpdb-&gt;posts posts INNER JOIN $wpdb-&gt;postmeta meta1 ON posts.ID = meta1.post_ID INNER JOIN $wpdb-&gt;postmeta meta2 ON posts.ID = meta2.post_ID INNER JOIN $wpdb-&gt;postmeta meta3 ON posts.ID = meta3.post_ID WHERE posts.post_type = 'club' AND posts.post_status = 'publish' AND meta1.meta_key = '_club-zone' AND meta1.meta_value = '$zone' AND meta2.meta_key = '_club-country' AND meta3.meta_key = '_club-town' ORDER BY meta2.meta_value, meta3.meta_value, posts.post_title"; $posts = $wpdb-&gt;get_results($query, object); if ($posts) foreach($posts as $post) { global $post; setup_postdata($post); echo '&lt;tr class="' . ($row % 2 == 0 ? 'odd' : 'even') . '"&gt;'; echo '&lt;td&gt;' . get_post_meta(get_the_ID(), '_club-country', true) . '&lt;/td&gt;'; echo '&lt;td&gt;' . get_post_meta(get_the_ID(), '_club-town', true) . '&lt;/td&gt;'; echo '&lt;td&gt;&lt;a href="' . get_permalink(get_the_ID()) . '"&gt;' . get_the_title() . '&lt;/a&gt;&lt;/td&gt;'; echo '&lt;/tr&gt;'; $row++; } ?&gt; &lt;/table&gt; </code>
WP_Query, custom sort and custom filter
wordpress
I am currently working on the completion of a custom template and my last hurdle is to be able to remove the comments feed link being added to the head of the page. For example: in firefox when you open any of the pages on my site there is an rss icon, when clicked I am shown 3 options to add to my reader but the last two are related to comments. The culprits are located in the <code> &lt;link rel="alternate" type="application/rss+xml" title="Example Title &amp;raquo; Comments Feed" href="http://example.com/comments/feed" /&gt; &lt;link rel="alternate" type="application/rss+xml" title="Example Title &amp;raquo; Home Page Comments Feed" href="http://example.com/home-page/feed" /&gt; </code> I wish to have the main feed, which contains blog posts from the blog area of the site but do not want any comments, therefore comment feeds are useless to me! I am wondering if there is a way I can remove these via the functions.php or some way through wordpress rather than coming up with another (messier) solution? Thanks, Tristan
Add this to functions.php <code> function remove_comments_rss( $for_comments ) { return; } add_filter('post_comments_feed_link','remove_comments_rss'); </code>
Disable comment rss feeds for pages in wordpress
wordpress
I'm trying to figure out how to link a logged-in user to his profile settings, but I can't seem to find a function that generates this link (like <code> wp_settings_url() </code> or <code> wp_profile_url() </code> ) Is there a default function for this?
The user edit page of the current user is <code> /wp-admin/profile.php </code> , so you can just do <code> admin_url( 'profile.php' ) </code> , which is the way it is used in the WP source code.
Link to user's profile settings page?
wordpress
Is it possible in wordpress to customise the search page to show certain information depending on the result? For example I run a motorsport site and if I searched for Jenson Button it would return a page with all the posts mentioning Jenson Button ( http://www.thecheckeredflag.co.uk/?s=Jenson+Button ). Is it possible to customise this page to show a div at the top with relevant links about that Jenson Button or whatever driver/search term the user is looking for?
You can create a template file in your theme that is used to display search results. It is called <code> search.php </code> . If it does not exist the <code> index.php </code> file is displayed. At the top of that file, or wherever you want, you can place extra code that queries your special posts (depending on how you saved driver data). You can get the current search query by calling <code> get_query_var( 's' ) </code> .
Customise search page depending on result
wordpress
I really like having my code all properly indented and all, but all the code generated by wordpress, like the one that appears on the header when we use wp_head(), loses all the indentation. I think it doesn't really matter, neither the users nor the search engines give a s**t about the code being indented or not, but when it comes to debugging, it really helps a lot. Do you know of any plugin or option or something to fix this?
I don't think correct global indentation is possible without massive (and inefficient) output buffering to change it. Since you are primarily interested in this for debug purposes I suggest using some tool that will format and color-code output (of any page btw, not just those that you control). Firebug and View Source Chart work nicely for me.
Proper indentation of code generated inside hooks
wordpress
I'm trying to create a conditional statement for the content width in the functions.php of my theme. So some categories will have a content_width of 580, some will have 900. This will make the oEmbed work correctly wherever it's used. Usually, you would have this in your functions.php: <code> if ( ! isset( $content_width ) ) $content_width = 900; </code> I want something like this: <code> if(in_category(array('news','blog'))) { $content_width = 580; } elseif(is_page()) { $content_width = 580; } else { $content_width = 900; } </code> When I have this in my functions.php the content width becomes whatever I write in the last line. Am I missing something? Is this even possible? Thanks!
No, its not possible. $content_width is a theme-wide constant, and its set in functions.php before any of the query conditionals are set. $content_width is used to determine the intermediate image sizes in <code> image_send_to_editor </code> . The "large" image size will be set to the value of $content_width. If you need to modify those sizes on a per-category basis, you can hook into that filter... see my answer on the question stackexchange-url ("change set_post_thumbnail_size according to post type admin page") for a general example of how this can be done (note that this will almost always fail if you're trying to do it by category, as the post category is almost always not set when the user first uploads an image - setting it by post type is a little more reliable) No matter how wide your posts and pages are, set $content_width to the widest image you want a user to include in a post.
how to create a conditional content_width for a wordpress theme?
wordpress
A website I work on recently posted a file at the root of their website named "2011.html." Now, any 2011 blog posts with the permalink structure of year/month/day/post-name do not work, and instead load the 2011.html file. Trying to bring up the archive at domain.com/2011/ also incorrectly brings up the file. 2010 and other years work as expected. Is there any way I can use mod_rewrite to only acknowledge this file when 2011.html is explicitly in the URL, and use the standard permalink structure with every other URL so that the blog functionality is restored? The link to this file was sent out in a marketing e-mail, and is receiving a lot of activity so it can't be moved or renamed.
The reason that's happening at all is because of content negotiation . <code> /2011.html </code> wouldn't normally be accessible through <code> /2011/ </code> , but content negotiation is making Apache automatically look for files named <code> 2011 </code> (whatever the extension) when it can't find the folder before it passes control to WordPress. This can be quite useful, but if you don't particularly need content negotiation (WordPress itself doesn't need it), you can turn it off by adding this to your <code> .htaccess </code> : <code> Options -MultiViews </code> If that doesn't work, or you do need content negotiation, you could rename the <code> 2011.html </code> to something else, and use mod_rewrite to make sure the link still works. E.g. rename <code> 2011.html </code> to <code> happynewyear.html </code> and then add this to your <code> .htaccess </code> (before the other RewriteRules): <code> RewriteRule ^2011\.html happynewyear.html [L] </code>
My permalinks are broken! Can I use mod_rewrite to ignore a physical file?
wordpress
Hi guys I have a headache on this I make a multicheck with this tutorial wpshout.com/create-an-in-post-theme-options-meta-box-in-wordpress/ the problem is it doesn't save all checked value and it doesn't checked the checked value when editing post. Here are my code I add here an array for muticheckbox <code> &lt;?php function hybrid_post_meta_boxes() { /* Array of the meta box options. */ $meta_boxes = array( 'title' =&gt; array( 'name' =&gt; 'Title', 'title' =&gt; __('Title', 'hybrid'), 'type' =&gt; 'text' ), 'description' =&gt; array( 'name' =&gt; 'Description', 'title' =&gt; __('Description', 'hybrid'), 'type' =&gt; 'textarea' ), 'location' =&gt; array( 'name' =&gt; 'location', 'title' =&gt; __('Location:', 'hybrid'), 'type' =&gt; 'check', 'options' =&gt; array( 'AL' =&gt; 'Alabama', 'CA' =&gt; 'California', 'DE' =&gt; 'Delaware', ), ); return apply_filters( 'hybrid_post_meta_boxes', $meta_boxes ); } ?&gt; </code> I add else statement for multi checkbox <code> &lt;?php function post_meta_boxes() { global $post; $meta_boxes = hybrid_post_meta_boxes(); ?&gt; &lt;table class="form-table"&gt; &lt;?php foreach ( $meta_boxes as $meta ) : $value = get_post_meta( $post-&gt;ID, $meta['name'], true ); if ( $meta['type'] == 'text' ) get_meta_text_input( $meta, $value ); elseif ( $meta['type'] == 'textarea' ) get_meta_textarea( $meta, $value ); elseif ( $meta['type'] == 'select' ) get_meta_select( $meta, $value ); elseif ( $meta['type'] == 'check' ) get_meta_check( $meta, $value ); endforeach; ?&gt; &lt;/table&gt; </code> I made a function for multicheck <code> &lt;?php function get_meta_check( $args = array(), $value = false ) { extract( $args ); ?&gt; &lt;tr&gt; &lt;th style="width:10%;"&gt; &lt;label for="&lt;?php echo $name; ?&gt;"&gt;&lt;?php echo $title; ?&gt;&lt;/label&gt; &lt;/th&gt; &lt;td&gt; &lt;?php foreach ( $options as $option ) : ?&gt; &lt;input type="checkbox" name="&lt;?php echo $name; ?&gt;" id="&lt;?php echo $name; ?&gt;" value=", &lt;?php echo $option; ?&gt;, " &lt;?php if ( htmlentities( $value, ENT_QUOTES ) == $option ) echo ' checked="checked"'; ?&gt; /&gt; &lt;?php echo $option; ?&gt;, &lt;?php endforeach; ?&gt; &lt;input type="hidden" name="&lt;?php echo $name; ?&gt;_noncename" id="&lt;?php echo $name; ?&gt;_noncename" value="&lt;?php echo wp_create_nonce( plugin_basename( __FILE__ ) ); ?&gt;" /&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php } ?&gt; </code> How can I do code with saving all value of checked box? thanks! UPDATE <code> function save_meta_data( $post_id ) { global $post; if ( 'page' == $_POST['post_type'] ) $meta_boxes = array_merge( page_meta_boxes() ); else $meta_boxes = array_merge( post_meta_boxes() ); foreach ( $meta_boxes as $meta_box ) : if ( !wp_verify_nonce( $_POST[$meta_box['name'] . '_noncename'], plugin_basename( __FILE__ ) ) ) return $post_id; if ( 'page' == $_POST['post_type'] &amp;&amp; !current_user_can( 'edit_page', $post_id ) ) return $post_id; elseif ( 'post' == $_POST['post_type'] &amp;&amp; !current_user_can( 'edit_post', $post_id ) ) return $post_id; $data = stripslashes( $_POST[$meta_box['name']] ); if ( get_post_meta( $post_id, $meta_box['name'] ) == '' ) add_post_meta( $post_id, $meta_box['name'], $data, true ); elseif ( $data != get_post_meta( $post_id, $meta_box['name'], true ) ) update_post_meta( $post_id, $meta_box['name'], $data ); elseif ( $data == '' ) delete_post_meta( $post_id, $meta_box['name'], get_post_meta( $post_id, $meta_box['name'], true ) ); endforeach; } ?&gt; </code>
I took the example code you suggested and changed the following to get multicheck support: <code> // Add this at the end of the file // A good prefix for your name prevents problems later! function wpse6513_get_meta_check( $args = array(), $current_values = array() ) { extract( $args ); $name_esc = esc_attr( $name ); if ( ! is_array( $current_values ) ) { $current_values = array(); } echo '&lt;tr&gt;'; echo '&lt;th style="width: 10%"&gt;'; echo '&lt;label for="' . $name_esc . '"&gt;' . esc_html( $title ) . '&lt;/label&gt;'; echo '&lt;/th&gt;'; echo '&lt;td&gt;'; foreach ( $options as $option_value =&gt; $option_label ) { $option_value_esc = esc_attr( $option_value ); echo '&lt;label&gt;&lt;input type="checkbox" name="' . $name_esc . '[]" id="' . $name_esc . '_' . $option_value_esc . '" value="' . $option_value_esc . '"'; if ( in_array( $option_value, $current_values ) ) { echo ' checked="checked"'; } echo '/&gt; ' . esc_html( $option_label ); echo '&lt;/label&gt;&lt;br/&gt;'; } echo '&lt;input type="hidden" name="' . $name_esc . '_noncename" id="' . $name_esc . '_noncename" value="' . wp_create_nonce( plugin_basename( __FILE__ ) ) . '" /&gt;'; echo '&lt;/td&gt;'; echo '&lt;/tr&gt;'; } </code> In <code> hybrid_save_meta_data() </code> : <code> // Replace this line: $data = stripslashes( $_POST[$meta_box['name']] ); // By these lines: $data = array_key_exists( $meta_box['name'], $_POST ) ? $_POST[$meta_box['name']] : ''; if ( is_array( $data ) ) { $data = array_map( 'stripslashes', $data ); } else { $data = stripslashes( $data ); } </code> And of course, in <code> post_meta_boxes() </code> : <code> // Add this to the `$meta['type']` if/else list elseif ( $meta['type'] == 'check' ) wpse6513_get_meta_check( $meta, $value ); </code> Now you can handle "multichecks" of the form you suggested: <code> 'location' =&gt; array( 'name' =&gt; 'location', 'title' =&gt; __('Location:', 'hybrid'), 'type' =&gt; 'check', 'options' =&gt; array( 'AL' =&gt; 'Alabama', 'CA' =&gt; 'California', 'DE' =&gt; 'Delaware', ), ), </code> Finally some code to prevent warnings (which you won't see unless you enable <code> WP_DEBUG </code> ): <code> // Replace all `wp_specialchar()` calls with `esc_attr()` // Add these lines in `hybrid_save_meta_data()`: // At the start, after `global $post`: if ( ! array_key_exists( 'post_type', $_POST ) ) { return $post_id; } // In the foreach loop, instead of: if ( !wp_verify_nonce( $_POST[$meta_box['name'] . '_noncename'], plugin_basename( __FILE__ ) ) ) return $post_id; // Write: $nonce_name = $meta_box['name'] . '_noncename'; if ( ! array_key_exists( $nonce_name, $_POST ) || !wp_verify_nonce( $_POST[$nonce_name], plugin_basename( __FILE__ ) ) ) return $post_id; </code>
multicheck box for post metabox
wordpress
I've been browsing all over google for a solution to this. I'm writing a custom post types plugin for work to log-in visitors that we get. I initially wrote a mock-up without custom post types, then I came around here from a google search and saw a screenshot that showed an example of custom post types to store information about Attorneys. It showed that someone redesigned the "add new"/"edit" page for custom post types with a whole new interface. I was wondering if wordpress @ stackexchange would have any resources to redesign the custom post types "add/edit" pages. I can't remember the search terms that I did to find that article however. Thanks, -Zack
The question / answer you are referring to was stackexchange-url ("Tips for using WordPress as a CMS"). The screenshots posted in that answer were created using the <code> register_meta_box_cb </code> argument that is available to for custom post types. register_meta_box_cb must specify a callback function that contains the code for the meta box. To create the meta box you can use the WordPress built in add_meta_box function which also requires a function to save the entered data when the post is saved. Here is some example code that I created to add 2 custom meta boxes to my portfolio post type I use on my personal website. The "Projects" post type I created contained this argument: <code> 'register_meta_box_cb' =&gt; 'c3m_project_meta', </code> The first function below is the call back function for register_meta_box_cb. The following 2 output the html for the meta boxes on the add post page and the last 2 save the entered data. <code> function c3m_project_meta() { add_meta_box('_c3m_project_url', __('Enter Website Url') , 'c3m_project_url', 'project', 'side', 'low'); add_meta_box('_c3m_project_work', __('Enter Work Done on Project') , 'c3m_project_work', 'project', 'side', 'low'); } function c3m_project_url($post) { global $post; echo '&lt;input type="hidden" name="banner-buttonmeta_noncename" id="banner-buttonmeta_noncename" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" /&gt;'; $projecturl = get_post_meta($post-&gt;ID, '_projecturl', true); echo '&lt;input type="text" name="_projecturl" value="' . $projecturl . '" class="widefat" /&gt;' ; } function c3m_project_work($post) { global $post; echo '&lt;input type="hidden" name="banner-buttonmeta_noncename" id="banner-buttonmeta_noncename" value="' . wp_create_nonce( plugin_basename(__FILE__) ) . '" /&gt;'; $projectwork = get_post_meta($post-&gt;ID, '_projectwork', true); echo '&lt;input type="text" name="_projectwork" value="' . $projectwork . '" class="widefat" /&gt;' ; } add_action('admin_init', 'c3m_project_meta'); function c3m_save_project_meta( $post_id , $post ) { if ( !wp_verify_nonce( $_POST [ 'banner-buttonmeta_noncename' ], plugin_basename( __FILE__ ) )) { return $post -&gt;ID; } if ( !current_user_can( 'edit_post' , $post -&gt;ID )) return $post -&gt;ID; $c3m_projecturl [ '_projecturl' ] = $_POST [ '_projecturl' ]; foreach ( $c3m_projecturl as $key =&gt; $value ) { if ( $post -&gt;post_type == 'revision' ) return ; $value = implode( ',' , ( array ) $value ); if (get_post_meta( $post -&gt;ID, $key , FALSE)) { update_post_meta( $post -&gt;ID, $key , $value ); } else { add_post_meta( $post -&gt;ID, $key , $value ); } if (! $value ) delete_post_meta( $post -&gt;ID, $key ); } $c3m_projectwork [ '_projectwork' ] = $_POST [ '_projectwork' ]; foreach ( $c3m_projectwork as $key =&gt; $value ) { if ( $post -&gt;post_type == 'revision' ) return ; $value = implode( ',' , ( array ) $value ); if (get_post_meta( $post -&gt;ID, $key , FALSE)) { update_post_meta( $post -&gt;ID, $key , $value ); } else { add_post_meta( $post -&gt;ID, $key , $value ); } if (! $value ) delete_post_meta( $post -&gt;ID, $key ); } } add_action( 'save_post' , 'c3m_save_project_meta' , 1, 2); </code>
Redesigning Custom Post Type "Add New" page
wordpress
I've been working lots with categories lately, what with the increased awareness and demand for themed or silo'd site structures. To that end, I'm looking to enhance my category landing pages by relabeling the "Description" field as "Summary Description" and adding a new field called "Detailed Description". I will be using the "Summary Description" field on my category index page (a listing of all my site's categories) and I want to use this new "Detailed Description" field to show on the landing page for each category. So I need a rich text edit field added to the Category Edit Screen. Does WordPress make it easy to create an instance of a rich text edit field, perhaps pulling a light version of the post/page editor? I probably don't need a toolbar, but it might be nice to have some basic formatting buttons like B, I, U, hyperlink, etc...
http://www.laptoptips.ca/projects/category-description-editor/ this works very good. about adding another field, I'v tried @MikeSchinkel solution here stackexchange-url ("Adding Fields to the Category, Tag and Custom Taxonomy Edit Screen in the WordPress Admin?") and it works very good also.
How to add a WYSIWYG text editor to the Category Edit Screen
wordpress
I think I'm pretty close to cracking this nut :) I'm trying to add a set of custom fields to the Category editor. Since I'm not dealing with post meta, I believe I'll be writing my custom category field values to the wp_term_taxonomy table rather than the wp_options table. Is this correct? If there are any examples of how to do this, please share a link or bit of code. I'm not sure how to capture and save my custom category fields. Here's my code... <code> //add the hook to place the form on the category editor screen add_action('edit_category_form','ce4_category_admin'); //Adds the custom title box to the category editor function ce4_category_admin($category){ echo "category: ".$category-&gt;term_id; //great, I got a reference to the term_id, now I need to get/set my custom fields with this key ?&gt; &lt;table class="form-table"&gt; &lt;tr class="form-field"&gt; &lt;th scope="row" valign="top"&gt;&lt;label for="_ce4-categoryTitle"&gt;Full Category Title&lt;/label&gt;&lt;/th&gt; &lt;td&gt;&lt;input name="_ce4-categoryTitle" id="_ce4-categoryTitle" type="text" size="40" aria-required="false" value="&lt;?php echo get_taxonomy($category-&gt;term_id, '_ce4-categoryTitle'); ?&gt;" /&gt; &lt;p class="description"&gt;The title is optional but will be used in place of the name on the home page category index.&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="form-field"&gt; &lt;th scope="row" valign="top"&gt;&lt;label for="_ce4_fullDescription"&gt;Full Category Text for Landing Page&lt;/label&gt;&lt;/th&gt; &lt;td&gt;&lt;textarea style="height:70px; width:100%;margin-left:-5px;" name="_ce4_fullDescription" id="_ce4_fullDescription"&gt;&lt;?php echo get_taxonomy($category-&gt;term_id, '_ce4_fullDescription'); ?&gt;&lt;/textarea&gt; &lt;p class="description"&gt;This text will appear on the category landing page when viewing all articles in a category. The image, you supply above, if any, will be used here and this content will wrap around it.&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;?php } //How to save the custom field data? Normally I'd use.. //add_action('save_post', 'custom_save_function'); //but this is not a post, so perhaps there's another method? </code>
No. You have to use <code> wp_options </code> , because you can't create new fields in the wp_term_taxonomy table (If you do, in the next WP update you'll loose them). So: <code> // the option name define('MY_CATEGORY_FIELDS', 'my_category_fields_option'); // your fields (the form) add_filter('edit_category_form', 'my_category_fields'); function my_category_fields($tag) { $tag_extra_fields = get_option(MY_CATEGORY_FIELDS); ?&gt; &lt;table class="form-table"&gt; &lt;tr class="form-field"&gt; &lt;th scope="row" valign="top"&gt;&lt;label for="_ce4-categoryTitle"&gt;Full Category Title&lt;/label&gt;&lt;/th&gt; &lt;td&gt;&lt;input name="_ce4-categoryTitle" id="_ce4-categoryTitle" type="text" size="40" aria-required="false" value="&lt;?php echo $tag_extra_fields[$tag-&gt;term_id]['my_title']; ?&gt;" /&gt; &lt;p class="description"&gt;The title is optional but will be used in place of the name on the home page category index.&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr class="form-field"&gt; &lt;th scope="row" valign="top"&gt;&lt;label for="_ce4_fullDescription"&gt;Full Category Text for Landing Page&lt;/label&gt;&lt;/th&gt; &lt;td&gt;&lt;textarea style="height:70px; width:100%;margin-left:-5px;" name="_ce4_fullDescription" id="_ce4_fullDescription"&gt;&lt;?php echo $tag_extra_fields[$tag-&gt;term_id]['my_description']; ?&gt;&lt;/textarea&gt; &lt;p class="description"&gt;This text will appear on the category landing page when viewing all articles in a category. The image, you supply above, if any, will be used here and this content will wrap around it.&lt;/p&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;?php } // when the form gets submitted, and the category gets updated (in your case the option will get updated with the values of your custom fields above add_filter('edited_terms', 'update_my_category_fields'); function update_my_category_fields($term_id) { if($_POST['taxonomy'] == 'category'): $tag_extra_fields = get_option(MY_CATEGORY_FIELDS); $tag_extra_fields[$term_id]['my_title'] = strip_tags($_POST['_ce4-categoryTitle']); $tag_extra_fields[$term_id]['my_description'] = strip_tags($_POST['_ce4_fullDescription']); update_option(MY_CATEGORY_FIELDS, $tag_extra_fields); endif; } // when a category is removed add_filter('deleted_term_taxonomy', 'remove_my_category_fields'); function remove_my_category_fields($term_id) { if($_POST['taxonomy'] == 'category'): $tag_extra_fields = get_option(MY_CATEGORY_FIELDS); unset($tag_extra_fields[$term_id]); update_option(MY_CATEGORY_FIELDS, $tag_extra_fields); endif; } </code> There might be some category-related hooks for the last two, I didn't search for them. I just adapted the code above from a old theme of mine in which the admin can attach a image to a custom taxonomy term...
Any examples of adding custom fields to the category editor?
wordpress
register plus no longer works with WP 3.0 and has been replaced by register plus redux. I haven't found anything about upgrading to that plugin and keeping all the data, does anybody have any experience with that?
I didn't get an answer here, but I did migrate my site to regi-plus-redux. I did have to recreate all of the custom fields, assuming the custom fields were recreated w/ the exact same name and options they did show up for the users after the migration. It wasn't a difficult migration, and anyone using regi-plus who wants to upgrade to 2.7+ will need to make the migration, don't worry it won't cause you problems.
Transfer from register plus to register plus redux plugin
wordpress
After following the advice in a previous question (stackexchange-url ("here")) I've managed to nuke my spam comments. I now, however, find that every day I have a few new members sign up to the site with rubbish e-mail addresses like [email protected]. I could close sign-ups but I'd rather not as I'm hoping the site will beceome a bit more popular and would like to encourage comments.
I have been using Recaptcha which has the added benefit of helping to translate literature. (!)The plugin linked above will add Re-Captcha to your comments or registration form or both. It also has features like themes for the captcha forms. Definitely worth looking into.
Reducing spammy user sign-ups
wordpress
Any way to change the wp-login.php url? It seems insecure that everyone that's ever used Wordpress could easily see if your site is using it, and get right to the login page. There used to be a plugin called "Stealth login," but it wasn't updated. (And hence our reluctance to rely on plugins).
Hi @David: If you are doing this for your own site then using <code> .htaccess </code> might be the easiest way although it could get tricky if you want to make it work for a plugin as there would be lots of different subtle configuration differences to support. Here are some articles that could help; not all are directly answering your question but they all address your security concern in one way or another: Hide WordPress WP-Admin Login Page <a href="stackexchange-url How to prevent attacks on WordPress wp-login.php page Secure Your WordPress, Playing With Your .htaccess File. How to: change from wp-login.php to login How to protect wp-login and wp-admin Hardening Wordpress with Mod Rewrite and htaccess And of course that's no blog expert on Apache and WordPress than the guy who writes AskApache . Be sure to check out these: AskApache Password Protection, For WordPress Security with Apache htaccess Tutorial The list of "WordPress" tagged posts on AskApache
Is there any way to rename or hide wp-login.php?
wordpress
I am developing a website for a record label and the basically it uses quite a few custom post types for various pieces of information. My problem is that I feel the same bits of information are being repeated, rather than shared. I have an artists custom post type, however on the homepage there is a carousel with artists as well but different pieces of information to display. So I have a "homepage carousel" custom post type of which I have to enter the artist names and info, as well as an image and also an "artists" custom post type with some of the same information entered again. The client is probably not going to like having to enter the same information into multiple custom post types all of the time, is it possible to make a post type inherit from another? So I can tell my "homepage carousel" post type to inherit from an artists post type so the artist information is shared and doesn't have to be re-entered again? At present I have created a custom taxonomy called artists and entered in all possible artist names and then for example in the "homepage carousel" post type I select the artist in the right hand side as being the category. This works well in a way, however you still need to enter a title or you get some "Autosave" nonsense being saved as the title which will make editing and sorting difficult down the track. Is there perhaps a way to set the title as the category "artist" that has been selected? Let me know if you don't quite understand and I'll try and elaborate a bit more. I basically want to share a centralised list of artists and information of which I can inherit from in other post types. * Update * A bit more elaboration on my original question. Here are my defined post types and the information that they hold. What I want to do is set up a shared relationship between my "artists" post type and other post types that relate to the artist in some way. Post type : artists Fields : Title, Wysiwyg Editor, Featured Image, Facebook URL, Twitter Username, Website URL. Post type : homepage_carousel Fields : Title, Learn More Link, Buy CD Link, Buy MP3 Link A carousel item corresponds to an artist defined in the artists post type above. So the ability to relate this post type to the artists post type is what I want. Post type : videos Fields : Title, Video Embed Code (455px), Video Embed Code (466px), Video Embed Code (608px), Video description. A video item corresponds to an artist defined in the artists post type. I want to be able to assign a video to an artist. As you can see I want to basically set up a many-to-one relationship or is it one-to-many relationship? One of those (I think). I've started messing with this plugin: http://wordpress.org/extend/plugins/posts-to-posts/ - but I don't quite understand how to properly use it yet, I think it's something that I want. So if someone has used this before, your help would be appreciated. Whilst I am aware of custom taxonomies and terms, I think that what I am wanting goes way beyond the requirements I am seeking as I am dealing with multiple pieces of information and merely want to tie 2 post types together some how.
I have partly solved my own question so-to-speak. I've been trying to get post type relationships working for ages and the plugin relation post types as mentioned in my comment to Christopher's answer. It is far from perfect, but I worked out how to get this plugin: http://wordpress.org/extend/plugins/relation-post-types/ - working (albeit not that pretty). The following code will fetch a homepage carousel item and then an associated artist name. This can be modified to get related post meta as well. I wanted to use Scribu's posts 2 posts plugin, but couldn't work out how to use it. <code> $carousels = get_posts(array('post_type' =&gt; 'homepage_carousel')); $counter = count($carousels); $increment = 0; foreach($carousels as $carousel): $image = wp_get_attachment_image_src( get_post_thumbnail_id( $carousel-&gt;ID ), 'large' ); $related_ids = rpt_get_object_relation($carousel-&gt;ID, array('artists')); foreach ($related_ids as $related_id) { $related_post[] = get_post($related_id); } &lt;li style="background: transparent url(&lt;?php echo $image[0]; ?&gt;) no-repeat;"&gt; &lt;div class="carousel_content"&gt; &lt;p class="large_heading"&gt;&lt;?php echo $related_post[$increment]-&gt;post_title; ?&gt;&lt;/p&gt; &lt;p class="carousel_meta"&gt; &lt;?php if (get_post_meta($carousel-&gt;ID, 'learn_more_link', true)): ?&gt; &lt;?php $link = true; ?&gt; &lt;a href="&lt;?php echo get_post_meta($carousel-&gt;ID, 'learn_more_link', true); ?&gt;"&gt;Learn More&lt;/a&gt; &lt;?php endif; ?&gt; &lt;?php if (get_post_meta($carousel-&gt;ID, 'buy_cd_link', true)): ?&gt; &lt;?php $link2 = true; ?&gt; &lt;?php if ($link): ?&gt; | &lt;?php endif; ?&gt; &lt;a href="&lt;?php echo get_post_meta($carousel-&gt;ID, 'buy_cd_link', true); ?&gt;"&gt;Buy CD&lt;/a&gt; &lt;?php endif; ?&gt; &lt;?php if (get_post_meta($carousel-&gt;ID, 'buy_mp3_link', true)): ?&gt; &lt;?php if ($link2 || $link): ?&gt; | &lt;?php endif; ?&gt;&lt;a href="&lt;?php echo get_post_meta($carousel-&gt;ID, 'buy_mp3_link', true); ?&gt;"&gt;Buy MP3&lt;/a&gt; &lt;?php endif; ?&gt; &lt;/p&gt; &lt;/div&gt; </code> As you can see this is very hacky and by no means a definitive solution. It worked for me, but I am still unhappy with how the above code works. To get associated post meta it would need more code. As there is no answer, should this perhaps become a wiki more than a question perhaps? As the solutions listed here will not always be current as Wordpress is constantly evolving and new plugins being released.
Is It Possible To Have Shared Wordpress Custom Post Types?
wordpress
I have a blog installed on my site using Wordpress. Last week I upgraded Wordpress from 2.6 to 3.0.4 (I had to do this manually). All went well, or so I thought, but I have just noticed that the content of an existing page has vanished. The page URL still works, but all content has disappeared - doctype, html tags, body tags, everything. Please note, this is specific to pages - posts are still displaying fine. I have since created a brand new page which does not display the content either. Things I have tried include <code> * Switching to a freshly installed theme * Reverting the page to an older version * Deactivating all plugins * Setting the problem page to draft, and back again * Deleting the .htaccess file </code> I suspect it's a database problem and have contacted my hosting company who have said the only thing they can do is restore the DB from a backup, but that I should consider it a last resort. Does anyone have any further ideas what to try?
Thanks everyone for your suggestions - the page is now back up and running, but I am not certain why. My theory is that I actually fixed it by deleting the .htaccess file which I removed from the root of <code> /public_html </code> and assumed would be recreated by Wordpress. It's not been replaced in the <code> /public_html </code> folder, but without me noticing a .htaccess file was created in the <code> /public_html/blog </code> folder (where the blog is kept). As I didn't notice this at first I can't be certain this was the solution, but it is my best guess.
The entire content of my Wordpress page has disappeared
wordpress
I've collected a few plugins that each have specific functionality I need for what would otherwise be a single large plugin. Is it possible to bundle these into a single installable zip?
Go through each plugin file and remove the plugin header. Create a loader.php file. Something like this: <code> &lt;?php /* Plugin Name: Combined Plugin Description: Contains plugin a, plugin b and plugin c */ include dirname(__FILE__) . '/plugin-a.php'; include dirname(__FILE__) . '/plugin-b.php'; include dirname(__FILE__) . '/plugin-c.php'; </code>
Combine multiple plugins into one?
wordpress
I'm working on a rather odd implementation that stretches the limits of WP a little - its a healthcare site where patients are a custom post type and procedure requests related to each patient are stored in comments on that post. I started off by storing alot of data in commentmeta, but I want an easier way to access it than having to pull from a meta table. I'd also like to be able to use the built-in functions where available ( wp_insert_comment can set most of the fields in wp_comments table through the arguments passed to it). My question is - where are these other values set and accessed in WordPress? Specifically, I'm curious about: comment_karma comment_type comment_approved I have one meta value I want to set, which I'm hoping to use <code> comment_type </code> for. I also want to set a flag on each request to show whether or not it has been confirmed and responded to. It seems like <code> comment_karma </code> would work well for this, as it is completely unsused, although I'm not sure if it can be set directly with wp_insert_comment . Are there any consequences I should be aware of when doing this? Would I be better off just adding additional columns to the table, or does this approach sound like it would work?
comment_karma This field is used by a few plug-ins to help you manage your comments. There are a few good articles explaining its exact use floating around on the Internet. But you should note that this field is actually just not used. As Mark Jaquith said once, it's a "there if you want to use it this." There was a short movement to remove it for version 3.1 ... but since some systems still hook onto it, it's staying there for now. comment_type Is this a comment, a trackback, or a pingback? This helps theme devs separate out the different types of "comments" in the front-end display. comment_approved Is the comment pending moderation, spam, or approved by the author? Just helps you manage what is and isn't OK for display on the site.
What are the additional fields in wp_comments used for?
wordpress
I'm checking out how a particular plugin works and noticed that it stores its data for option_value in wp_options in this array format... a:2:{i:20;a:2:{s:8:"original";s:15:"20.original.jpg";s:9:"thumbnail";s:12:"20.thumb.jpg";}i:8;a:2:{s:8:"original";s:14:"8.original.png";s:9:"thumbnail";s:11:"8.thumb.png";}} I like this method, since it only uses a single row to hold my custom data, uninstall cleanup is easy. Is there a standard way to do a get/set operation on a custom field that results in this syntax? Update: Thanks to Denis and the others who've added responses. Here's an excellent tutorial on this method in case anyone else has this question > http://striderweb.com/nerdaphernalia/2008/07/consolidate-options-with-arrays/
Just pass an array when updating your option. It'll then get serialized automatically.
How do you store options with a:n:{{}} syntax in wp_options?
wordpress
i have my website with permalink, till now everything was fine, but few days before i changed my permalink, now everything is going wrong, now each and every page i am getting 404, even my about-us and contact us pages, they are giving me 404 page if i come to my site from google or any search engines, then also it gives me 404 i have 1000+ posts on my website, for each post &amp; page from google i get 404 page, but within the website except pages i get no 404 page my previous permalink: <code> %postname%/%category%/ </code> now i added custom taxonomy to my permalink, so now it is: <code> %location%/%courses%/%postname% </code> I asked this question first also, but it was into wrong section i guess, thats why asking again and in detail. Related Question: stackexchange-url ("custom taxonomies on permalink")
http://wordpress.org/extend/plugins/custom-post-permalinks/ check this plugin, I've used it on a couple of sites and it works great.
permalink changed, now getting 404 for every pages
wordpress
I'm on <code> Wordpress 3.0.4 </code> and I'm having a hard time deciding which way to go. The following is my problem: I have a <code> mysql </code> database table <code> widgets </code> , with about 10 <code> properties </code> like id, size, color etc. Now I'd like to integrate this table into <code> Wordpress </code> , preferably in such a way that I can get paginated lists of the <code> widgets </code> , show information on a single widget and have a flexible layout. Preferably, I would like the ability to change a custom template in such a way that I can change the position of each property on the page (So maybe I'd like to put e.g. the size-property on top of the page on the left, later I might want to put it on the right bottom). What would be the best way to store the <code> widgets </code> , retrieve them by using as much <code> Wordpress </code> build-in functions and how can I get this flexible layout as well? I've written my own plugins before, so I have more than basic knowlegde on <code> Wordpress/PHP/MySQL </code> .
This is precisely what custom post types are for. If it were my project, I'd scrap the custom table you have, set up a custom post type for your "widgets", add all your existing widgets as regular WP content, and use standard WordPress functions and templates to query and display them. It's a bit of investment in the short term (if you have a lot of existing data you need to migrate), but in the long run it's best to have all your content in standard WordPress tables and display it using standard WordPress functions and templates--unless there's a really compelling reason not to.
How to integrate custom database table in Wordpress and using Wordpress functions
wordpress
0 down vote favorite Hi, I am working with wordpress where i have a event listing system. There is a custom field in my post called starting_time which is unix timestamp. Now i want to short all posts by starting_time by this query_post command: <code> query_posts(array( 'post_type' =&gt; 'event', 'meta_key' =&gt; 'end_time', 'meta_compare' =&gt;'&gt;=', 'meta_value'=&gt;time(), 'order_by' =&gt; 'start_date', 'order' =&gt; 'ASC' )); </code> But it not working. Here is the site http://citystir.com/events/ . I am echoing the start_time in unix before the time remaining so you can see the value. And also my pagination is not working. May be i did something wrong in the query_post command. Please someone response. --------------------- Update ----------------- i have found a wonderful post here kovshenin.com/archives/customize-posts-order-in-wordpress-via-custom-fields but i didn't get it worked. May be for lack of my knowledge. Please take a look at it and let me know if you have any suggestions. I will continue working on that. -------------------- Resolved ----------------- Changed order_by to orderby. And also i came to know that we can use meta key multiple times if we want it will not conflict. Here is the final code: <code> $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts(array( 'post_type' =&gt; 'event', 'meta_key' =&gt; 'end_time', 'meta_compare' =&gt;'&gt;=', 'meta_value'=&gt;time(), 'meta_key' =&gt; 'start_time', 'orderby' =&gt; 'meta_value_num', 'post_per_page' =&gt; '-1', 'order' =&gt; 'ASC', 'paged' =&gt; $paged )); </code> Thanks for all your hard work!
<code> order_by </code> doesn't take a name of the field, it takes type of order. Which for custom numeric field will be <code> orderby=meta_value_num </code> . But actual field used is taken from <code> meta_key </code> and you are already using it for filtering. See Orderby Parameters . So you can't pull this of this easily at moment, not without filtering and modifying resulting SQL query. Upcoming WP 3.1 will have much more improved and flexible querying support for custom fields and it will likely be easier than.
Sorting problem with 'query_posts' funcion in wordpress. Sort by custom field not working
wordpress
After I updated my site, I'm not able to get the RSS working. I used to get this RSS icon in the address bar in my web browser (opera), but now it's not there any more. I try accessing the following URL: http://www.norwegianfashion.no/feed/ But I only get this error message: <code> XML parsing failed XML parsing failed: syntax error (Line: 3, Character: 0) 1: 2: 3: &lt;?xml version="1.0" encoding="UTF-8"?&gt; 4: &lt;rss version="2.0" 5: xmlns:content="http://purl.org/rss/1.0/modules/content/" 6: xmlns:wfw="http://wellformedweb.org/CommentAPI/" </code> Testing it in a feed validator , is says I have a blank line at the start of the file. Clicling he help link , says that Wordpress has a tendency to create empty spaces :( Does this mean I have to go through each template file, include file and plugins and remove the <code> ?&gt; </code> at the end? Anything else that could cause my problems?
You have two separate issues here. Feeds are not detected by browser, because information for that is not being output in page body. I believe the current way of adding those links is declaring it in theme with <code> add_theme_support('automatic-feed-links'); </code> in <code> functions.php </code> , see Feed Links in Codex. Other issue is that something spits out unwanted new lines at the very start of output, both for your feeds and regular pages as well. Usually this is caused by such whitespace outside of <code> &lt;?php ?&gt; </code> tags somewhere in theme or plugin file, it can be rather hard to track down. <code> functions.php </code> of theme is always good place to check for this first.
I'm not able to get RSS feed working. I get 'XML parsing failed'
wordpress
The code below writes out a list of the most recent posts. However, it does not appear to be skipping over sticky posts although I'm using 'post_not_in' => get_option('sticky_posts'). What am I missing? <code> &lt;?php $cat=get_cat_ID('top-menu'); $catHidden=get_cat_ID('hidden'); $myquery = new WP_Query(); $myquery-&gt;query(array( 'cat' =&gt; "-$cat,-$catHidden", 'post_not_in' =&gt; get_option('sticky_posts') )); $myrecentpostscount = $myquery-&gt;found_posts; if ($myrecentpostscount &gt; 0) { ?&gt; &lt;div&gt;&lt;h4&gt;Recent Posts&lt;/h4&gt; &lt;ul&gt; &lt;?php global $post; $current_page_recent = get_post( $current_page ); $myrecentposts = get_posts(array('post_not_in' =&gt; get_option('sticky_posts'), 'cat' =&gt; "-$cat,-$catHidden",'numberposts' =&gt; $cb2_recent_count)); foreach($myrecentposts as $idxrecent=&gt;$post) { ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php } ?&gt;&lt;/ul&gt;&lt;/div&gt; </code>
You are lacking a one underscore in parameter, it should be <code> post__not_in </code> . Also the better way is to use <code> caller_get_posts </code> parameter (it will be deprecated and replaced with more aptly named <code> ignore_sticky_posts </code> in 3.1 that will do same thing) that will keep sticky posts in results if they fit, but will prevent them from jumping to the top. See Sticky Post Parameters in Codex.
Why do sticky posts show in this menu?
wordpress
There are ways to convert color image to <code> black and white </code> on the client side with javascript. However, it won't work in all browsers and it's slow. Is there a way to convert Wordpress post-thumbnails to <code> black and white </code> on the <code> server side </code> automatically? This is what I would like to achieve: Upload a color image Have it displayed in black and white On hover change to its original color
You can use the php GD library which you most likely already have on your server since wordpresses uses it. You can filter the image using imagefilter specifically IMG_FILTER_GRAYSCALE and/or IMG_FILTER_CONTRAST. For example <code> imagefilter($im, IMG_FILTER_GRAYSCALE); imagefilter($im, IMG_FILTER_CONTRAST, -100); </code> The hover would have to been done in javascript. A much simpler solution would be to use the html5 canvas tag or a javascript image library like pixastic and wrestle with making it browser friendly ( not that hard using one of the html5 js kits)
Black and White thumbnails
wordpress
I have installed the Custom Post Type UI plugin. After activation of this plugin I have created a custom post type called <code> portfolio </code> . Now I want to use this on the portfolio page in the front-end. How do I fetch all post that are of custom post type <code> portfolio </code> ?
<code> query_posts( array( 'post_type' =&gt; array('post', 'portfolio') ) ); </code> witch shows both normal posts and posts inside 'portfolio' or <code> query_posts('post_type=portfolio'); </code> For only portfolio. Use as normal WP Query - read the Codex: http://codex.wordpress.org/Function_Reference/query_posts#Usage and http://codex.wordpress.org/Function_Reference/query_posts#Post_.26_Page_Parameters <code> &lt;?php query_posts(array( 'post_type' =&gt; 'portfolio', 'showposts' =&gt; 10 ) ); ?&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;h2&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;&lt;?php echo get_the_excerpt(); ?&gt;&lt;/p&gt; &lt;?php endwhile;?&gt; </code>
Query for custom post type?
wordpress
I've long wished Wordpress would support SQL Server, but it would also really amazing if it supported MongoDB (for example.) My question is are there any plans to do so, at all? Is the core Wordpress team so commited to MySQL that there are no plans to offer any sort of support for other DBs (at least anytime soon?) This post leads me to believe any such thing won't happen: http://codex.wordpress.org/Using_Alternative_Databases However, as an example (while I much prefer Wordpress to it) Drupal 7 now features a ... Database abstraction layer, enabling the use of many databases, such as Maria DB, Microsoft SQL Server, MongoDB, Oracle, MySQL, PostgreSQL, or SQLite http://drupal.org/node/1015646
Hi @Justin Jenkins: It's very hard for use to say if WordPress will or will not support it since they can make those decisions and we cannot. However we can look at some evidence. SQL Server? For SQL Server on one hand a trac ticket was debated and stalled a year ago; since then more recently it appears that Automattic and Microsoft are exploring business relationships: WordPress Trac - Ticket Resting Microsoft SQL Server Support Microsoft brings WordPress onto its cloud: Automattic blogs will go Azure Microsoft's Blogging Platform Deal with WordPress Looks Like a Win-Win Mongo DB? For Mongo DB there was a support question proposing it but no official acknowledgement and no real traction: WordPress Support - Suggestion: support MongoDB, HyperTable or other noSQL storage Forecast? So, SQL Server looks more likely than MongoDB, at least from Automattic in the near term but that's only a guess and not one I'd actually bet on. What about Plugins? More importantly one would need to consider that a major benefit of WordPress is the huge repository of free plugins and many of those encode MySQL directly and thus would cease to work and blunt much of the benefit of WordPress. Drupal Modules and their Support of Other Databases Besides MySQL What's more in the Drupal world you do have multiple database support but the reality is that vast majority of Drupal modules that interact with the database only support MySQL. Supporting multiple databases requires many times more effort and most Drupal module developer simply don't have the resources or even the inclination to create free plugins with those levels of support and I would expect the same would be true with WordPress. Real-world Use-Cases? Which bring me to an honest question: What's the real-world use-cases for this? As a technologist myself I always look at these types of these as really cool, but as an entrepreneur I also look at them pragmatically and ask for use-cases. Are there situations where MySQL is really not an option but SQL Server is? Are the installations where benefits of Mongo DB would exceed the downsides? (And just as importantly, are there companies who really need this who are willing to spend money to support the development and maintenance? More specifically I'd be curious to know your motivations? Again, that's an honest question; market research really, and not to challenge you in any way for asking.) Next Steps? If you want to hear it more from the horse's mouth I'd suggest but asking on the wp-hackers mailing list and posting a proposal ticket for MongoDB on trac . UPDATE I just came across this page on Microsoft.com that claims they have a patch for using SQL Server with WordPress. I didn't try it so I can't vouch for it, though here's Microsoft's WordPress page: http://www.microsoft.com/web/wordpress
Are There Any Plans for Wordpress to Support Databases Other Than MySQL?
wordpress
For some reason the excerpt box on the new posts page (post-new.php) is always closed. I can alter that with firebug, but it should be open anyway. There is a "closed" class being added by someone somewhere, but it is unwanted. Is there any fix?
By default, Wordpress saves the open/close state of these metaboxes each time you toggle it. This is done via javascript, requesting an ajax endpoint on the server. You need to find out if that request is still send or not. If it's not send (e.g. javascript error, blocked by some plugin), then you found the cause. If it is send, you need to find out if the new state is successfully stackexchange-url ("stored inside the database"). If it is not stored inside the database, you found the cause. If it is stored into the database, you need to find out if it is read out of the database. If it is not read out of the database, then you found the cause. If it is read out of the database you need to find out if it get's correctly applied as the metabox class either via the pages response or via some additional javascript / ajax hook. I don't remember from mind if there is something like the latter as well. If not, you found the cause. If it does, well then I have no additional idea what the cause of the error might be right away, but I'm pretty sure if you debug it that far, you found the cause ;) More information is available here: stackexchange-url ("Make Custom Metaboxes Collapse by Default")
how to reset metabox excerpt to open
wordpress
I've got a custom query on my homepage showing all posts in a certain category. I need this query to respect sticky posts, but it seems from my research that category queries ignore stickyness. My question is two (and a half) fold: Can anyone tell me where/how in the database stickyness is applied to a post? I don't see it in <code> wp_postmeta </code> or <code> wp_posts </code> . This one is most important and will probably be enough to get you the win accepted answer. Is there any simple elegant way to grab sticky posts only from a certain category? If not, then how about an ugly way to do it? Just for the heck of it, here's my query, though I think it won't make a difference to the answer. <code> $getHighlights = array( 'posts_per_page' =&gt; 7, 'post_type' =&gt; array('post','Event'), 'category_name' =&gt; 'Highlights', ); </code> Sorry for the long title, but I wanted to be clear what I was asking for.
Just add <code> 'post__in' =&gt; get_option('sticky_posts') </code> to your query, to confine your query to only sticky posts. So, <code> $getHighlights = array( 'numberposts' =&gt; 7, 'post_type' =&gt; array('post','Event'), 'post__in' =&gt; get_option('sticky_posts'), 'category_name' =&gt; 'Highlights' ); </code> should work for you. Edit: This is how you can merge two arrays to get the sticky posts at the top of your query: <code> $getHighlights_sticky = get_posts( array( 'numberposts' =&gt; 7, 'post_type' =&gt; array('post','Event'), 'post__in' =&gt; get_option('sticky_posts'),//it should be post__in but not posts__in 'category_name' =&gt; 'Highlights' )); $getHighlights_other = get_posts( array( 'numberposts' =&gt; 7 - count( $getHighlights_sticky ), 'post_type' =&gt; array('post','Event'), 'post__not_in' =&gt; get_option('sticky_posts'),//it should be post__not_in but not posts__not_in 'category_name' =&gt; 'Highlights' )); foreach ( array_merge( $getHighlights_sticky, $getHighlights_other ) as $post ) { setup_postdata( $post ); // your display loop } </code> This will show 7 posts, with the stickies at the top (of course, this is assuming you don't have more than 7 stickies, otherwise it'll be all messed up...) (edited to use <code> numberposts </code> as per OP's comment below...)
Using categories & "stickyness" together
wordpress
I have a few custom post types set up. However, a couple of them have the title field removed from the edit screen because a title does not make sense in some aspects. However, I now find that all posts are being saved improperly with the text "Autosaved Post" or whatever. Is it possible to set the post title upon saving the post to be the assigned category name? The reason I want this is because I am building a record label website with the following custom post types: Artists Homepage Carousel Videos Tours The homepage carousel does not need a title and I would like it to perhaps be the following format: "Bandname Carousel" bandname being the category name of which would only be band names. Should I add the title field back in and use jQuery to perhaps set the title instead of writing a custom Wordpress plugin and set the field to read only so the user can't make changes to it? The reason I want to set the title is to stop the annoying "Autosaved Post" value being added to the title hence preventing the user from being able to sort through and differentiate between posts that have been added.
Q: Is it possible to set the post title upon saving the post to be the assigned category name? A: Yes it is. Each time a post is saved or created, a filter is called. You can hook into that filter and set the title of the post to the value you want. This will, in contrast to a solution with jQuery, ensure that your data is correct regardless how the editor configured his browser or if something is broken on his system. If you want to find out more about the hooks I'm talking about, these two functions are a good place to start: <code> wp_update_post() </code> and <code> wp_insert_post() </code> . The related source-code is available in <code> /wp-includes/post.php </code> . You can find all associated hooks inside the functions code. There are multiple available, so I can only suggest one at best guess. That would be <code> wp_insert_post_data </code> in line 2 531 , you can change/set the title by hooking into that filter: <code> add_filter('wp_insert_post_data', function($data, $postarr) { /* your job */ $data['post_title'] = $defaultTitle; $return $data; }, 10, 2); </code> Or it's possible even better to hook into <code> save_post </code> action in line 2 620 as it's already saved within the database and might work for both functions. The principle is the same: You modify the data on your own.
Dynamically Set Wordpress Post Title To The Category Name
wordpress
The short installation instruction for WordPress ("5 Minutes") state that: Create a database for WordPress on your web server, as well as a MySQL user who has all privileges for accessing and modifying it. While setting up a new blog professionally I was wondering how that maps to what the MySQL database user privileges/permissions configuration offers me: Data: <code> SELECT </code> , <code> INSERT </code> , <code> UPDATE </code> , <code> DELETE </code> Definition: <code> CREATE </code> , <code> ALTER </code> , <code> DROP </code> Extra: <code> INDEX </code> More: <code> LOCK TABLES </code> <code> REFERENCES </code> <code> CREATE TEMPORARY TABLES </code> <code> CREATE VIEW </code> <code> SHOW VIEW </code> <code> CREATE ROUTINE </code> <code> EXECUTE </code> <code> ALTER ROUTINE </code> I'm pretty sure for the first three groups, I named them Data, Definition and Extra here. But what about the others below the More entry? Normally I would say, those are not needed, but I would like to get a second opinion.
The others are not needed as you point out. Btw, what you could do is, conditionally set the user/pass based on the requested page. As in unprivileged with select/insert/update/delete for normal usage, and privileged with definition/index related stuff in addition when visiting the upgrade page.
MySQL Database User: Which Privileges are needed?
wordpress
I have a plugin that I only want to execute when the home page is being viewed. How would I stub out my plugin in order to make this happen? This is does not work... <code> &lt;?php /* Plugin Name: My Test Plugin */ if ( is_home() OR is_sticky() ) { add_filter( 'the_content', 'my_function' ); } function my_function( $content ) { echo "hello world".$content; } ?&gt; </code> This is my original code, but it executes the filter on every page. Which seems overkill to me, since I only want the plugin to run on the home page anyway. <code> add_filter( 'the_content', 'wpse6034_the_content' ); function wpse6034_the_content( $content ) { if ( is_home() ) { $content .= '&lt;p&gt;Hello World!&lt;/p&gt;'; } return $content; } </code>
You need to add the filter later: <code> function _add_my_filter() { if ( is_home() OR is_sticky() ) { add_filter( 'the_content', 'my_function' ); } } add_action('template_redirect', '_add_my_filter'); </code>
How to create a plugin that only operates on the home page?
wordpress
I've been trying to write a post about a simple Windows Powershell script for the last few hours, but when I try to preview the post with the script included, it takes down my server. Unfortunately the server isn't mine to control (it's hosted by 34sp.com) so I'm limited in what I can do to diagnose the issue - I'm not sure where I'd start anyway. The problem seems to stem from including the following lines in the post : &lt;pre&gt; $camera_getid.Parameters.Add("@CameraGUID", [System.Data.SqlDbType]"NVarChar").Value = $guid; &lt;/pre&gt; I'm having trouble narrowing down the problem precisely, since every time it happens, my server is down for about 5-10 minutes. Has anyone seen anything similar?
Wordpress, by default, has no problem with such a content. It won't crash your server. And I think in fact this does not crash your server as well. I think your server has some webapplication firewall configured. Such a firewall checks each request for malicious data that are assumed to be triggering exploits or introducing payloads to the server or installed applications. Those firewalls are often configured with a blacklist that is "best guessed". This means, they do block requests that are valid as well, because such a firewall can not differ between a valid or invalid request. Some of those webapplication-firewalls are also interfaced into IP based firewalls. So on seeing a malicious request they block your computer accessing the server for a certain period of time, e.g. 5 to 10 minutes. Please contact your server administration and ask them if such a firewall exists because you have got problem to post (as in HTTP POST METHOD) the content you named to your host. They should be able to reconfigure the firewall and tweak the rule that is the cause of the false positive.
How can a single line in a blog post take down my server?
wordpress
WP Robot looks like a very powerful plugin, but one which could be used for all sorts of spammy websites. Just wondering what the general community opinion is of these plugins? Are they useful or damaging to a website?
I am not sure what answer you are looking for. Plugins are not something that you directly see when you look at site. Not something site's reputation is based on. I hadn't looked into this specific plugin, but as any of this kind it likely can be used both for perfectly legit and absolutely spammy purposes.
Are plugins like WP Robot considered as spammy by the community?
wordpress
I'm aware it's not a feature of Wordpress, but I was wondering if there was a way or a plug-in (haven't found one from searching) that allows me to force a user to change their password after a defined number of days.
I was busy writing up a plugin for this without even checking of one already existed. So I did a little research and found out that it does indeed already exist and that the path I was going down was the right one. Well, there's no need to reinvent the wheel here, so here's the link to the existing plugin. http://wordpress.org/extend/plugins/expire-password/ Does what you need - I tested it myself.
Setting WP Admin passwords to expire
wordpress
I am new to theming with wordpress. I have a theme layout with one sidebar at the right side of the website. Now on my homepage and one other page i dont want to have the sidebar. On all other pages it needs to stay. How can i do this. Any help would be appreciated. Thanks.
... on my homepage and one other page i dont want to have the sidebar. You can tell WordPress to do not generate sidebar on specific page(s) with simple condition in your page.php file (or other relevant template file ). For example the following piece of code will disable sidebar on 'About Me' page. <code> &lt;?php if (!is_page('about-me')) get_sidebar(); ?&gt; </code> *Note: you can use numeric ID or slug of your page inside the is_page() function.*
How to change sidebar per page?
wordpress
give it an tipp or solution for deactivate the method request() in class WP_Http_Streams? I use WordPress also on offline-servers and have wp_debug true for development and tests. But i have many warnings from functions to use the http-class; as example the functions to read the feeds in dashboard. Current i have deactivate all hooks for update themes, plugins, core and the crons; see my small plugin for this: https://github.com/bueltge/WP-Offline Thanks for a reply
Try this in <code> wp-config.php </code> : <code> define( 'WP_HTTP_BLOCK_EXTERNAL', true ); </code>
How deactivate the http-api
wordpress
I've got some pages with a custom taxonomy for each page and i'm trying to retrieve this taxonomy on the page. I'd basically need something like <code> the_current_taxonomy() </code> like <code> the_title() </code> . This has to run outside the loop cos i'll use it in a custom <code> WP_Query </code> right after. Edit: Found a solution using a different way to retrieve the information i needed. Thanks for your help guys.
So, i needed to extract the term of a know taxonomy given to a page (like this: <code> function register_prod_categoria() { </code> register_taxonomy( 'prod-categoria', array( 'produtos', 'page' ), ( produtos being a custom post type, just for info.)). I tried various things, among them, this: <code> get_terms('prod-categoria',''); </code> This, works, but gives me everything about my taxonomy prod-categoria , which isn't what i needed. Then as explained in the codex , two (interesting for me) parameters are available for <code> get_terms() </code> : child_of and parent . This sounded perfect, so i went: <code> get_terms('prod-categoria','child_of=marca'); </code> and also <code> get_terms('prod-categoria','parent=marca'); </code> , marca being a term parent (from the custom taxonomy prod-categoria ) from which i wanted to extract the child terms. Both gave me no results. I also tried with the name Marca and the slug marca , nothing. The solution i ended up with is this: <code> $tt = the_title('','',false); </code> . I'm getting the page title to use it as a parameter after: <code> $posts = posts_search ('produtos',array('prod-categoria'=&gt;$tt,'prod-cols'=&gt;'5-C-P-F-NF-P')); if($posts) { echo "&lt;table class=\"table-marca\"&gt;"; foreach($posts as $post) { ... } </code> Btw, the function posts_search() (found it on stackexchange-url ("stackexchange-url or stackexchange-url ("stackexchange-url if i'm right, dont remember for sure) allows to do queries on multiple taxonomies. I agree very much that it's far away from being perfect, the title of the page having to be equal to the taxonomy name, but in my case it works. Thanks a lot to Rarst and Piet for trying to help.
Get current page's taxonomy
wordpress
I'm trying to integrate Invision Power Board into our website, Wordpress by using IPB Website Integration (IPBWI). I have used the script sometime before on a static website, but I'm having trouble with the integration in Wordpress. The script is actually working as intended in Wordpress, but I am getting a lot of warning-messages throughout the site, like this: <code> Strict Standards: call_user_func_array() expects parameter 1 to be a valid callback, non-static method RCCWP_Query::FilterCustomPostsFields() should not be called statically in [path]\wp-includes\plugin.php on line 220 Strict Standards: call_user_func_array() expects parameter 1 to be a valid callback, non-static method RCCWP_Query::FilterCustomPostsJoin() should not be called statically in [path]\wp-includes\plugin.php on line 220 Strict Standards: call_user_func_array() expects parameter 1 to be a valid callback, non-static method RCCWP_Query::FilterCustomPostsOrderby() should not be called statically in [path]\wp-includes\plugin.php on line 220 Strict Standards: call_user_func_array() expects parameter 1 to be a valid callback, non-static method RCCWP_Query::FilterCustomPostsFields() should not be called statically in [path]\wp-includes\plugin.php on line 220 </code> It is mainly where I have custom queries I get these warnings This might be beyond the scope of support witch this board gives, but hopefulle someone might know some solutions.
the error you see is given by PHP and is giving you a hint that the code you use has not been programmed carefully. It is violating strict standards, in you case, a function is called in a way it should not. That's basically all. I assume on the server you just have installed the integration, there is some other PHP configuration. So previously on some other configuration there was not such error reporting given. Please contact the author(s) of the wordpress IPB integration and report the error you are getting back to them. If they have questions back, please try the best you can to answer their questions. This will help them to improve the software. If you are a coder your own, you can as well fix the problem on your end and report the problem with the solution back to project.
Invision + Wordpress integration
wordpress
I was wondering how does external app works for <code> wordpress.com </code> or <code> wordpress.org </code> . Directly connecting to the wordpress database seems a bad idea to me. Questions How can I create an app or get / post data from the wordpress database? Is there a JSON API or XML API format so that I can easily exchange data between the two?
WordPress features a very rich XML-RPC interface that you can work with from external applications. It provides you access to most of the functionality you'd have directly in the admin - write posts, edit posts, edit comments, create/edit categories, manage site options, upload files, etc. As a matter of fact, certain third-party applications are already using this functionality to allow you to manage WordPress remotely - a good example is Windows Live Writer. It works for both self-hosted (.org) sites and sites hosted on WordPress.com. So if you need to get posts from WordPress, I'd recommend following API calls: metaWeblog.getPost - for retrieving a single post based on its ID. metaWeblog.getRecentPosts - for retrieving a list of recently published posts You can also create/edit posts with these API calls: metaWeblog.newPost - create a new post metaWeblog.editPost - edit an existing post There's more information about creating your own application (and an explanation as to why WordPress supports third-party APIs like metaWeblog) in the Codex. I've also written tutorials on how to use the API and documentation specific to making/parsing metaWeblog API requests.
Creating external apps Wordpress / How they work
wordpress
Curious to know if there is a handy solution for showing cool email stats like Ma.tt's contact page http://ma.tt/contact/ Inbox: 157. Low priority: 1,461. Unknown: 155. I’ve sent out 920 emails to 357 people in the past month.
This is actually not all that hard to do using the imap functions in PHP: http://php.net/manual/en/book.imap.php Basically, he has some script somewhere which runs every hour or so. I have not seen this script, but I can venture a good guess about how it works. First, it connects to his email system, probably using imap. Second, it performs some set of custom rules to divide new emails into high and low priorities in some manner. This much is obvious from the contact page. Third, it gets the counts and stores them in a database table custom made for storing this count. To display the graphs, I wrote some queries in a Page Template that connects to that custom table, gets the counts for the last month, does a bunch of math and reformatting of the numbers, and finally produces a URL to the Google Chart API with the numbers to display the graph. A very minimal knowledge of PHP and a server with the php_imap extension is all that's really required to script your own email. This is a highly instructive read if you've never taken a look at it before: http://php.net/manual/en/book.imap.php
Email stats at Ma.tt contact form
wordpress
I have searched all over the web to find some solution, but none of them are working for me, can someone help me with this and explain what is wrong? I've spent 3 hours debugging and didn't find the issue. Here is my code: <code> global $paged; global $wp_query; wp_reset_query(); $per_page = get_option('posts_per_page'); $cat_cars = get_term_by('slug', 'cars', 'category'); $page_links_total = ceil($cat_cars-&gt;count / $per_page); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' =&gt; 'cars', 'post_status' =&gt; 'publish', 'cat' =&gt; $cat_cars-&gt;term_id, 'orderby' =&gt; 'date', 'order' =&gt; 'DESC', 'posts_per_page' =&gt; $per_page, 'paged' =&gt; $paged ); $page_links = paginate_links(array( 'base' =&gt; add_query_arg('paged', '%#%'), 'format' =&gt; '', 'prev_text' =&gt; __('«'), 'next_text' =&gt; __('»'), 'end_size' =&gt; 2, 'mid_size' =&gt; 1, 'type' =&gt; 'plain', 'total' =&gt; $page_links_total, 'current' =&gt; $paged )); $car_query = new WP_Query($args); </code> And later i call <code> have_posts </code> , <code> the_post </code> , etc.. This part works, until I go to the second page of my pagination and get nothing found.
I had a similar problem recently and determined the cause to be that when WordPress queries for posts in a category, it looks for posts with post_type equal to 'post' before it reaches the point where you query for post_type 'any' or some custom post type. This doesn't cause a problem on page 1 because even if there are no posts it calls your template. However on page 2 and so forth, it doesn't find any posts of post_type 'post' so it loads the 404 template before your template even gets a chance to modify the post_type parameter. Is this a bug? That's a good question. I would say so because you should expect that if you register the 'category' taxonomy on other post_types, all post_types would show up in that archive, not just strictly posts. Hopefully that helps.
WordPress pagination with custom post type?
wordpress
I am using custom taxonomies with WordPress 3.0.4 I am wondering if anyone knows how to remove the taxonomy base from the URL? I have seen plugins that do it for categories and tags, but not for custom taxonomies. For example, I have a custom taxonomy called 'cities'. I would like my URL structure to be mydomain.com/newyork instead of mydomain.com/cities/newyork Is there a function or something I can use?
I think this is possible, but you will need to keep an eye on the order of the rewrite rules. To help you with this I recommend stackexchange-url ("a plugin I wrote to analyze the rewrite rules") (soon available in the repository, but you can download a pre-release ). First of all, these rules are quite generic, and should thus come at the end of the rules list. The default action is to put them at the top, so we prevent the default and add them ourselves. We already have the generic page rules at the bottom, so we should make them explicit and move them to the top by enabling verbose page rules . This is not efficient when you have lots of pages, but I don't think there is another way to do it now. <code> add_action( 'init', 'wpse6342_init' ); function wpse6342_init() { // Register your taxonomy. `'rewrite' =&gt; false` is important here register_taxonomy( 'wpse6342', 'post', array( 'rewrite' =&gt; false, 'label' =&gt; 'WPSE 6342', ) ); // Enable verbose page rules, so all pages get explicit and not generic rules $GLOBALS['wp_rewrite']-&gt;use_verbose_page_rules = true; } add_action( 'generate_rewrite_rules', 'wpse6342_generate_rewrite_rules' ); function wpse6342_generate_rewrite_rules( &amp;$wp_rewrite ) { // This code is based on the rewrite code in `register_taxonomy()` // This rewrite tag (%wpse6342%) is just a placeholder to use in the next line // 'wpse6342=` should be the same as the `query_var` when registering the taxonomy // which is the name of the taxonomy by default // `(.+?)` works for a hierarchical taxonomy $wp_rewrite-&gt;add_rewrite_tag( '%wpse6342%', '(.+?)', 'wpse6342=' ); // This will generate the actual rewrite rules, and put the at the end of the list $wp_rewrite-&gt;rules += $wp_rewrite-&gt;generate_rewrite_rules( $wp_rewrite-&gt;front . '%wpse6342%', EP_NONE ); } </code>
Remove Custom Taxonomy Base
wordpress
I just tried the first time to extend a custom post type admin-UI-edit-page with some "meta" boxes (if this is the right word). <code> register_post_type( 'post_type', array( 'register_meta_box_cb' =&gt; 'additional_input_field' ) ); function additional_input_field() { global $post; $custom = get_post_custom( $post-&gt;ID ); $length = $custom["post_type-length"][0]; return print '&lt;label&gt;Length:&lt;/label&gt;&lt;input name="post_type-length" value="'.$length.'" /&gt;'; } </code> So far i haven't seen any documentation or example about how to use this. A look in the core showed me that it should be equal to: <code> add_action( 'add_meta_boxes'.$post_type, 'additional_input_field', 10, 1 ); </code> The appropriate hook can be found in (core) <code> ~/wp-admin/edit-form-advanced.php </code> line #163. The call for add_action in (core) <code> ~/wp-includes/post.php </code> line #877. The only problem is that it doesn't seem to work as expected. The field get's loaded in front (visually: on top) of everything else. If I try to hook it directly to <code> 'add_meta_boxes'.$post_type </code> , I get nothing. Simplified examples in this text to show what i mean. Typos may be there but doesn't matter. The callback fn is taken from some sample code over here .
I love answering my own questions: Wrap the function <code> add_additional_input_field() </code> in a new function that contains this and call it in the <code> register_meta_box_cb </code> argument. And yes: This is the solution.
register_post_type & 'register_meta_box_cb' argument
wordpress
<code> the image is worth a thousand words. take a look at it. </code> you know how craigslist has posts organized by date ..ex <code> Tue 3 </code> post links for tuesday <code> Wed 4 </code> post links for wed <code> Thurs 5 </code> post links for thur I know wordpress posts are organized by date by default. take a look at this any ideas? btw if this did not make sense let me know. tx
You may notice that I did more or less exactly this for Matt's site: http://ma.tt . Every set of posts is grouped by the day. The basic principle is to keep track of your day in the loop, then print the date and related stuff only when it changes. Take a basic Loop: <code> if ( have_posts() ) : while ( have_posts() ) : the_post(); the_title(); the_content(); endwhile; endif; </code> This just prints the title and content (without any formatting or anything) for everything in the current Loop. Now, you want it to pop out a new date every time the date changes. So you need to keep track of when it changes. Like so: <code> $loopday = ''; if ( have_posts() ) : while ( have_posts() ) : the_post(); if ($loopday !== get_the_time('D M j')) { $loopday = get_the_time('D M j'); echo $loopday; } the_title(); the_content(); endwhile; endif; </code> What this does is to store the date that you're wanting to output into a variable. Each pass through the loop, it gets it again and checks to see if it has changed. If it has not changed, then nothing happens. If it has changed, then it sets the variable with the new date string, outputs it, then moves on. Obviously this is just an example. The specific details depend on how your existing loop works and how you want to output the information. While it's true that the_date() does this by default, sometimes it's easier to do it yourself in this manner, for formatting reasons.
order posts by date like craigslist
wordpress
I am trying to <code> automate </code> editors work by automating <code> excerpts </code> . My solution works but there are few problems with it: If a post has images/broken html at the beginning it breaks the layout. Substring cuts words. Is there a better solution to automate excerpts or improve my existing code? <code> &lt;?php if(!empty($post-&gt;post_excerpt)) { the_excerpt(); } else { echo "&lt;p&gt;".substr(get_the_content(), 0, 160)."...&lt;/p&gt;"; } ?&gt; </code>
The excerpt filter by default cuts your post by a word count, which I think is probably preferable to a character-based substr function like you're doing, and it strings out tags and images as well while doing it. You can set the number of words to excerpt with the filter excerpt_length (it defaults to 55 words, this function from the codex shows how to change it to 20:) <code> function new_excerpt_length($length) { return 20; } add_filter('excerpt_length', 'new_excerpt_length', 999); </code> If you need to use a character-length based cutoff as in your example, you could fix broken tags and such just by applying an appropriate filter to your output, like this: <code> $content_to_excerpt = strip_tags( strip_shortcodes( get_the_content() ) ); echo "&lt;p&gt;". substr( apply_filters('the_excerpt', $content_to_excerpt), 0, 160)."...&lt;/p&gt;"; </code> Note that you're stripping tags and applying the filters before truncating the excerpt, so as not to leave an open tag in your excerpt that will screw up the rest of your layout. There are a number of great themes out there that deals with excerpts in creative ways, I advise you to take a look at how they do it. Here are a few good blog posts from people who have thought through the issue: More Tags or Excerpts (wptheming) Replacing WordPress content with an excerpt without editing theme files (justintadlock) Also, for a really random way of dealing with excerpts, look at the Kirby theme - it tries to implement something like Microsoft Word's autosummarize feature by using css to show only headers and lists (from what I remember).
Automating Excerpt
wordpress
I have a subdirectory within my WP installation called <code> labs </code> . I created a WP page called <code> labs </code> as well. When a user hits <code> mydomain.com/labs/ </code> I want them to load up the WP page. But instead it's loading up the <code> labs </code> directory listing. I've read a few ways to do this if I want my WP page to have a different name than my directory name, but I don't really want that. For example, I want to have: <code> mydomain.com/ &lt;-- WP Root mydomain.com/labs/ &lt;-- Pretty WP page listing all of my projects mydomain.com/labs/project1/ &lt;-- raw (i.e. no WP) web app mydomain.com/labs/project2/ &lt;-- raw (i.e. no WP) web app </code> Is this possible? I should also mention that WP is installed in the root of <code> mydomain.com </code> , so <code> /labs/ </code> is both a WP page and a subdirectory that I created manually. Solution : I renamed my <code> labs </code> folder to <code> projects </code> and used the following .htaccess. <code> RewriteEngine On RewriteCond %{REQUEST_URI} labs/(.+)$ RewriteCond %{REQUEST_URI} !labs/(.+)/$ RewriteRule ^labs/(.+)$ http://mydomain.com/labs/$1/ [L] RewriteRule ^labs/(.+)$ projects/$1 [L] </code> I'm a little unclear as to why I had to use <code> RewriteRule ^labs/(.+)$ http://mydomain.com/labs/$1/ [L] </code> instead of just <code> RewriteRule ^labs/(.+)$ labs/$1/ [L] </code> But when I used the latter it never appended the trailing slash.
You'll need to do some .htaccess-fu to get what you're proposing to work. <code> RewriteCond $1 ^/labs/(.+) RewriteRule ^/labs/(.*)$ /labs-folder/$1 [L] </code> This isn't tested yet but it if you put it before the wordpress rules in your htaccess file it will remap urls that begin with /labs/ to /labs-folder/ but not if the url is just "/labs/" on its own. Let me know if it doesn't work and I'll debug it with you. You can replace "labs-folder" with any folder name you choose but essentially a url like: <code> http://example.com/labs/project1/ </code> Will really be looking here: <code> http://example.com/labs-folder/project1/ </code>
WP Page and Subdirectory with same name
wordpress
I am working on a theme that shows 200/200px post thumbnail on the home page and 500/300px image on the category page. Here is what I have in fuctions.php but it doesn't seem to work (only the homepage thumbnail works) <code> add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size( 200, 200, true ); add_image_size( 'homepage', 200, 200, true ); add_image_size( 'category', 500, 300, true ); </code>
Simply naming the size in the functions file is not enough to get the sizes to work: To call a custom size that you added do this: <code> &lt;?php the_post_thumbnail('category'); ?&gt; </code> I see you <code> set_post_thumbnail_size(200, 200, true) </code> which you don't need to do if you're also naming a post thumnail size the same sizes for homepage. Perhaps this line is messing up your other sizes. Also, the_post_thumbnail doesn't usually work on images already uploaded. To test if the sizes truly aren't working upload a new file after adding the new thumbnail size/calling it in your theme file.
Post Thumbnails multiple sizes
wordpress
i have a custom post on my website, i just want that the all post from custom post types should be published on a separate page which will be "Blog", is this possible? the code worked, i edited the code this is my code: <code> &lt;?php /* Template Name: Blog template */ get_header(); $blog_query = new WP_Query; $blog_query-&gt;query( 'post_type=uni' ); // &lt;-- Your args on this line ?&gt; &lt;div id="content" class="col-full"&gt; &lt;div id="main" class="col-left"&gt; &lt;?php if( $blog_query-&gt;have_posts() ) : ?&gt; &lt;?php while( $blog_query-&gt;have_posts() ) : $blog_query-&gt;the_post(); ?&gt; &lt;div class="featured post"&gt; &lt;h2 class="title fl"&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="&lt;?php the_title(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/h2&gt; &lt;/br&gt; &lt;p class="fr"&gt; &lt;span class="small"&gt;&lt;span class="post-category"&gt;&lt;?php the_category(' ') ?&gt;&lt;/span&gt;&lt;/span&gt; &lt;/p&gt; &lt;p class="post-meta"&gt; &lt;span class="small"&gt;&lt;?php _e('Featured Venue &amp;#124;', 'woothemes'); ?&gt;&lt;/span&gt; &lt;span class="comments"&gt;&lt;?php comments_popup_link(__('0 Reviews', 'woothemes'), __('1 Review', 'woothemes'), __('% Reviews', 'woothemes')); ?&gt;&lt;/span&gt; &lt;/p&gt; &lt;div class="entry"&gt; &lt;?php the_excerpt(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php get_footer(); </code> but when i click on the title of the blog page, it takes me to a page where content of the posts come without div tag, and on the menu its on the home page check this image in this image everything looks fine, this is what i wanted in this when i click on the post i.e. title it comes this way check this image the menu is pointing on home and there is no <code> div </code> tag in the post
Create a page, call it blog. Create a page template and fetch posts from the custom type. Attach the template to the page. Save. Example Page Template You can use any parameters in the query line that you would with query posts . <code> &lt;?php /* Template Name: Blog template */ get_header(); $blog_query = new WP_Query; $blog_query-&gt;query( 'post_type=mycustomtype' ); // &lt;-- Your args on this line ?&gt; &lt;div id="content"&gt; &lt;?php if( $blog_query-&gt;have_posts() ) : ?&gt; &lt;?php while( $blog_query-&gt;have_posts() ) : $blog_query-&gt;the_post(); ?&gt; &lt;div class="post"&gt; &lt;h2 id="post-&lt;?php the_ID(); ?&gt;"&gt;&lt;?php the_title();?&gt;&lt;/h2&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/div&gt; &lt;?php get_footer(); </code>
custom posts on different page
wordpress
I have some texts that need to be replaced in every posts in my blog. Is it possible to do that? ps (I need to tag this question as <code> search-and-replace </code> but not enough reputation to do that. Please add the tag if you can. Thank you!)
You have at least three different ways: 1) Edit directly in the database. The content of the post is stored in post_content column of wp_posts table. Since you are running your own WordPress, you should have full access to that. Just use SQL to do search and replace . Remember, the table content is sort-of HTML, so may have tags and/or escaped characters 2) Export your blog into XML, do search/replace in any UNICODE ready editor and import it back in after deleting original content. I would practice this a couple of times first though, especially checking what happens with images, etc. 3) Use WordPress remote access API to iterate through posts and update them that way. Good for programmers and/or more flexible way of doing things, such as content-specific updates.
How to search and replace text in all posts of a wordpress.com blog (NOT wordpress.org one)?
wordpress
I'm creating a multi-author blog, and have recently added the "Dashboard Notepads" plugin. This allows me to add 1 to 3 dashboard widgets which I can write custom notes in, like news or notices. Is there a way I can set that widget to appear at the top by default? I had a look but could only find a plugin which works up to 2.8. Using version 3.0.4. I would much rather do this without the need to change code, although I would consider it as a last resort option. Thanks in advance.
Hi @Relequestual: I think what you want is here: Dashboard Widgets API / Advanced: Forcing your widget to the top It doesn't require you to change code per se, just to add the code like shown in the WordPress Codex to your theme's <code> functions.php </code> file which is a standard way to customize and/or extend WordPress: To find out the values you need use, just add a <code> print_r($wp_meta_boxes); </code> line then an <code> exit; </code> immediately below the <code> global $wp_meta_boxes; </code> line like this: <code> global $wp_meta_boxes; print_r($wp_meta_boxes); exit; // Stop execution here so you can see it. </code> You may need to actually view source to make sense of it all. -Mike
Can I set a default dashboard layout for all users?
wordpress
I got the following setup: Parent &amp; Child Theme (Parent contains basic stuff, but no loops, style, etc.) inside the functions.php of the Parent Theme i call my init.file, that cares about different stuff right at the begging of the parent functions.php file (before the init happens) i call my constants.php file that defines theme version, etc. When i now call <code> wp_enqueue_script($name, $path, $parent, VERSION_CONSTANT, $footer) </code> and set <code> $footer == true; </code> i would expect to get a) the script loaded in my footer and b) to get the *VERSION_CONSTANT* as my version number. But it doesn't work. Here is my workaround: Set <code> $footer == true; </code> pack it into a function add_action that function to a hook on top ...and stupid as it is: it works like a charm and the constant value get's inserted correct. Can anyone confirm this or has some explanation? I would expect to find the cause for this particular problem at where wp_enqueue_script get's loaded. This would explain why it works with the function (loaded later). Thanks!
Parent theme's <code> functions.php </code> is loaded after that of child theme. So your constants are not available at the moment of child theme loading. It is good practice to actually run any theme code at the hook after both themes are loaded. At the earliest at <code> after_setup_theme </code> hook. For enqueues is is explicitly documented that <code> init </code> hook should be used.
Use of CONSTANT in wp_enqueue_script not possible?
wordpress
I am using the following to help display a list of posts created in a custom post type. <code> &lt;?php $args = array( 'post_type'=&gt;'portfolio', 'title_li'=&gt; __('Portfolio') ); wp_list_pages( $args ); ?&gt; </code> However a class is not being added to the list item of the current page (current_page_item). Any ideas of how I could make this happen? Thanks!
Found this and it works perfectly! stackexchange-url ("Dynamic navigation for custom post type (pages)")
Adding class "current_page_item" for custom post type menu
wordpress
I've created my own admin page in wp-admin folder using add_theme_page() function. How to pass variables from there to my blog? I mean what's the easiest way without arrays etc. I've tried using "globals" but failed. Thanks a lot.
Read the codex page on creating options pages , and let us know if you run into any specific issues. It has a complete copy/paste example you can monkey with. If you're trying to avoid learning WordPress' options mechanisms in favor of a more generic custom php solution, I understand where you're coming from, but recommend learning to do it the right way. It'll be a couple hours investment, but it'll pay off over time. For reals.
Accessing variable from admin panel?
wordpress
I have a website in which I need to control the displayed excerpt length. Some of the posts might have manual excerpt so I can't use the <code> excerpt_length </code> filter. I can, of course, use some kind of <code> substr() </code> , but was looking for a more elegant solution (if such exists).
Take a look on my answer here: stackexchange-url ("Best Collection of Code for your functions.php file") If I understood your question correctly, it does what you are looking for. Place this in <code> functions.php </code> : <code> function excerpt($num) { $limit = $num+1; $excerpt = explode(' ', get_the_excerpt(), $limit); array_pop($excerpt); $excerpt = implode(" ",$excerpt)."... (&lt;a href='" .get_permalink($post-&gt;ID) ." '&gt;Read more&lt;/a&gt;)"; echo $excerpt; } </code> Then, in your theme, use the code <code> &lt;?php excerpt('22'); ?&gt; </code> to limit the excerpt to 22 characters. :)
How to control manual excerpt length?
wordpress
The title says it all. I'm using WP 3.0.4
Something like this should work. <code> $handle </code> should be the menu's slug; set <code> $sub </code> to true to search submenus (defaults to top level menus): <code> function find_my_menu_item( $handle, $sub = false; ){ if( !is_admin() || (defined('DOING_AJAX') &amp;&amp; DOING_AJAX) ) return false; global $menu, $submenu; $check_menu = $sub ? $submenu : $menu; if( empty( $check_menu ) ) return false; foreach( $check_menu as $k =&gt; $item ){ if( $sub ){ foreach( $item as $sm ){ if($handle == $sm[2]) return true; } } else { if( $handle == $item[2] ) return true; } } return false; } </code> One last quick note: this should not be used before the menu is set. <code> 'admin_init' </code> is a safe bet for the earliest time to use this. I also added some code to leave gracefully if the menus aren't set.
How to check if an admin (sub)menu already exists?
wordpress
I'm working on a plugin that constructs a top level menu and resides within its own directory in /wp-content/plugins. For example, the plugin looks like this: <code> function main_menu() { if(function_exists('add_menu_page')) { add_menu_page('Main Menu Title', 'Main Menu', 'administrator', 'main-menu-handle', 'menu-display'); } } add_action('admin_menu', 'main_menu'); </code> I would like to build out additional menu items as plugins in the future so that they may reside in their own directory within /wp-content/plugins but will add themselves to this particular custom menu. Ideally, these new plugins would register themselves like this: <code> function register_submenu() { if(function_exists('add_submenu_page')) { add_submenu_page('main-menu-handle', 'Widget Title', 'Widget', 'administrator', 'widget-handle', 'widget_display'); } } add_action('admin_menu', 'register_submenu'); </code> But I can't seem to make this work mainly because of the way WordPress uses the admin.php and the page query string parameter to navigate custom menus. Any insight?
If i'm following, you're having problems adding submenus from a plugin to a parent item registered in another plugin. Add priorities to your <code> admin_menu </code> actions to make sure the parent(top level) item exists at the point your additional plugins attempt to add items to that menu.. Add top level <code> add_action('admin_menu', 'main_menu', 100 ); </code> Add sub items <code> add_action('admin_menu', 'register_submenu', 105 ); </code> Default priority is 10, so your two callbacks were possibly executing in the wrong order. Let me know if that helps.
How do I add a custom sublevel menu specified in one directory to a custom top level menu specified in another directory?
wordpress
I have a .csv file with hundreds of rows and 2 columns. First column is the group name, and the second is the group description. I need forum to be active on all of the groups. I was told to use this code: <code> &lt;?php include "../../../wp-load.php"; $groups = array(); if (($handle = fopen("groupData.csv", "r")) !== FALSE) { while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) { $group = array('group_id' =&gt; 'SOME ID', 'name' =&gt; $data[0], 'description' =&gt; $data[1], 'slug' =&gt; groups_check_slug(sanitize_title(esc_attr($data[2]))), 'date_created' =&gt; gmdate( "Y-m-d H:i:s" ), 'status' =&gt; 'public' ); $groups[] = $group; } fclose($handle); } foreach ($groups as $group) { groups_create_group($group); } ?&gt; </code> So I created a php file with this code and opened the file in the browser, and I got a blank screen. And it didn't create the groups. I have no idea what to do from here. What should I do?
thanks for sharing your script with us. It's totally normal that this script results in a blank screen because it does not do any output. So once you have requested it, it should have created the groups. UPDATE: If it did not create the groups, then the script failed. It's highly likely you've made an error. Ensure that you can see all errors, so check the error log or enable error displaying and reporting for that file. This is some runtime configuration for a starter: <code> ini_set('display_errors', true); error_reporting(E_ALL); </code>
Displaying the errors from my BuddyPress script
wordpress
I'm developing a new custom theme - and noticed that if a post contains the shortcode [gallery] it gets ignored ( edit : I mean that the HTML delivered to the browser does not include [gallery], nor anything in its place... I think there's a blank line or two) My Theme is grabbing post contents via <code> the_content('&amp;rarr;') </code> ; also removing the standard <code> &lt;p&gt;&lt;/p&gt; </code> wrapper via <code> remove_filter('the_content', 'wpautop'); </code> The Codex does not list this as one of the features you explicitly have to add support for - but we know the codex can be outdated/incomplete at times. Anyways, what is it needed for a theme to recognize [gallery] (and/or other such standard shortcodes) ?
Have you added any images to the page in which you are using the gallery? The [gallery] shortcode won't work without there actually being attachments on said post.
How to provide support for [gallery] shortcode?
wordpress
I'm receiving many many spam comments using the same username and I guess it is a bot that keeps on submitting comments. In one week I get around 100 such comments (which is quite a lot for my small blog). I want to have a look at all comments that are marked as spam (just in case Akismet is too strict on a certain legit comment), but this is really annoying. Therefore I have two small questions: How can I tell WP to trash all comments that come from a certain username? What do you generally do in situations like this?
You actually want to keep these comments marked as spam--not trashed. Akismet checks against your spam list while deciding what to do with a new comment. So having a large database of spam comments actually helps Akismet work. I get what your issue is, but what you're essentially asking for is a spam filter for your spam filter. If you're having trouble with a particular user, you might consider disabling their account somehow. This is pretty easily done by changing their username and password in the DB to something unguessable. This ensures that they can't sign in, and can't create another account using the same email address.
A spam bot loves me, what can I do?
wordpress
Out of the box the P2 Theme does not have search. Is there a quick and easy way to add it?
Native search widget? Google Custom Search Element is also quite easy to implement, but won't fit private site.
Quick and Easy way to Add Search to the P2 Theme?
wordpress
I'm working an a Thematic child theme wherein I need to have a unique image decorating each of the site's main pages, from a pre-defined set of permanent images. It would also be ideal to have one of these same images randomly selected to appear on all other pages. Using a sidebar widget to load the images seems like a good option, but I don't know how to create my own widgets yet, and haven't had any luck finding a plugin which provides the simple functionality I'm looking for. I also don't want to clutter up the admin panel with plugins and options that the client shouldn't be fiddling with. I think it will probably be most ideal to put something into my <code> functions.php </code> which adds some generated markup to a Thematic hook based on the page ID, but I'm not quite sure what I'm doing, so I thought I should ask to see if someone already has a great solution.
Looking at their demo source, the easiest way to do this is by styling page classes like <code> pageid-69 </code> or <code> slug-example-page </code> : <code> body.slug-example-page{ background: url(...); } </code> If it has to be random image, add your styles in the header template so you can use PHP to generate dynamic css.
A good way to add a different background image for each page?
wordpress
I would like to write a function to email me the URL of the website when my theme is activated. What is the hook initiated when the theme is activated?
I have that code here just name the file theme_activation_hook.php like on the website and copy this. <code> &lt;?php /** * Provides activation/deactivation hook for wordpress theme. * * @author Krishna Kant Sharma (http://www.krishnakantsharma.com) * * Usage: * ---------------------------------------------- * Include this file in your theme code. * ---------------------------------------------- * function my_theme_activate() { * // code to execute on theme activation * } * wp_register_theme_activation_hook('mytheme', 'my_theme_activate'); * * function my_theme_deactivate() { * // code to execute on theme deactivation * } * wp_register_theme_deactivation_hook('mytheme', 'my_theme_deactivate'); * ---------------------------------------------- * * */ /** * * @desc registers a theme activation hook * @param string $code : Code of the theme. This can be the base folder of your theme. Eg if your theme is in folder 'mytheme' then code will be 'mytheme' * @param callback $function : Function to call when theme gets activated. */ function wp_register_theme_activation_hook($code, $function) { $optionKey="theme_is_activated_" . $code; if(!get_option($optionKey)) { call_user_func($function); update_option($optionKey , 1); } } /** * @desc registers deactivation hook * @param string $code : Code of the theme. This must match the value you provided in wp_register_theme_activation_hook function as $code * @param callback $function : Function to call when theme gets deactivated. */ function wp_register_theme_deactivation_hook($code, $function) { // store function in code specific global $GLOBALS["wp_register_theme_deactivation_hook_function" . $code]=$function; // create a runtime function which will delete the option set while activation of this theme and will call deactivation function provided in $function $fn=create_function('$theme', ' call_user_func($GLOBALS["wp_register_theme_deactivation_hook_function' . $code . '"]); delete_option("theme_is_activated_' . $code. '");'); // add above created function to switch_theme action hook. This hook gets called when admin changes the theme. // Due to wordpress core implementation this hook can only be received by currently active theme (which is going to be deactivated as admin has chosen another one. // Your theme can perceive this hook as a deactivation hook. add_action("switch_theme", $fn); } </code>
Theme Activate Hook
wordpress
I want users to be able to use a car template in new posts. The template will include items such as a photograph of a car, make, model, number of doors, colour of car, etc. Users will not want to use the template in every one of their posts. How should I do this? My idea is to: Create a new widget within the 'Add new post' page. This would contain a form in which the user can upload a photograph and enter data (in text input fields). Once the user has completed the form (within the widget), they could press a button (either in the widget or in the 'Add new post' toolbar) which will embed the form data into the new post. Please can you tell me if this would be a good/best approach, or if I should do it another way.
IMO this ia a good approach. However one thing I would focus is instead of embedding the data into the post body, you may insert custom fields in that post. This may help you sorting posts based on color, make etc or what ever your fields are.
How to embed form data within the 'Add new post'
wordpress
I'm setting up a blog that I'm trying to integrate the posts of into old site pages. The <code> $id = $_GET['article_id']; $post = get_post($id); setup_postdata($post); echo $post-&gt;post_content; </code> However, when I echo the blog post from <code> $post-&gt;post_content </code> , it seems that the html has been stripped out. The lines all run together. There are line breaks in the source, but there are no html <code> &lt;BR&gt; </code> s or <code> &lt;p&gt; </code> s. However, the post looks fine when I view it through the actual WordPress page. I have to use <code> &lt;pre&gt; </code> to get it to display properly, but then on the page, lines don't wrap and it defaults to that typewriter font. What am I doing wrong?
Post content, stored in database, is not equal to what gets displayed. It should be displayed with template tag function or at least run through <code> the_content </code> filter. Try: <code> the_content(); </code> Or: <code> echo apply_filters( 'the_content', $post-&gt;post_content ); </code>
Can't get blog entry to format properly using wp-load
wordpress
One of the big problems my site staff has had with tags is the overwhelming number of similar or duplicate tags, due to the write-in ability. I'm about to add new custom taxonomies to my site for them to use, but I'd like to avoid the problem we had with tags. I'm curious to know if I can turn off write-ins, so they can only be added manually through that taxonomy's part of the admin area. It's non-hierarchical, so they can still type in and the system will auto-complete and search for tags they might be looking for, which is great. I just don't want them to be able to create new tags from the post screen. Is this possible? I was looking at the Taxonomies and register_taxonomy() pages in the Codex, and thought maybe the "rewrite" function might be what I'm looking for, but I don't think it is now.
Here is what I came up with, seems to work: <code> add_filter( 'pre_post_tags_input', 'no_tags_input_create' ); add_filter( 'pre_post_tax_input', 'no_tax_input_create' ); function no_tags_input_create($tags_input) { $output = array(); foreach( $tags_input as $tag ) if( term_exists( $tag, 'post_tag') ) $output[] = $tag; return $output; } function no_tax_input_create($tax_input) { if( !isset($tax_input['post_tag']) ) return $tax_input; $output = array(); $tags = explode(',', $tax_input['post_tag']); foreach( $tags as $tag ) if( term_exists( $tag, 'post_tag') ) $output[] = $tag; $tax_input['post_tag'] = implode(',',$output); return $tax_input; } </code> This is for tags, you can easily extend second function to handle custom taxonomies.
Can I turn off write-in tags/taxonomies?
wordpress
This was really driving me crazy. I was debugging some code with code-generated transient names and they were failing like crazy for no apparent reason. After much much pain and experimentation I figured out that it fails when over certain key length: <code> $key = '1234567890'; var_dump( get_transient($key) ); // works just fine var_dump( set_transient( $key, $key, 10) ); // false when not expired $key = '1234567890123456789012345678901234567890123456'; var_dump( get_transient($key) ); // always returns false var_dump( set_transient( $key, $key, 10) ); // always true </code> Apparently <code> option_name </code> field in database is <code> varchar(64) </code> . However I absolutely can't figure out why this doesn't produce any database errors and all returns and hooks on setting transient work just fine... Except that in reality timeout option doesn't get written and it all fails miserably. I suspect this query in <code> add_option() </code> : <code> $result = $wpdb-&gt;query( $wpdb-&gt;prepare( "INSERT INTO `$wpdb-&gt;options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s) ON DUPLICATE KEY UPDATE `option_name` = VALUES(`option_name`), `option_value` = VALUES(`option_value`), `autoload` = VALUES(`autoload`)", $option, $value, $autoload ) ); </code> Can anyone help figure out what it should do when option's name passed is too long and why it doesn't produce errors or anything?
You don't get an error because WordPress does not check for the length , and MySQL silently truncates it (giving a warning, not an error), unless you enable the <code> STRICT_ALL_TABLES </code> option (which will change the warning into an error). Even more confusing, when you enable multisite the options are saved in the <code> sitemeta </code> table with a maximum key length of 255, but without multisite they go to <code> options </code> where the maximum key length is 64. Have fun debugging that in your plugin!
Long option names fail silently?
wordpress
I am working with a magazine client who sells adversiting offline in their magazine and now has a WordPress online magazine. Each of their stories is broken into different posts, and they are using the Wootheme Spectrum. They want the ads in the magazine to correspond to the ads online. So if Story B has Ad Z, then online, Post B should have Ad Z in the sidebar. However, Story A and C might have differents ads. What's the best way to accomplish this? Custom plugin? Plugin? Adsense? Thank you.
Hi @ewakened: The simplest solution would be to have them upload the ads as photos using the media features in WordPress and then to have them add custom field called "Advertisement" with the URL to the ad copied from the media module, and a custom field called and "Ad URL" to link to the advertiser's site. Then in the theme use the following to retrieve the add's URL: <code> &lt;a href="&lt;?php echo get_post_meta($post-&gt;ID,'Ad URL',true); ?&gt;"&gt; &lt;img src="&lt;?php echo get_post_meta($post-&gt;ID,'Advertisement',true); ?&gt;" /&gt; &lt;/a&gt; </code> Beyond that is would be very possible to create a custom metabox plugin that would allow them to upload one of more ads directly into the post edit screen but that would require more programming.
Specific and Different Ads for each Post?
wordpress
After a site of a friend has been hacked I told him he should just clean up the mess and restart from scratch so he know that no file has been altered. I could scan the site for him with tools like grep an so on (For a start: Grep and Friends ) but what I wondered about is, how to scan the database? What if some hacker has placed payload inside the database. Can be something simple like XSS or even PHP code in case there is some eval'ing still going on in core (or was at the time of the hack). Any suggestions? I thought about using SQL-Queries with the LIKE comparison function or there is even some REGEX possible. But maybe someone has already done this or wants to do this an has some ideas to share.
I've read that dumping the database as text and searching in it is a good way to go. You can search with phpmyadmin, but it's limited. Depends on the size of the database and a good text editor, but you can delete post/page revisions before dumping the database to bring it down in size. Or dump a few tables at a time.
Scanning Database for malicious Data
wordpress
I'd like to be able to filter out a commenters ability to add hyperlinks in their comment text. I removed the "websites" field from the mix to reduce the amount of spammage already (see: stackexchange-url ("Removing the "Website" Field from Comments and Replies?")") which has helped a lot. By default, they can use the '&lt; a '> tag to do so in the comment box text, which allows spammers to embed hyperlinks to their sites. Is there a way to filter out that capability in the wysiwyg editor for comment fields?
WP runs so many prettifying filters on this stuff that it's easy to get lost. Here is what I ended up with: <code> remove_filter('comment_text', 'make_clickable', 9); add_filter('pre_comment_content', 'strip_comment_links'); function strip_comment_links($content) { global $allowedtags; $tags = $allowedtags; unset($tags['a']); $content = addslashes(wp_kses(stripslashes($content), $tags)); return $content; } </code> This scrubs out clearly defined links and removes filter that turns plain text links into properly tagged ones.
How to remove commenters ability to add hyperlinks to comments?
wordpress
Ever tried this? <code> // template file do_action( 'my_hook' ); // ex. functions.php function my_hooked_template_part() { get_template_part( 'my_loop_part_file', 'default' ); } add_action( 'my_hook', 'my_hooked_template_part' ); // my_loop_part_file-default.php get_template_part( 'query', 'default' ); if ( have_posts() ) { while ( have_posts() ) : the_post(); etc. // query-default.php $args = array( 'whatever' =&gt; 'and_so_on' ); query_posts( $args ); </code> Maybe it's my setup, but it won't load the file. Could it be that it's too late for loading some other file inside? Can anyone confirm or this just a drawback of using the get_template_part() function (only one file - no nesting)?
If your comments in the code above reflect the file names then it's a dash vs. underscore mistake. Name of the second included file should be query-default.php
get_template_part inside get_template_part?
wordpress
I want the user to fill in a form (when they create a new blog post). The results of the form should be embedded within the new blog post. So I am trying to think of the best way of coding this. Meta boxes might be the best way? Edit, the original question changed a little. The old one was: How can I add a Dashboard Widget into a custom Plugin Options Page? I have followed the example here http://codex.wordpress.org/Dashboard_Widgets_API to create a custom Dashboard Widget, but cannot see how to add it into my custom plugin options page (which is found under the 'Settings' sidebar in the Control Panel).
Dashboard widgets only go on the dashboard. You can't put 'em on any other pages, as far as I know. For a primer on plugin options, see the codex article on creating plugin options pages . Is there any reason you need to add a widget-style meta box in your settings page? Are you after the drag-and-drop functionality, or the expand-collapse functionality? If so, you might modify your question to ask for those things specifically. EDIT What you're looking for (based on your comments) are called meta boxes, not widgets (it takes a while to learn all the WordPress-specific terminology). There are some easy-to-use WordPress functions for adding meta boxes to the post creation/editing page--you don't need to create a separate admin page for them. To actually save the information entered into these boxes, you'll want to hook into the save_post action. This is all explained (including a copy/paste example you can play with) in the codex article on the add_meta_box function .
How to add meta boxes to the 'Add new post' screen?
wordpress
I'm running into circles trying to set up a simple rewrite rule, and thought I'd run the question by some of the rewrite experts here. I have a custom post type, "mealplan", and I'm trying to implement a basic url rewrite where visitng <code> site.com/mealplan/current </code> will take the visitor to the most recent post of type "mealplan". I've tried using several variants on this rule: <code> global $wp_rewrite; $wp_rewrite-&gt;add_rule('mealplan/current', 'index.php?post_type=mealplan&amp;numberposts=1&amp;orderby=date&amp;order=DESC', 'top' ); </code> ... but I can't seem to get either the 'numberposts' or the 'posts_per_page' parameters to do anything in the query string like that. It just goes straight to the archive page with the default number of posts per page. This does what I want: <code> global $wp_rewrite; $current_mealplan = get_posts( array( 'post_type'=&gt;'mealplan', 'numberposts'=&gt;1, 'orderby'=&gt;'date', 'order'=&gt;'DESC' ) ); $wp_rewrite-&gt;add_rule('mealplan/current', 'index.php?post_type=mealplan&amp;post_id='.$current_mealplan[0]-&gt;ID, 'top'); </code> ...but at the cost of an additional query and a potential flush rules on every page load. Even if I optimize this by saving the current post ID in an option that's updated on <code> update_post </code> (so rules only have to be flushed when they change), this feels like unnecessary work that could be avoided if I could only get the url parameters above to work correctly.
Well, <code> numberposts </code> is not actually a query variable. It's just turned into <code> posts_per_page </code> in <code> get_posts() </code> before the query is run. <code> posts_per_page </code> is a private query var, which means you can't run it in the query string. A possible solution would be to register a custom query variable (let's say <code> 'latest_mealplan' </code> and add that variable to the rewrite rule (e.g. <code> index.php?post_type=mealplan&amp;orderby=date&amp;order=DESC&amp;latest_mealplan=1 </code> ). Then, hook into <code> 'parse_request' </code> , which passes the <code> $wp </code> object to the callback. From there, it's just a matter of setting the parameter: <code> if( !empty( $wp-&gt;query_vars['latest_mealplan'] ) ){ $wp-&gt;query_vars['posts_per_page'] = 1; add_filter( 'template_include', create_function( '$a', 'return locate_template(array("single-mealplan.php"));' ) ); } </code> Hope this helps!
Can 'numberposts' be passed in the URL query string?
wordpress
I have two Wordpress installs, both with a little bit of different data. I have a LIVE site and I have a DEV Site. I need to merge the content of these two databases together to make a STAGING Site. I need to merge the new Posts/Pages/Comments/Categories from DEV to a LIVE database backup, and then make that database become STAGING. What is best, easiest, and least time consuming way of tackling this? NOTE: XML Importer will not work for this task as the amount of data is too large.
NOTE: XML Importer will not work for this task as the amount of data is too large. This tool is by far the simplest solution if there's any way you can get it to work. Is it absolutely "too large" for the importer, or just limited by file upload / PHP execution time limits? If I were doing this, I'd crank up the limits on my development environment to process a really big XML file. If that won't work, I'd probably guess that you have some mucking around in SQL to do. :-P
Best Way to Merge a Dev and Live Site to Become a Staging Site?
wordpress
What's the easiest way to get a subscribe to this blog for a private P2-Themed Site? I want to have an obvious link on the page without having to modify the theme so that everyone using the site can easily see the link. Ideally I'd also be able to see who is subscribed and if possible subscribe them myself (it's the team members for the project I want to make sure are subscribed.) Suggestion for the best plugin for this?
I use a combination of Subscribe to Comments and Subscribe2, but it's not pretty.
Subscribe to this Blog for a Private P2 Themed Site?
wordpress
How to install Wordpress for ios on Apple's SDK's iPhone/iPad simulator? and what are other ways to make Wordpress Admin compatible with iphone?
This seems to be stackexchange-url ("answered on Stack Overflow"). The accepted answer refers to a thread on the MacRumors forum .
How to install "Wordpress for ios" on Apple's SDK's iPhone/iPad simulator?
wordpress
I run a video game news blog. When my staff writes a news article or a review, I would like them to be able to "assign" that post to a game (if applicable), so then I could have the single.php template call information on that game (title, boxart, publisher, release date, etc.) and display it in the sidebar. I thought this might involve a custom taxonomy so that it could be assigned to a post just like tags are. But then I realized I also wanted those games to have full pages loaded with information. I initially thought to create a custom post type for pages, and using custom fields, I could call the game's box art, show its release date, display any posts or reviews on that game and displaying them with brief excerpts, and using custom taxonomies to display the game's publisher, developer, etc... And THEN I realized I also wanted those publishers and developers to have their own pages as well. Description, location, links to articles involving them, lists of any games attributed to them... and so on. None of these can be child pages of the other, since developers aren't always permanently tied to any particular publisher, games are sometimes co-developed by multiple parties, etc. I'm in a pickle, and can't figure out how to re-organize my site. I really want to use all the new toys in WordPress to make the site I want, rather than WP limiting what I can do. Any suggestions? I've been brainstorming for days trying to figure something out. Any suggestions would be appreciated.
There are a few choices to go with this. I've actually gone through the same though process you have been. It would be easy if Wordpress let you link posts or custom post types together but in lieu of that, the hackery of Wordpress developers must occur! The solution I went with in the plugin I'm working on is a bit hacky, but it works for me. Basically in my plugin, I wanted to have a post type called series that holds info on a particular tv series, a post type for episodes and another post type for DVD and Blu-ray releases. I wanted both the episode and releases post types to reference the series type they come from, so if I create a single series post page, it could list the episodes and releases as well as the series info. My solution involves a custom field that holds the object id of the series. The first way to accomplish this was to create a metabox that had a select box of all the posts of type series: <code> public function get_select_array($post_type) { global $wpdb; $query = "SELECT ID, post_title FROM $wpdb-&gt;posts WHERE post_type = '$post_type' AND post_status = 'publish' ORDER BY post_title"; $results = $wpdb-&gt;get_results($query, OBJECT); $series = array(); foreach ($results as $result) { $series[] = array('name' =&gt; $result-&gt;post_title, 'value' =&gt; $result-&gt;ID); } return $series; } </code> The function get_select_array() basically takes a custom post type and returns the post titles and ID's of all the ones that are published in an array. I then use that array to populate a select box. In my plugin, I'm using the metabox creation class created by Rilwis but I'll post some code for you to use (code is adapted from Rilwis's code): <code> add_meta_box('parent_series', 'Series', 'show_series_metabox', 'episode', 'side', 'high'); //add a side metabox function show_series_metabox() { global $post; echo '&lt;input type="hidden" name="wp_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" /&gt;'; //nonce $series = get_select_array('series'); //get post titles and ID's of post type 'series $meta = get_post_meta($post-&gt;ID, 'parent_series', true); //get the meta value of the custom field echo '&lt;select name="parent_series" id="parent_series"&gt;';//create the select box foreach ($series as $s) { echo '&lt;option value="', $s['value'], '"', $meta == $s['value'] ? ' selected="selected"' : '', '&gt;', $s['name'], '&lt;/option&gt;'; } echo '&lt;/select&gt;'; } add_action('save_post', 'save_series_metabox'); function save_series_metabox() { $real_post_id = isset($_POST['post_ID']) ? $_POST['post_ID'] : NULL ; //get post id $old = get_post_meta($real_post_id, 'parent_series', true); //get old stored meta value $new = $_POST['parent_series']; //new meta value if ($new &amp;&amp; $new != $old) { //saving or deleting value update_post_meta($real_post_id, 'parent_series', $new); } elseif ('' == $new &amp;&amp; $old) { delete_post_meta($real_post_id, 'parent_series', $old); } } </code> This will add a metabox that has a select that lists all the series available. When the post is saved, the id of that series will be saved in a custom field called 'parent_series'. Once that is done, you can call on that id and use it to call the series info via a custom query. Or its possible to do the opposite: on the series page, you do a query for all the episode pages that have the same value in their custom field/meta data. And there you have it. Using this code you can link posts of one type to those of another, making them work like pseudo taxonomies in a way. I edited the code up pretty quickly so if you find any errors or bugs, let me know. If there are better ways to do this, please let me know :)
Making pages also serve as taxonomies? Or give full pages to taxonomies?
wordpress
How can i echo total number of posts in last year ? I‚m writing article with stats, and want to get number of posts i published last year. There is something here, but not for last year http://perishablepress.com/press/2006/08/28/display-total-number-of-posts/ It displays only total number of all posts
All you need to do is modify the SQL query. Using the code you linked as a base: <code> $numposts = $wpdb-&gt;get_var("SELECT COUNT(*) FROM $wpdb-&gt;posts WHERE post_status = 'publish' AND year(post_date) = 2010"); if (0 &lt; $numposts) $numposts = number_format($numposts); </code> The 'AND' I added basically gives you all the posts of 2010. Change the year accordingly
Total number of posts in last year
wordpress
What are the actions that a plugin can hook on to for processing when the user deletes a category?
<code> wp_delete_category() </code> is a small wrapper around <code> wp_delete_term() </code> ( source ). It has number of hooks, the one that comes right before delete is: <code> do_action( 'delete_term_taxonomy', $tt_id ); </code> Hooks after delete: <code> do_action( 'deleted_term_taxonomy', $tt_id ); do_action('delete_term', $term, $tt_id, $taxonomy); do_action("delete_$taxonomy", $term, $tt_id); </code> There are also few earlier hooks that deal with remapping children terms.
Which are the hooks run before/after when a category's deletion?
wordpress
I'm using the WP Super Cache plugin and inside my theme I have code that executes differently if the site is viewed on a mobile device (iOS, Android) than a desktop browser. How do make WP Super Cache create a separate cache for each, most likely via the user agent? Right now, I have use mod_rewrite to serve cache, which I believe WP Super Cache will cache the pages as html files to be served. Since the cache is saved from the desktop browser, the mobile browser is seeing that as well. I'd like WP Super Cache to generate two separate caches, one of mobile devices and another for desktop browser. Is this something WP Super Cache can handle or is there a better cache plugin I should be using to make this work? Thanks!
There are several ways to handle mobile devices and doing it inside of single theme is builky and hard to maintain (as for me at least). More commonly this seems to be accomplished with separate templates or separate mobile-specific theme. I don't know about WP Super Cache specifics because I hadn't used it extensively. Plugin I currently use is W3 Total Cache . It allows you to create groups of user agents strings, for which visitors can be redirected to another theme or domain and (as I understand from description of settings) will have separate versions of cached pages.
WP Super Cache separate cache for mobile
wordpress
I have two WordPress installations, one at http://inversekarma.in and the other at http://inversekarma.in/photos . The latter is a photoblog, and its theme uses the standard WP post thumbnails ( EDIT: featured images, to be precise!). Is there a way to show the most recent thumbnails from the second site on my first site's sidebar?
There are (at least) two (2) ways to approach this: You can query the second database which will require you to maintain the database credentials in two places, or at least in an include file, or You could create a simple JSON feed for your photo blog and consume the feed on your main blog and cache it for a short time. This will cause a slight latency on page load when the cache expires but since both are on the same machine it shouldn't be an issue. Let me know which you'd prefer and if I'll update the answer to so you how. UPDATE To connect to another database you can read more about it here: <a href="stackexchange-url Using wpdb to connect to a separate database So here's what I hacked together for you, a function called <code> show_thumbnails_2nd_db() </code> which you can copy into your theme's <code> functions.php </code> file: <code> function show_thumbnails_2nd_db() { global $wpdb; global $table_prefix; $save_wpdb = $wpdb; $save_prefix = $table_prefix; include_once(ABSPATH . '/photos/database-credentials.php'); extract($database_credentials); $wpdb = new wpdb($DB_USER, $DB_PASSWORD, $DB_NAME, $DB_HOST); wp_set_wpdb_vars(); // This is the code for featured images $sql = &lt;&lt;&lt;SQL SELECT DISTINCT CONCAT('&lt;img src="',attachment.guid,'"/&gt;') AS url FROM {$wpdb-&gt;posts} attachment INNER JOIN {$wpdb-&gt;postmeta} ON attachment.ID={$wpdb-&gt;postmeta}.meta_value AND {$wpdb-&gt;postmeta}.meta_key='_thumbnail_id' INNER JOIN {$wpdb-&gt;posts} ON {$wpdb-&gt;posts}.ID={$wpdb-&gt;postmeta}.post_id WHERE {$wpdb-&gt;posts}.post_status='publish' AND attachment.post_type='attachment' ORDER BY attachment.ID DESC LIMIT 10 SQL; $post_urls = $wpdb-&gt;get_col($sql); if (is_array($post_urls)) echo implode("\n",$post_urls); // This is the code for post thumbnails // $sql = &lt;&lt;&lt;SQL // SELECT DISTINCT {$wpdb-&gt;posts}.ID // FROM {$wpdb-&gt;posts} // INNER JOIN {$wpdb-&gt;posts} attachment // ON {$wpdb-&gt;posts}.ID=attachment.post_parent // WHERE {$wpdb-&gt;posts}.post_status='publish' // AND attachment.post_type='attachment' // ORDER BY attachment.ID // LIMIT 10 // SQL; // $post_ids = $wpdb-&gt;get_col($sql); // foreach($post_ids as $post_id) { // $thumbnail = get_the_post_thumbnail($post_id); // if ($thumbnail) { // echo $thumbnail; // } // } $table_prefix = $save_prefix; $wpdb = $save_wpdb; } </code> Note: That the above assumes you have created a <code> database-credentials.php </code> in the root of your photos blog, and it should look like this: <code> &lt;?php $database_credentials = array( 'DB_NAME' =&gt; 'your_database', 'DB_USER' =&gt; 'your_db_user', 'DB_PASSWORD' =&gt; 'your db password', 'DB_HOST' =&gt; 'localhost', 'table_prefix' =&gt; 'your_photos_db_prefix_', ); </code> Then inside the <code> /wp-config.php </code> for your photos blog you would replace the sections of code that look like this: <code> // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', 'your_database'); /** MySQL database username */ define('DB_USER', 'your_db_user'); /** MySQL database password */ define('DB_PASSWORD', 'your db password'); /** MySQL hostname */ define('DB_HOST', 'localhost'); </code> And this: <code> $table_prefix = 'wp_'; </code> With this: <code> include_once(ABSPATH . '/database-credentials.php'); // ** MySQL settings - You can get this info from your web host ** // /** The name of the database for WordPress */ define('DB_NAME', $database_credentials['DB_NAME']); /** MySQL database username */ define('DB_USER', $database_credentials['DB_USER']); /** MySQL database password */ define('DB_PASSWORD', $database_credentials['DB_PASSWORD']); /** MySQL hostname */ define('DB_HOST', $database_credentials['DB_HOST']); $table_prefix = $database_credentials['table_prefix']; </code> If you need more explanation just ask in the comments.
Getting post-thumbnails from another WP site
wordpress
When I'm logged out, everything works fine. When I'm logged in, I'm unable to visit the front-end of my site. My main page is actually located in a sub-folder of my multisite installation: http://beta.eamann.com/mindshare/ . I'm mapping a domain to this installation: http://mindsharestrategy.com/ . When I'm logged in, the front-end of my site keeps bouncing back and forth between these two domains. I can still get to the admin side just fine ... but not the front-end. If I log out, I can view the front-end of things just fine. I'm using the development version of the plug-in, as I was instructed to do by several conversations with the developers. Ideas? I should also note that the other sites on this network are not having this issue. They are working properly: http://eamann.com -> http://beta.eamann.com/portfolio/ http://prosepainting.com -> http://beta.eamann.com/creative/ There is no infinite redirect loop here. What can I check to fix the problem?
this is not a full answer but probably of use to gain more information about your problem. I guess it's related to cookies but that is really a guess only. To find out more I suggest a combination of two tools: One Firefox and a wordpress Add-On. No Redirect Toolpress Strict Edition (Firefox Add-On) On Toolpress in the tools folder , you can find a Firefox Add-On that is tracking every redirect and can prevent automatic redirection on those. It's called NoRedirect 1.2.4 Toolpress Strict Edition (Firefox Add-On) . Install it, restart Firefox. Then go to Menu: Tools -> NoRedirect which opens the configuration dialog. Enter a URL pattern like <code> ^http://.* </code> and *un*check the Allow checkbox: You will now get a notification prior to any redirect: You can click the link in the grey area. The website you see is the redirect body which is generated (here by stackexchange). Wordpress by default does not return and HTTP Body for redirects which is getting the HTTP specs wrong as HTTP clients do not need to redirect automatically. Better HTTP Redirects (Wordpress Plugin) Next to that grab my Better HTTP Redirects Plugin . It deals with the wordpress core defect and returns a HTTP body for each redirect . There is a hook available called <code> redirect_hypertext </code> in which you can hook into (or just hack this plugin which is must-use compatible as well) and output the backtrace that caused the redirect (hint: xdebug ). Power of the two: The firefox plugin will ensure that you're not getting redirected without confirmation and the wordpress plugin will taking care to display debug information. This hooktracer tool (SJ Hook Profiler) might be of use as well but I have not used it so far.
Infinite loop problem with the WordPress MU Domain Mapping plug-in
wordpress
Is there any way to use <code> str_replace() </code> in Wordpress outside the loop? I want to change my html markup which starts before the loop. I need something like this: <code> function content_magic($content) { str_replace('&lt;div id="content"&gt;','&lt;div id="new_content"&gt;',$content); return $content; } add_filter('the_content','content_magic'); </code> But this works only for markup within the loop. Please help me!
Filters don't really affect resulting markup. More precisely they affect anything that is passed through them, in this specific case output of <code> the_content() </code> function is passed through <code> the_content </code> filter and you are able to modify it. If markup you want to change is not generated by function and not passed through filter then most likely you will need to edit theme's template file that markup belongs to. It is also good practice to create and use child theme to retain compatibility with theme updates and such if you are going to edit template.
How to use str_replace() outside the loop?
wordpress
i just transferred my website from shared server to VPS, but then it is not starting, when i inquired with the VPS technical support then they emailed me something this, which i am not understanding:- email Your site "www.onlinemba.co.in" has been migrated from your previous host and we are now getting a blank page while accessing the database dependant php files. There seems to be an issue with the database codings as all other php files are accessing fine and there is also no problem with the database connectivity. You can check for the same by accessing the site preview URL "http://38.100.101.228/info.php". Your Kloxo panel details are URL : XXXXX User : XXXXXX pass : XXXXX Server root access detail are as follows IP : 38.100.101.228 User : XXXXXXX Pass : XXXXXXX Kindly check your database once with your database developers with the details given above and let us know for further help. what should i do? ok well i did some changes for this in wp-config.php, but after that the admin guys from hosting are saying me this: Virtual host entry for the IP is pointing to different folder ( which doesn't have any contents ), hence you have received the default page. I have pointed in to the correct folder "onlinemb". You can view the blank page, please check and resolve it. i edited the database MySql hostname from local host, to the IP-38.100.101.228 but then he changed again to local host, and again the blank page came, what to do now?
I believe Rarst is right. It sounds like you need to configure the wp-config.php file for the new database. Just go to the cpanel or other control panel of your hosting service, and use the address they use for the host address. If the database is on the same server as the web site, localhost is used. I am not sure how you moved you website. I assume that it is a WordPress site, and it is not difficult to move. When I did this, I made a new installation of WordPress on the new hosting service. This included installing WordPress with a new database. Then, I went to the old site WordPress dashboard, found the Export menu, and saved the resulting XML file. This file contains all the database info for your site. At the new site, I simply went to the new site dashboard Import menu and imported the file from the old site. The new database system then had the correct data from the old site. There were a few issues on the new site, mainly dealing with cosmetic things. As a matter of fact we should all keep a current backup of our WordPress database, and there is a plugin for that.
Server database problem
wordpress
I am trying to build custom user profile with the guidance of this tutorial: How to make a WordPress profile page I have successfully implemented it to my theme, everything is working well. Now what I want to achieve is to get the comment template in the user profile page, where other registered user can post comment on his profile page, kinda like facebook wall or last.fm shoutbox. I am trying it like this: In the author page I am added this line: <code> &lt;?php comments_template(); ?&gt; </code> But it does not show up. Then I tried this way: Get WordPress comments outside of WordPress It adds the comment template alright but, does not work. When you click on on the submit button it redirects to a blank page. I think the goal is not achievable easily, it requires custom database creation for each user to store the comments, since the comment system only stores comments of certain page or post, not for any other page like archive or author page. If anyone can show me the right direction, I will be forever grateful. Thanks Towfiq I.
Hi @Towfiq : Comments are related in the database to Posts. You'll have to do a lot of work to get Comments to relate to Users. Have you considered creating a Custom Post Type for Users and then use either a <code> user_meta </code> field to store the <code> post_id </code> , or a <code> postmeta </code> field to store the <code> user_id </code> , or both? If you did that then you would get the comments with no effort at all. UPDATE What follows is code developed after our discussion in the comments. I've been meaning to write something like this for a long time but your question finding got me to make it a priority. I've created a <code> 'towfiq-person' </code> custom post type for you and I've set it up to automatically add a Person post whenever a User is added and it uses the email address as the associating key in a post custom field called <code> '_email' </code> . It also associates a User with an appropriate email address to the Person post if a User is added or updated with the same email as an existing Person (this may or may not be a good idea.) And it cross-references User with Person and Person with User using postmeta and usermeta fields <code> '_user_id' </code> and <code> '_person_id' </code> , respectively. These are of course business rules I chose to implement but they may turn out not to be appropriate for your use-case in which case you may need to modify them. You also may find ways that WordPress allows these two to get out of sync but it's hard to know that without exhaustive testing. If you find issues you can always look to update the logic to resolve them. You can copy the following code to your theme's <code> functions.php </code> file: <code> class Towfiq_Person { static function on_load() { add_action('init',array(__CLASS__,'init')); add_action('wp_insert_post',array(__CLASS__,'wp_insert_post'),10,2); add_action('profile_update',array(__CLASS__,'profile_update'),10,2); add_action('user_register',array(__CLASS__,'profile_update')); add_filter('author_link',array(__CLASS__,'author_link'),10,2); add_filter('get_the_author_url',array(__CLASS__,'author_link'),10,2); } static function init() { register_post_type('towfiq-person', array( 'labels' =&gt; array('name'=&gt;'People','singular_name'=&gt;'Person'), 'public' =&gt; true, 'show_ui' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'people'), 'hierarchical' =&gt; false, //'supports' =&gt; array('title','editor','custom-fields'), ) ); } static function get_email_key() { return apply_filters( 'person_email_key', '_email' ); } static function profile_update($user_id,$old_user_data=false) { global $wpdb; $is_new_person = false; $user = get_userdata($user_id); $user_email = ($old_user_data ? $old_user_data-&gt;user_email : $user-&gt;user_email); $email_key = self::get_email_key(); $person_id = $wpdb-&gt;get_var($wpdb-&gt;prepare("SELECT post_id FROM {$wpdb-&gt;postmeta} WHERE meta_key='%s' AND meta_value='%s'",$email_key,$user_email)); if (!is_numeric($person_id)) { $person_id = $is_new_person = wp_insert_post(array( 'post_type' =&gt; 'towfiq-person', 'post_status' =&gt; 'publish', // Maybe this should be pending or draft? 'post_title' =&gt; $user-&gt;display_name, )); } update_user_meta($user_id,'_person_id',$person_id); update_post_meta($person_id,'_user_id',$user_id); if ($is_new_person || ($old_user_data &amp;&amp; $user-&gt;user_email!=$old_user_data-&gt;user_email)) { update_post_meta($person_id,$email_key,$user-&gt;user_email); } } static function wp_insert_post($person_id,$person) { if ($person-&gt;post_type=='towfiq-person') { $email = get_post_meta($person_id,self::get_email_key(),true); if (filter_var($email, FILTER_VALIDATE_EMAIL)) { $user = get_user_by('email',$email); if ($user) { // Associate the user IF there is an user with the same email address update_user_meta($user-&gt;ID,'_person_id',$person_id); update_post_meta($person_id,'_user_id',$user-&gt;ID); } else { delete_post_meta($person_id,'_user_id'); } } } } static function get_user_id($person_id) { return get_user_meta($user_id,'_user_id',true); } static function get_user($person_id) { $user_id = self::get_user_id($person_id); return get_userdata($user_id); } static function get_person_id($user_id) { return get_user_meta($user_id,'_person_id',true); } static function get_person($user_id) { $person_id = self::get_person_id($user_id); return get_post($person_id); } static function author_link($permalink, $user_id) { $author_id = get_user_meta($user_id,'_person_id',true); if ($author_id) // If an associate is found, use it $permalink = get_post_permalink($author_id); return $permalink; } } Towfiq_Person::on_load(); </code> If you need any clarifications to what I did and why, just ask in the comments.
Commenting in user profile page?
wordpress
I am adding administration pages using <code> add_menu_page() </code> function. But it wont look good. Check the image below. I would like to have it as separated and in between Appearance and Plugins section with rounded borders.
This will put one separator right after 'Appearance' and one right before 'Plugins'. Just make sure to give your menu position 62 or 63. You can just add it to whatever file is adding the admin page to begin with. This should be called after everything else has been added. <code> function jpb_menu_isolator(){ global $menu; $menu[61] = array('', 'read', 'separator3', '', 'wp-menu-separator'); $menu[64] = array('', 'read', 'separator3', '', 'wp-menu-separator'); uksort($menu,'strnatcasecmp'); } add_action( 'admin_menu', 'jpb_menu_isolator', 1000 ); </code>
Administration Pages Styling
wordpress
On a multi author WordPress blog I need to show a list with more posts from the current author. The list is inside the Loop, so I can use <code> &lt;?php the_author_meta('first_name'); ?&gt; &lt;?php the_author_meta('last_name'); ?&gt; </code> and <code> &lt;?php the_author_meta('description'); ?&gt; </code> , but how to retrieve the user's posts?
This will retrieve the posts of current author when used in the loop. Put the following in your theme functions.php: <code> function my_get_display_author_posts() { global $authordata, $post; $authors_posts = get_posts( array( 'author' =&gt; $authordata-&gt;ID, 'post__not_in' =&gt; array( $post-&gt;ID ) ) ); $output = '&lt;ul&gt;'; foreach ( $authors_posts as $authors_post ) { $output .= '&lt;li&gt;&lt;a href="' . get_permalink( $authors_post-&gt;ID ) . '"&gt;' . apply_filters( 'the_title', $authors_post-&gt;post_title, $authors_post-&gt;ID ) . '&lt;/a&gt;&lt;/li&gt;'; } $output .= '&lt;/ul&gt;'; return $output; } </code> And add <code> echo my_get_display_author_posts(); </code> in your template file, within the loop where you want the posts displayed.
More posts from the current author
wordpress
Hello friends I am trying to get my wordpress posts to display in a non- wordpress application. Currently I am getting them by using the following method. My wordPress page is something like this: <code> &lt;div id="header"&gt; &lt;!-- header content goes here --&gt; &lt;/div&gt; &lt;div id="main-body"&gt; &lt;div id="content"&gt; &lt;!-- Main Body goes here --&gt; &lt;/div&gt; &lt;div id="sidebar"&gt; &lt;!-- My Sidebar Widgets go here --&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="footer" &lt;!-- My footer goes here --&gt; &lt;/div&gt; </code> and I am using: <code> &lt;?php file_get_contents('http://mysite.com/blog'); ?&gt; </code> It's working ok but there are 2 issues......... It is getting the entire page. My page stops loading till it fetches the wordpress data. Hence I thought AJAX was the solution. But I don't know AJAX. hence decided to seek help here. What I am looking for is that I just want the output content of #Content Div and #sidebar Div separately so that I can place them in my other application in two different places. I don't even need the CSS or JS as they are common for both my themes. I just want the output and separately placed at 2 different place. Please help.
If it is all on same server it is rather easy to load WP engine and parts you need, see Integrating WordPress with Your Website . Otherwise there is probably better to get specific data (rather than whole page) from WordPress remotely, but there are a lot of approaches to that. Also I am not aware of any off-the-shelf code that allows to do that for sidebars. For post content there is XML-RPC support and plugins for other formats (I think I read about JSON one).
WordPress : using AJAX to get posts & Sidebar Content to an external application
wordpress
when does &lt;!--nextpage--&gt; get processed by wordpress filtering. i am adding multiple paged posts in post content on the content_save_pre and this is good for rendering my shortcodes, but &lt;!--nextpage--&gt; doesnt get processed and shows up as an html comment
I am not sure what you mean by rendering shortcodes at that stage, they are usually rendered when content is retrieved for display. nextpage tag is processed in <code> setup_postdata() </code> ( source ), which is called by <code> the_post() </code> . In other words - during Loop.
When does wordpress process &lt;!--nextpage--&gt;
wordpress
Hi to the community, i try to build a shortcode that prints the Creative Commons logo and some text, everything is working fine except that i put the shortcode at the end of the post but the shortcode goes to the top of the post content, i use the code bellow: <code> &lt;?php // Creative Commons License Shortcode function creativecommons( $atts, $content = null ) { extract( shortcode_atts( array( 'type' =&gt; '', 'code' =&gt; '', ), $atts ) ); { ?&gt; &lt;div class="license"&gt; &lt;div class="cc-img"&gt; &lt;img src="&lt;?php bloginfo('template_directory'); ?&gt;/images/cc.png" width="32" height="32" alt="Creative Commons License" /&gt; &lt;/div&gt; &lt;div class="cc-content"&gt; &lt;h4&gt;&lt;?php echo $type ?&gt;&lt;/h4&gt; &lt;small&gt;&lt;?php echo $code ?&gt;&lt;/small&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- end of license --&gt; &lt;div class="clear"&gt;&lt;/div&gt;&lt;!-- clear div --&gt; &lt;?php } return; } add_shortcode('cc1', 'creativecommons'); ?&gt; </code> I'm missing something here or something else have to do with my problem? Thanks a lot, Philip
Couple things: I think your shortcode function should return the value rather than print it, and you shouldn't have the output wrapped in braces like that (the one just before the first div, and the one just before the return). Unless that's some obscure php syntax I've never seen (which is entirely possible)? As far as I know, whenever you close a php tag--even inside a function--the parser will just immediately output the results, not return them.
What is wrong with this Shortcode? I get it in a wrong place inside the content
wordpress
What are plugins that are added to a post or page using comments...for instance I am aware of the <code> &lt;!--nextpage--&gt; </code> tag, (it's part of Wordpress not a plugin...) but I'm assuming that there may be plugins out there with functionality that is placed in a post in a similar manner. What is the name of plugins that operate in this manner?
There's a similar concept for plugins called shortcodes (as andrewk said). The syntax for these is slightly different than the more tag (which does look a lot like an html comment). Shortcodes are wrapped in square braces like so: <code> [myshortcode arg1="something" arg2="something else"] </code> Shortocde is the term for the technique, but plugins that implement shortcodes don't have any special name or anything. They're just plugins that use the shortcodes API. Similarly, plugins that use the widget API (or any other WP functionality) don't have special names. They're all just plugins. As far as I know, there is no built-in API for implementing "html comment-style" tags like the more tag. And I don't think the technique is in popular use by plugin developers since the shortcode API became available. At least, I don't see it very often.
Is there a specific term for Plugins that are specified in a Wordpress Post using Comments?
wordpress
Is there a Wordpress Plugin that you can give it a list of old tweets (specified by url or tweet number (for example: http://twitter.com/#!/leeand00/status/20215977534820353 ) and put them on a map, which will slowly move between them (in demo mode) and then allow the user to click on those tweets? (Just figured I'd check before implementing one) P.S. Can someone please tag this post with "Google Maps" or "Maps" please.
I'm not entirely sure if this will help in EXACTLY the way you are looking for, but when it comes to map integration into posts, I love to use MapPress . It supports a pretty robust API which allows you to hook into the plugin to do some custom things, and I'm sure with a little work you could get to where you want to be with your project. I don't usually like the pay-for plugins but I highly recommend buying his MapPress Pro, it works very very well, is highly versatile, and he is always keeping it updated.
Wordpress Plugin for Maps of specific Tweets?
wordpress
I was wondering if someone can help me with this. I'm currently following Shibashake's tutorial about creating custom meta-boxes that include taxonomy selection here: http://shibashake.com/wordpress-theme/wordpress-custom-taxonomy-input-panels . They show how to remove the standard metabox Wordpress automatically creates for taxonomies using the remove_meta_box function. Only problem is that the function for some reason doesn't seem to work on taxonomies that work as categories ie ones where the hierarchical option is set to true. I know I have the function working because the ones set up as tags disappear easily enough. I can't if it just isn't possible or if there is something special I need to add in one of the parameters to make it work. Example: <code> $args = array( 'hierarchical' =&gt; false, 'label' =&gt;'People', 'query_var' =&gt; true, 'rewrite' =&gt; true ); register_taxonomy('people', 'post',$args); remove_meta_box('tagsdiv-people','post','side'); </code> That works fine. If I set hierarchical to 'true, however, the meta box stays put. Can anyone shed some light?
Non-hierarchical taxonomies (like tags) use <code> tagsdiv-{$tax_name} </code> . Hierarchical taxonomies (like categories) use <code> {$tax_name}div </code> . This is for historical reasons: categories were placed in <code> categorydiv </code> , tags in <code> tagsdiv </code> . When support for multiple non-hierarchical taxonomies was added, the <code> tagsdiv </code> name was expanded to <code> tagsdiv-{$tax_name} </code> . When finally multiple hierarchical taxonomies were made possible, they choose to generalize <code> categorydiv </code> to <code> {$tax_name}div </code> .
How do you remove a Category-style (hierarchical) taxonomy metabox?
wordpress
I'm new to the "posts_" filter hooks and wanted to know a few things from those in the know: In this stackexchange-url ("question"), someone posted an answer using posts_join that took a second parameter of $query: add_filter('posts_join',array(&amp;$this,'posts_join'),10,2); ... function posts_join($join,$query) { } Is this an instance of wp_query or something similar? -Same example: how would I determine the post type so that I can do custom joins for each custom post type I have on the admin side -What does the posts_fields filter hook do? from the example I've seen, it looks like it replaces the columns in the SELECT clause of an SQL call. Am I correct in that assumption? And does it too have more parameters that can be called?? I find some examples but I can't get any solid documentation anywhere. Thank you in advance for all answers given
When you use one of the methods to query for posts ( <code> query_posts() </code> , <code> get_posts() </code> or <code> WP_Query </code> object) arguments you provide are processed and turned into SQL query. This happens in <code> WP_Query-&gt;&amp;get_posts() </code> method. Since arguments are not omnipotent there are a lot of hooks in there that allow to modify or override parts of resulting SQL query. <code> posts_join </code> is part of query that handles SQL JOINs - adding additional tables to the mix, for example tables related to taxonomies when they are needed. <code> posts_fields </code> seem to control which database fields will be returned in query, it seems to default to all fields from <code> posts </code> table.
Explanation of the "posts_join" and "posts_fields" filter hooks?
wordpress
I have a spreadsheet that was provided to me of users to import to a new site I have built. I was provided with the password in MD5 hash form. I suspect if I insert this into the password field in the database, since it is MD5 it will still match their password when the user tries to login on the new system. Is this a correct assumption? I also have a large amount of metadata for each user that needs to be inserted. Because I want to insert the md5 string, and not the password text and the extra custom meta fields, I don't think I can use wp_insert_user. Does anybody have experience with this type of thing? I am thinking I will just do something directly in mysql, rather than hack up a WP plugin, any suggestions would be appreciated though.
WordPress used MD5 for password hash in the past, but had since moved on to more secure phpass. The good thing is that it retains backwards compatibility - if user had old MD5 hash then it will be checked as such and automatically re-hashed and re-saved using current algorithm, see <code> wp_check_password() </code> . You are correct that you cannot use <code> wp_insert_user() </code> because it expect plain text password.
importing users where password is provided as md5 + much metadata
wordpress
i have a site ( http://fashionlog.com.br ) with a custom post type 'fotolog' as you can see on the right side. The posts and pagination of the blog (central column) work fine. But when it comes to the posts and pagination of my CPT it goes wrong. If i dont use the flush_rewrite_rules( false ); function after my register_post_type() call in functions.php, i can see the posts but the pagination doesnt work. If a use the function it's the oposite, i can't see the posts (404) but i get the pagination! I've been trying lots of times to switch the permalinks structure for tests, i checked my .htaccess file and its permissions, i tryed to "play" with the 'rewrite' parameter of the register_post_type() function, i've read and tryed the solution written stackexchange-url ("here"), here and also here ... So far no luck, or am i missing something super obvious? I'd really be grateful for some help.
Make sure your query has paged in it like so: <code> query_posts('post_type=fotolog' . '&amp;paged=' . get_query_var('paged')); </code> Check to be sure that you don't have page and a post type with the same permalink /foflog and /fotolog/your-post-name-here
Custom post type, permalinks & pagination, going wrong
wordpress
Ok so i have a custom post type called 'profile' with a custom taxonomy called 'company'. The site has many profiles and companies defined, with profiles being associated with companies as necessary. I have created a taxonomy-company.php template and have the correct profiles being displayed, but i don't know how to get the name of the company being displayed so that i can put it at the top of the template. Is there a quick way, perhaps a variable or function call that gets me that? Thanks.
<code> $wp_query-&gt;get_queried_object() </code> will give you the taxonomy term you're currently displaying. It works in many other situations too, like categories, authors, ...
Custom Post Type, Custom Taxonomy Template: How to get current taxonomy name?
wordpress