question
stringlengths
0
34.8k
answer
stringlengths
0
28.3k
title
stringlengths
7
150
forum_tag
stringclasses
12 values
Edit: Found that the theme options panel set up (using a class) was causing the problem. Still not sure why - would still love know how to find out what the problem is - e.g. is it a JS or PHP issue. Going to try a different method of creating the theme options panel to see if it fixes the problem. I am able to add extra TinyMCE buttons that are bundled (e.g. HR, anchor), but am unable to add custom plugins of my own. I have also noticed that other plugins (WP-Table Reloaded, cForms, TinyMCE Advanced) are also unable to load custom plugins. Disabling all other plugins does not solve the issue. What could be causing this, and/or how can I find the problem? When viewing source of an edit post screen, mceInit options do not list any plugins besides those defined as WP default. Altering the $initArray does work, but of course does not point to the correct location of added plugins.
You should read this: http://codex.wordpress.org/TinyMCE_Custom_Buttons It's pretty straightforward if you already know how to program a TinyMCE plugin (which it sounds like you do).
How can I troubleshoot why TinyMCE won't load custom plugins in the visual editor?
wordpress
I have been working on using featured image to create a list of items on the right column here: http://www.julianamaeberger.com/soma/news/ The current featured image is now being given a class of "highlighted" so that you can tell which image is related to the post. I now need to move that li class="highlighted" to the top of the list so that it's always visible. Is jquery sortable the best option here? Thanks for any help in the right direction.
Can't you do this in HTML? So instead of printing everything in your loop, append it to a string that you print in the end. That way you can keep special stuff apart. I assume this is a follow-up question to your previous question about featured images, so I will use stackexchange-url ("the code from my answer there") as an example. <code> &lt;?php $testimonials = get_posts( array( 'category_name' =&gt; 'testimonial', 'numberposts' =&gt; -1, 'order' =&gt; 'DESC' ) ); $highlighted_testimonial_thumbnail = ''; $other_testimonial_thumbnails = ''; foreach ( $testimonials as $testimonial ) { if ( $testimonial-&gt;ID == $current_testimonial_id ) { $highlighted_testimonial_thumbnail = '&lt;li class="highlighted"&gt;' . get_the_post_thumbnail( $testimonial-&gt;ID, 'nav' ) . '&lt;/li&gt;'; } else { $other_testimonial_thumbnails .= '&lt;li&gt;' . get_the_post_thumbnail( $testimonial-&gt;ID, 'nav' ) . '&lt;/li&gt;'; } } echo '&lt;ul class="portfolio"&gt;'; echo $highlighted_testimonial_thumbnail; echo $other_testimonial_thumbnails; echo '&lt;/ul&gt;'; </code> Or more generic: instead of: <code> foreach ( $array_of_stuff as $stuff ) { echo $stuff } </code> Do it like this: <code> $output = ''; $featured_output = ''; foreach ( $array_of_stuff as $stuff ) { if ( is_featured( $stuff ) ) { $featured_output = $stuff; } else { $output .= $stuff; } } echo $featured_output; echo $output; </code> Almost all functions in WordPress that echo something have an equivalent that doesn't echo but just returns it. <code> get_the_content() </code> vs <code> the_content() </code> for example.
How to move featured image to the top of the list?
wordpress
I am registering sidebars automatically for each category (a separate widget space per category). The technique I'm using is here . In the admin side I have an options page where I need to display a dropdown of all registered sidebars... Is there are way to dynamically get this list of registered sidebars? since they're being registered in functions.php I assume they're in memory, not in the database. I could keep track of the sidebars I register in some global variable, but just in case plugins register their own sidebars, I'd like to account for them too. I'll dig through the core if I have to, but thought someone might know off-hand:) Thanks
Hmm... I'm not sure if this is the best way to do it but it's simple: I looked in register_sidebar() and found that new sidebars are simply tacked onto an array: $wp_registered_sidebars And I guess that's that. If they ever change the name of the variable, I guess I'd be screwed.
Get list of all registered sidebars
wordpress
So I have a custom type called "vendors" and two custom taxonomies for it. One is "state" and the other is "type". I am trying to list all the vendors from a certain state on one page. I'm using the file called "taxonomy-state.php" which works perfectly. It displays all the vendors in the state. Now what I want to do is specify the types of vendors in order. So the page will look something like this: Vendors in "STATE": Vendor Type #1: Vendor #1 Vendor #2 Vendor #3 Vendor Type #2: Vendor #1 Vendor #2 Vendor #3 I got it to display vendors by state. But I need to display them in the above layout. I have an idea of how to do it. But I need to be able to make a query that can get a vendor from a certain state and certain vendor type. Thanks in advanced, Alain
Hopefully someone else will flesh out this answer, I don't have the time to write out a full solution right now... If you're using WordPress 3.1, look at the <code> tax_query </code> parameter that you can pass to <code> query_posts </code> . It can handle multiple taxonomies and relationships between them. Otto's post WordPress 3.1: Advanced Taxonomy Queries is the best explanation I've seen of what tax queries can do, and how to use them... In older versions of WP, you're stuck using a plugin like this one , or rolling your own fairly complex SQL queries.
Query posts with double taxonomy
wordpress
Is there a way to use regular categories with custom post types? It seems like there is better functionality and options with regular categories (such as permalink options, etc.).
No problem, the categories and tags are also registered as taxonomies that you can pass to the <code> taxonomies </code> argument when you call <code> register_post_type() </code> . Categories are <code> category </code> and tags are <code> post_tag </code> . You can also do this later with <code> register_taxonomy_for_object_type() </code> : <code> add_action( 'init', 'wpse6098_init', 100 ); // 100 so the post type has been registered function wpse6098_init() { register_taxonomy_for_object_type( 'category', 'your_custom_post_type' ); } </code>
Is there a way to use regular categories with custom post types?
wordpress
If I'm using a custom post type for a Movie or a TV show episode, I may use a taxonomy for "actors" and assign all the actors related to the work to it, but I'm not sure how, besides of that, I can also add the character the actor is playing in said work . The characters themselves may or may be not a taxonomy, as sometimes one also needs extra space for adding notes, like "John Doe (voice)" or "John Smith (via stock footage). I can figure something like a metabox with columns for each thing, yet I'm not sure how to make it harmonious (or do it at all).
You could simply use the "pods"-plugin (for WordPress) from Matt Gibs and Scott Kingsley Clark. It's exactly what you searching for. Take a look at the doku and look specificaly at "pick columns". Aside from that it has a nice and ajax driven interface and builds it's database tables next to wordpress and doesn't make use of the default tables (there's nothing wrong with adding new tables). It really converts Wordpress to a full CMS system. I tried it in some projects and was easily able to achieve everything i wanted. A big plus is the irc-chat where you find a nice, friendly and helpful croud and the developers. An here goes another plus: When you feel comfortable with pods, then add pods UI to your weaponary. :) Wish you best!
Add additional data to a specific taxonomy term when used in a post
wordpress
<code> &lt;?php $recent = new WP_Query(); ?&gt; &lt;?php $recent-&gt;query('cat=1&amp;showposts=2'); ?&gt; </code> With what can i replace cat=1 to show posts from all the categories?
You should be able to remove that category from the query so you would have <code> &lt;?php $recent-&gt;query('showposts=2'); ?&gt; </code> you can also take a look at completely custom queries here . `
How can i show all categories using wp query?
wordpress
For a project I'm working on, I want to change the labels of the 'Nickname' and 'Biographical Info' fields on edit profile (user-edit.php) page in the dashboard. I still want to use those fields as they are, I only want to change the labels. Anyone know of a function that can do this?
Every string goes through <code> translate() </code> , which uses the <code> gettext </code> filter. This mean you can try something like this: <code> add_filter( 'gettext', 'wpse6096_gettext', 10, 2 ); function wpse6096_gettext( $translation, $original ) { if ( 'Nickname' == $original ) { return 'Funny name'; } if ( 'Biographical Info' == $original ) { return 'Resume'; } return $translation; } </code> It's probably even more efficient if you only call the <code> add_filter </code> when you are on the <code> user-edit.php </code> page (see the <code> admin_head-user-edit.php </code> hook or something like that).
Change labels on 'Nickname' and 'Biographical Info' in user-edit.php
wordpress
Basically, I'd like to create a category permalink like example.com/books/adventure without having to make adventure a child-category because it will apply to other categories as well. So the end result is: example.com/books/adventure example.com/movies/adventure example.com/toys/adventure The order is based on the two parent categories, with "items" going first, and "genre" going second. And you could also search the categories separately to see all of the books, or all of the adventure items. How can I do this? Thanks!
David, welcome to wordpress answers. The answer is: Switch to some other platform. Wordpress can not with what's currently in core produce such a result easily. Technically spoken it's possible, but folks hate me here to say how (well Apache + PHP) in concrete, so I don't tell it because I fear the negative karma this give on this site. Just switch to something else if you seriously want to do such stuff and more. Like symfony2 with a database layer. After about one to three month as a single developer you can achieve much more then you can imagine with wordpress. And the best thing is: You can even add a wordpress blog later on. ;)
How can I create a permalink with two categories, with the order based on the parent category?
wordpress
is it possible to bring custom taxonomies to permalink? currently my permalink is looking something like this <code> /%postname%/%category% </code> but i also want to add custom taxonomies to my permalink so it should look something like this <code> /%postname%/%category%/%location%/%mba_courses% </code> is this possible? the solution to this answer i found, i googled and i found this code, which works perfetc for me <code> add_filter('post_link', 'mba_courses_permalink', 10, 3); add_filter('post_type_link', 'mba_courses_permalink', 10, 3); function mba_courses_permalink($permalink, $post_id, $leavename) { if (strpos($permalink, '%mba_courses%') === FALSE) return $permalink; // Get post $post = get_post($post_id); if (!$post) return $permalink; // Get taxonomy terms $terms = wp_get_object_terms($post-&gt;ID, 'mba_courses'); if (!is_wp_error($terms) &amp;&amp; !empty($terms) &amp;&amp; is_object($terms[0])) $taxonomy_slug = $terms[0]-&gt;slug; else $taxonomy_slug = 'mba_courses'; return str_replace('%mba_courses%', $taxonomy_slug, $permalink); } </code> but now i have one more problem, when i google my website i get the old url structure link, when i click on that i get 404 error, where as the post is still inside the website, just the url has changed, so how can i make the old url to direct it to new url i mean if clicking on the old url and instead of redirecting to 404 page, can it redirect to the actual post where i have the new url? is this possible?
What you're looking for is a 301 redirect. I use two plugins to catch do this. One notify's me of 404 errors ( http://wordpress.org/extend/plugins/404-notifier/ ) and the other makes writing the 301 redirects easy ( http://wordpress.org/extend/plugins/simple-301-redirects/ ). You could also write the 301 redirects in your .htaccess file and dig through the server logs to find the 404 notices. Long term you just need to wait for Google to crawl the site and find the new link structure. If other people are linking to your site from other blogs you can try and get them to fix their links but it's unlikely that you'll be able to get many people to do that.
custom taxonomies on permalink
wordpress
I am new to WordPress, and I need to make some quick changes. How can I find the Page that is referenced by a permalink: e.g. for www.example.com/mypermalink how can I locate the actual WP Page so I can find it either in the file system or in the WP Pages list?
Addressing both your original question and the question implied by your comment ... Finding the page ID Every post and page within WordPress is given an ID. By default, WordPress uses the ID in the link structure: http://www.example.com/?page=ID or http://www.example.com/?p=ID (for posts). You can change this to a more user-friendly structure called "pretty permalinks" that will use the page slug in the URL instead: http://www.example.com/my-page-slug. In practice, though, these permalinks can become very long. This is bad for certain situations (i.e. posting to Twitter), so WordPress retains the shorter ID-based URLs as "shortlinks." You can figure out the shortlink for a particular post or page by navigating to that page, right-clicking, and selecting "view source." Then look through the source for a specific section of meta tags: <code> &lt;meta name="generator" content="WordPress 3.0.3" /&gt; &lt;link rel='shortlink' href='http://example.com/?p=2' /&gt; </code> This "shortlink" tag tells you that you're looking for post #2. Finding the page in WordPress admin You've already discovered the easiest way to find a post or page - just search for the page slug when you're in the admin. This will find it almost every time, or at least give you a small list of possibilities. Another way is to use the ID you discovered above to jump straight to the post/page edit screen. Every post or page edit screen uses the following URL structure: http://example.com/wp-admin/post.php?post= ID &amp;action=edit Just substitute the ID you discovered above for ID in the URL and you'll be taken to the post/page edit screen for that content. Template Files Page templates are defined by your theme. They'll all be located somewhere in the <code> /wp-content/themes/YOUR-THEME/ </code> folder. The name of the page template (which you saw on the post edit screen) might give you a hint as to which file you're looking for, but I can't guarantee it. Just know that all page template files will begin with the following code: <code> &lt;?php /* Template Name: PAGE TEMPLATE NAME */ ?&gt; </code> So if you have more than one template file defined by your theme, looking for this tag will help you identify the specific one you'll need to edit. This template will define the HTML and PHP code used by pages that specifically call out that particular template.
How can I reverse engineer a Permalink to Find the Page?
wordpress
I'm having a bit of a brain fart on this one. I'm working on some code that resembles a custom search form. The custom search form, is a mixture of checkboxes as well as some drop downs. All of the fields which are being searched for are also custom fields. The custom fields were entered through a custom write panel. Some of the fields are single values others are serialized fields. The current code works, but i'm not sure if should be taking another approach, i'm not looking for anyone to write code for me. I'm just looking for some ideas on how this could be better. <code> $city = $_REQUEST['sCity']; $activity = $_REQUEST['sActivity'][0]; $riverSegment = $_REQUEST['sRiverSegment']; $topicOfInterest = $_REQUEST['sTopicOfInterest'][0]; $querystr = " SELECT DISTINCT wp_posts.* FROM wp_posts, wp_postmeta WHERE ( wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'city' AND wp_postmeta.meta_value = '$city' ) OR ( wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'riverSegment' AND wp_postmeta.meta_value = '$riverSegment' ) OR ( wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'topicOfInterest' AND wp_postmeta.meta_value LIKE '%$topicOfInterest%' ) OR ( wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'activity' AND wp_postmeta.meta_value LIKE '%$activity%' ) AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'sites' ORDER BY wp_posts.post_date DESC"; </code> I feel like the above sample is flawed because if the first condition finds a match it will ignore the rest of the conditions. Side Note: If i'm working with $wpdb-> get_results(); should i still be escaping the user input to keep it clean?
This doesn't seem especially complex, but does seem bulky and prone to errors. As I answered couple of times on similar issues - if this isn't time critical then wait for WP 3.1 because it will have major improvements for querying by custom fields. See Advanced Metadata Queries for brief writeup on upcoming improvements. For sanitizing queries see <code> $wpdb-&gt;prepare() </code> method - Protect Queries Against SQL Injection Attacks .
Custom Search, MySql Query Gone Wrong?
wordpress
I'm currently working on a website that has a static frontpage and couple of pages that is going to contain portfolio and things alike on the other pages. The thing I want to do is to hardcode content on the frontpage in css and xhtml. Is this possible and where do I do this? I thought it should be done in index.php in between: <code> "&lt;?php get_header(); ?&gt;" and "&lt;?php get_footer(); ?&gt;" </code> calling the content with if and else statement on: is_front_page()
I would set up a new page template (see http://codex.wordpress.org/Pages#Creating_Your_Own_Page_Templates ), create a new page (Pages > New) and set it to use that template, and then set WordPress to use that page as the homepage (Settings > Reading). Then you can fill the custom page template with whatever content you want in between wp_head() and wp_footer().
how to setup content on a static frontpage with css and xhtml
wordpress
I made a custom post type and a custom taxonomy, but I have a problem. When I access the url <code> http://www.ithemes.co.kr/?shopcat=galaxy-s </code> , it works well. But when I access the url <code> http://www.ithemes.co.kr/?shopcat=5 </code> , it returns a 404 page. <code> galaxy-s </code> is the taxonomy term slug, but I want to access it by <code> term_id </code> , like you can with a category: <code> cat=1 </code> . I prefer <code> cat=1 </code> . What can I do?
This is not supported by default, but you can convert the numeric terms back to slugs with the <code> pre_get_posts </code> hook. I tested this with WP 3.0.1, but in 3.1 the taxonomy query handling changed, so I don't know whether this will work by default or if there is a better way to do it. <code> add_action( 'pre_get_posts', 'wpse6066_pre_get_posts' ); function wpse6066_pre_get_posts( &amp;$wp_query ) { if ( $wp_query-&gt;is_tax ) { if ( is_numeric( $wp_query-&gt;get( 'term' ) ) ) { // Convert numberic terms to term slugs $term = get_term_by( 'term_id', $wp_query-&gt;get( 'term' ), $wp_query-&gt;get( 'taxonomy' ) ); if ( $term ) { $wp_query-&gt;set( 'term', $term-&gt;slug ); } } } } </code> Bizarre that you prefer the numeric version, many would choose the term slug for SEO reasons.
Query custom taxonomy by term id?
wordpress
I'll try to make this as clear as possible. I'm am trying to figure out a few things to clean up the permalinks on a large website project. We're using custom post types and ~200+ custom categories (we chose this because you can really add a lot of custom field spaces and data easily with the new custom post types). We need our permalinks to look like this: example.com/books/adventure/post-name where "books" and "adventure" are both categories, but we would prefer "books" came first. We would create adventure as a sub-category of books, but we use this same category for adventure movies, adventure games, etc. So a large site with books, movies, games, etc. where a person first chooses one of those categories and then drills down deeper to adventure, romance, kids, etc. Right now, we have: example.com/main-category/books example.com/sub-category/adventure example.com/product/post-name Basically I need to: Remove the slugs from the custom type categories (i.e. main-category &amp; sub-category) Make the "sub-category" appear after the "main-category" for the permalinks for sub-category pages. Create a new dynamic base category for the custom posts, which reflects the categories it's in (/books/adventures/post-name). Do this as simply and clean as possible, without a lot of plugins or things that may cause trouble down the line. OR...if you have a much better way to do this, I'm open to any suggestions. I know that we can use a Wordpress Network install instead of main-categories, but with 50-100+ of them, that is not feasible for us.
There is no such thing as a "dual category permalink" in wordpress, so you might be looking for custom rewrite rules (Wordpress.org Forums) and let deal your own code with the URL design as you need it then.
Remove slug from Custom Category Permalink + dual-category permalinks
wordpress
I am starting a new wordpress blog, and no longer updating an old one. The old one still gets 400-500 hits a day, so I would like to keep it up for archival purposes, as people still link to its posts. Obviously there is the problem that wordpress and plugins will be updated, and I have no desire to maintain it. How can I lock the installation of wordpress down so I don't need to maintain it? I have seen someone suggest making a static version, which sounds like alot of work. A more reasonable solution I thought of was to disable write access to the database at the database user level. I'm fine with disabling comments from now on. Feel free to share any thoughts or comments on this. Thanks in advance.
With a dynamic CMS like WordPress, there is no real way to "lock it down." As the web evolves, formerly unknown security holes are discovered and patched in new versions. In reality, unless you're always running the latest version of WordPress (currently 3.0.4), your site is in some way vulnerable. If you don't intend to ever update it again, creating a static version is the best and safest option - not "crazy talk. A strong possibility is to use a caching plug-in and set the cache to never expire. The plug-in will automatically create static versions of your pages as they're needed. Your links will still work, and people will be directed to the static HTML versions of each post and page rather than the dynamic, database generated ones. By generating a static version, you won't need to worry about database updates, WordPress updates, plug-in upgrades, or new versions of themes. It becomes maintenance-free, but is also "frozen" in the sense that comments won't work and you can't add new content ... which is probably fine in this case. Another alternative is to keep things dynamic and outsource the task of updating your site. Have someone like WordPress.com host the site and point all of your links to that version of the site. The hosted service (particularly that one) will always have the latest security patches without any intervention from you.
How can I lock down an old wordpress install I don't intend to update?
wordpress
I want to write a simple plugin. For every time a page is viewed, it will write to the MySQL database. Then, if the current hour is odd, it will set a PHP variable of $is_odd to true; <code> &lt;?php require_once('library-of-functions-to-support-this-plugin.php'); function_to_write_to_mysql_db(); $is_odd = false; if(current_hour_odd()) { $is_odd=true; } $is_odd_json = json_encode($is_odd); ?&gt; </code> Then, it should embed the following JavaScript (note: I've already modified the theme's templates to put an on each page): <code> &lt;script type="text/javascript" src="jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; var odd = &lt;?php echo $is_odd_json; ?&gt;; if(odd) { $("#OddElement").html('Odd!'); } &lt;/script&gt; </code> So basically, I have no idea where to put these code snippets. What filters do I want to apply? I know this plugin seems stupid, but it's laying the groundwork for something else I want to do. Thanks so much!
You could attach the to wp_head action http://codex.wordpress.org/Plugin_API/Action_Reference/wp_head
What filters to call to modify the output of the entire page?
wordpress
I think there used to be an out-dated plugin to do this. Is there any way to do this easily with just a little code? We prefer not to rely on a plugin since that makes us dependent on the developer to keep it up-to-date. We only have two parent categories we would like to remove for all of their child-category permalinks: "items" and "genres" (so it could be tailored to just removing two category IDs) I see that there was a solution with the individual posts stackexchange-url ("here"), but I don't think this works with the category permalinks as well, does it ?
This code pretty much does the job for this question and another one about removing the /category/ base from the permalinks. Got it from a plugin that does this, and decided to just use the raw code. So the permalinks only have the lowest child-category listed. First, we had: example.com/category/items/books/ and now... example.com/books The RSS feeds, however, don't seem to work with this shorter url, and still require the long-form url. (Not sure if there's a fix for that.) Also, it doesn't change the post permalink. It's just the category permalink that changes. Paste the code below into your functions.php file. I'm using Wordpress 3.0+. <code> // Remove category base add_filter('category_link', 'no_category_parents',1000,2); function no_category_parents($catlink, $category_id) { $category = &amp;get_category( $category_id ); if ( is_wp_error( $category ) ) return $category; $category_nicename = $category-&gt;slug; $catlink = trailingslashit(get_option( 'home' )) . user_trailingslashit( $category_nicename, 'category' ); return $catlink; } // Add our custom category rewrite rules add_filter('category_rewrite_rules', 'no_category_parents_rewrite_rules'); function no_category_parents_rewrite_rules($category_rewrite) { //print_r($category_rewrite); // For Debugging $category_rewrite=array(); $categories=get_categories(array('hide_empty'=&gt;false)); foreach($categories as $category) { $category_nicename = $category-&gt;slug; $category_rewrite['('.$category_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&amp;feed=$matches[2]'; $category_rewrite['('.$category_nicename.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&amp;paged=$matches[2]'; $category_rewrite['('.$category_nicename.')/?$'] = 'index.php?category_name=$matches[1]'; } // Redirect support from Old Category Base global $wp_rewrite; $old_base = $wp_rewrite-&gt;get_category_permastruct(); $old_base = str_replace( '%category%', '(.+)', $old_base ); $old_base = trim($old_base, '/'); $category_rewrite[$old_base.'$'] = 'index.php?category_redirect=$matches[1]'; //print_r($category_rewrite); // For Debugging return $category_rewrite; } // Add 'category_redirect' query variable add_filter('query_vars', 'no_category_parents_query_vars'); function no_category_parents_query_vars($public_query_vars) { $public_query_vars[] = 'category_redirect'; return $public_query_vars; } // Redirect if 'category_redirect' is set add_filter('request', 'no_category_parents_request'); function no_category_parents_request($query_vars) { //print_r($query_vars); // For Debugging if(isset($query_vars['category_redirect'])) { $catlink = trailingslashit(get_option( 'home' )) . user_trailingslashit( $query_vars['category_redirect'], 'category' ); status_header(301); header("Location: $catlink"); exit(); } return $query_vars; } </code>
Remove parent category from permalink? Basically only have the child category?
wordpress
We've seen plugins to do this, and a lot of people with different code modifications. We really would like to achieve this the cleanest and simplest way possible, without worrying about out-dated plugins or causing problems with too many mods.
Not sure how clean or easy this is, but it seems to work. This code pretty much does the job for this question and another one about removing the parent category from the permalinks. Got it from a plugin that does this, and decided to just use the raw code. So the permalinks only have the lowest child-category listed. First, we had: example.com/category/items/books/ and now... example.com/books The RSS feeds, however, don't seem to work with this shorter url, and still require the long-form url. (Not sure if there's a fix for that.) Paste the code below into your functions.php file. I'm using Wordpress 3.0+. <code> // Remove category base add_filter('category_link', 'no_category_parents',1000,2); function no_category_parents($catlink, $category_id) { $category = &amp;get_category( $category_id ); if ( is_wp_error( $category ) ) return $category; $category_nicename = $category-&gt;slug; $catlink = trailingslashit(get_option( 'home' )) . user_trailingslashit( $category_nicename, 'category' ); return $catlink; } // Add our custom category rewrite rules add_filter('category_rewrite_rules', 'no_category_parents_rewrite_rules'); function no_category_parents_rewrite_rules($category_rewrite) { //print_r($category_rewrite); // For Debugging $category_rewrite=array(); $categories=get_categories(array('hide_empty'=&gt;false)); foreach($categories as $category) { $category_nicename = $category-&gt;slug; $category_rewrite['('.$category_nicename.')/(?:feed/)?(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&amp;feed=$matches[2]'; $category_rewrite['('.$category_nicename.')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&amp;paged=$matches[2]'; $category_rewrite['('.$category_nicename.')/?$'] = 'index.php?category_name=$matches[1]'; } // Redirect support from Old Category Base global $wp_rewrite; $old_base = $wp_rewrite-&gt;get_category_permastruct(); $old_base = str_replace( '%category%', '(.+)', $old_base ); $old_base = trim($old_base, '/'); $category_rewrite[$old_base.'$'] = 'index.php?category_redirect=$matches[1]'; //print_r($category_rewrite); // For Debugging return $category_rewrite; } // Add 'category_redirect' query variable add_filter('query_vars', 'no_category_parents_query_vars'); function no_category_parents_query_vars($public_query_vars) { $public_query_vars[] = 'category_redirect'; return $public_query_vars; } // Redirect if 'category_redirect' is set add_filter('request', 'no_category_parents_request'); function no_category_parents_request($query_vars) { //print_r($query_vars); // For Debugging if(isset($query_vars['category_redirect'])) { $catlink = trailingslashit(get_option( 'home' )) . user_trailingslashit( $query_vars['category_redirect'], 'category' ); status_header(301); header("Location: $catlink"); exit(); } return $query_vars; } </code>
Best and Cleanest way to remove /category/ from category permalinks?
wordpress
I have a few custom thumbnail sizes and obviously one of them is used in the set_post_thumbnail_size, what directly affects the interface in the admin area. What I'm looking to do is to intercept which admin page (for post-type) I'm in and set a different size in the above function, so basically I'd like to have that: <code> function setup_the_theme() { add_theme_support( 'post-thumbnails' ); if ($post_type == 'type_A'){ set_post_thumbnail_size( 298, 167, true ); //portrait } else { set_post_thumbnail_size( 192, 108, true ); //landscape } add_image_size( 'top_articles', 298, 167, true ); //portrait add_image_size( 'article_thumb', 203, 114, true ); //portrait add_image_size( 'featured_articles', 60, 200, true ); //landscape } add_action( 'after_setup_theme', 'setup_the_theme' ); </code> I suspect its too early in the cycle to know which post type i'm editing.
Simpler way to figure out the post type of the item (which you are editing) and uploading media to: <code> $type = get_post_type($_REQUEST['post_id']); </code> As has been noted, the media upload iframe that is shown in the lightbox overlay when you try to upload something doesn't indicate the parent post that new upload will be attached to. But the <code> $_REQUEST </code> is still active from the edit window, and still contains the post_id of the item you're editing - so just query the type for that id... You can use this technique in various hooks and filters - I've used the <code> intermediate_image_sizes </code> filter for image processing before, but not for this particular problem, but it should work there too...
change set_post_thumbnail_size according to post type admin page
wordpress
I am using a WordPress plugin called MyReview but I want some changes to it. That plugin has feature to review posts, where users will come and give star ratings to the post according to categories, but in that plugin a user can give star rating to a post to as many times as the user wants, which I dont want, what I want is a user can give star rating to a post just a single time, for that purpose I had words with the author of the plugin, and he suggested me something like this, Query the comments table for any comments by the same email ID, check if there are any attached ratings, if there are, don't accept the ratings. All these changes would go in myrp-save.php. If you know PHP and are comfortable working with phpMyAdmin to understand the database tables, it would not be difficult to do. <code> SELECT id FROM myrp_ratings as rat, wp_comments as com WHERE com.comment_ID=rat.comment_id AND com.comment_author_email='whatever@whatever.com' AND rat.value!='0' AND rat.value!='1' LIMIT 1 </code> How can I put this line in that plugin file which is <code> myrp-save.php </code> ? I think code should be inserted after this line or before this line: <code> $wpdb-&gt;query("INSERT INTO `" . $wpdb-&gt;myrp_ratings . "`(`ID`, `category_id`, `post_id`, `comment_id`, `value`, `outof`, `weighted`) VALUES('', '{$name}', '{$postID}', '-1', '{$value}', '{$outof}', '" . ($value/$outof) . "')"); </code> How can this be done? <code> &lt;?php function myrp_save_comment_fields($commentID) { global $wpdb; $fields = $wpdb-&gt;get_results("SELECT * FROM " .$wpdb-&gt;myrp_comment_fields." ORDER BY `order`"); $rq = get_option("myrp_comment_fields_required"); foreach($fields as $f) { $puniqid = str_replace(".", "_", $f-&gt;uniqid); if(!isset($_POST[$puniqid])) continue; $postdata = $_POST[$puniqid]; switch($f-&gt;type) { case "date": if(strlen($postdata) &gt; 2) { $date = strtotime($postdata); if($date &gt; strtotime($f-&gt;minimum)) { add_comment_meta($commentID, $f-&gt;uniqid, $date, true) or update_comment_meta($commentID, $f-&gt;uniqid, $date); } else { if($rq) { wp_die(__("Field {$f-&gt;name} is required and must be after {$f-&gt;minimum}!", "myrp") . " &lt;a href='javascript:history.back(1);'&gt;Click here to continue...&lt;/a&gt;"); } else { continue; } } } break; case "short": case "long": if(strlen($postdata) &gt; 0) { $text = ($postdata); if(strlen($text) &gt; intval($f-&gt;minimum) &amp;&amp; strlen($text) &lt; $f-&gt;maximum) { add_comment_meta($commentID, $f-&gt;uniqid, $text, true) or update_comment_meta($commentID, $f-&gt;uniqid, $text); } else { if($rq) { wp_die(__("Field {$f-&gt;name} is required and must be between {$f-&gt;minimum} and {$f-&gt;maximum} characters!", "myrp") . " &lt;a href='javascript:history.back(1);'&gt;Click here to continue...&lt;/a&gt;"); } else { continue; } } } break; case "number": if(strlen($postdata) &gt; 0) { $text = intval($postdata); if(($text) &gt; intval($f-&gt;minimum) &amp;&amp; strlen($text) &lt; $f-&gt;maximum) { add_comment_meta($commentID, $f-&gt;uniqid, $text, true) or update_comment_meta($commentID, $f-&gt;uniqid, $text); } else { if($rq) { wp_die(__("Field {$f-&gt;name} is required and must be between {$f-&gt;minimum} and {$f-&gt;maximum}!", "myrp") . " &lt;a href='javascript:history.back(1);'&gt;Click here to continue...&lt;/a&gt;"); } else { continue; } } } break; case "select": case "radio": case "check": if(strlen($postdata) &gt; 0) { add_comment_meta($commentID, $f-&gt;uniqid, $postdata, true) or update_comment_meta($commentID, $f-&gt;uniqid, $postdata); } break; } } } // myrp_require_rating_comment, myrp_require_all_rating_comment function myrp_save_ratings($commentID) { global $wpdb; global $myrp_type_outof; $post_id = $_POST['comment_post_ID']; $rating_categories = get_post_meta($post_id, "_myrp_rating_categories", true); if(is_array($rating_categories) &amp;&amp; count($rating_categories) &gt; 0) { $submit_count = 0; foreach($rating_categories as $rc) { $type = $wpdb-&gt;get_var("SELECT `type` FROM `" . $wpdb-&gt;myrp_categories . "` WHERE `ID`='{$rc}' LIMIT 1"); $outof = $myrp_type_outof[$type]; if(isset($_POST[$rc . "_input"]) &amp;&amp; $_POST[$rc."_input"] != "") { $submit_count++; $value = $_POST[$rc . "_input"]; if(!empty($value)) { if($value &lt; 1) $value = 1; if($value &gt; $outof) $value = $outof; $value = round($value*2)/2; } else { $value = 0; } $sql =&lt;&lt;&lt; SQL SELECT id FROM myrp_ratings AS rat, wp_comments AS com WHERE 1=1 AND com.comment_ID = rat.comment_id AND com.comment_author_email = '%s' AND rat.value != '0' AND rat.value != '1' LIMIT 1 SQL; $sql = $wpdb-&gt;prepare($sql,'whatever@whatever.com'); $id = $wpdb-&gt;get_var($sql); if (is_null($id)) { $wpdb-&gt;query("INSERT INTO `" . $wpdb-&gt;myrp_ratings . "`(`ID`, `category_id`, `post_id`, `comment_id`, `value`, `outof`, `weighted`) VALUES('', '{$name}', '{$postID}', '-1', '{$value}', '{$outof}', '" . ($value/$outof) . "')"); } } } if( ( get_post_meta($post_id, "_myrp_no_allow_comments_without_ratings", true) == 1 &amp;&amp; $submit_count == 0 ) || ( ( (get_option("myrp_require_rating_comment") == 1 &amp;&amp; $submit_count == 0) || (get_option("myrp_require_all_rating_comment") == 1 &amp;&amp; $submit_count != count($rating_categories)) ) &amp;&amp; ( get_post_meta($post_id, "_myrp_allow_comments_without_ratings", true) != 1 ) ) ) { //$wpdb-&gt;query("DELETE FROM `".$wpdb-&gt;myrp_ratings."` WHERE `comment_id`='{$commentID}' LIMIT {$submit_count}"); wp_delete_comment($commentID); // should clean up ratings on its own. wp_die(__("Ratings are required! Please select star ratings for this review.", "myrp") . " &lt;a href='javascript:history.back(1);'&gt;Click here to continue...&lt;/a&gt;"); } } if(get_post_meta($post_id, "_myrp_automatically_approve_comments", true) == 1) $wpdb-&gt;query("UPDATE `" . $wpdb-&gt;comments . "` SET `comment_approved`=1 WHERE comment_ID='{$commentID}' AND `comment_approved`=0"); wp_update_comment_count($post_id); do_action("myrp-savingratings"); update_option("myrp_notChanged",0); return true; } function myrp_save_post($postID) { global $wpdb; global $myrp_type_outof; myrp_save_hides($postID); if(isset($_POST['myrp_affiliate_link'])) { $affiliate_link = trim($_POST['myrp_affiliate_link']); if(!empty($affiliate_link)) { $link = parse_url($affiliate_link); $scheme = $link['scheme']; if($scheme == "") $affiliate_link = "http://" . $affiliate_link; } add_post_meta($postID, "_myrp_affiliate_link", $affiliate_link, true) or update_post_meta($postID, "_myrp_affiliate_link",$affiliate_link); } if(isset($_POST['myrp_icon_image'])) { $icon_image = $_POST['myrp_icon_image']; if(!empty($icon_image)) { $link = parse_url($icon_image); $scheme = $link['scheme']; if($scheme == "") $icon_image = "http://" . $icon_image; } add_post_meta($postID, "_myrp_icon_image",$icon_image, true) or update_post_meta($postID, "_myrp_icon_image", $icon_image); } $checked = array(); $rating_categories = array(); if(isset($_POST['myrp_save_categories_please'])) { if(count($_POST['myrp_checked_categories']) &gt; 0) { foreach($_POST['myrp_checked_categories'] as $cid) { if(@$_POST["myrp_value_" . $cid] != "") { $rating = (@$_POST["myrp_value_" . $cid]); } else { $rating = ""; } $checked[] = array($cid, $rating); $rating_categories[] = $cid; } } add_post_meta($postID, "_myrp_rating_categories", $rating_categories, true) or update_post_meta($postID, "_myrp_rating_categories", $rating_categories); if(count($rating_categories) &gt; 0) { update_option("myrp_previously_checked", $rating_categories); } else { update_option("myrp_previously_checked", array()); } $wpdb-&gt;query("DELETE FROM `" . $wpdb-&gt;myrp_ratings . "` WHERE `post_id`='{$postID}' AND `comment_id`='-1'"); foreach($checked as $rating) { $name = $rating[0]; $value = $rating[1]; $type = $wpdb-&gt;get_var("SELECT `type` FROM `" . $wpdb-&gt;myrp_categories . "` WHERE `ID`='{$name}' LIMIT 1"); $outof = $myrp_type_outof[$type]; if($outof == 1) { if($value == "Yes") $value = 1; if($value == "No") $value = 0; } if($outof == 40) { $value = myrp_translate_letter_to_number($value); } $value = floatval($value); $wpdb-&gt;query("INSERT INTO `" . $wpdb-&gt;myrp_ratings . "`(`ID`, `category_id`, `post_id`, `comment_id`, `value`, `outof`, `weighted`) VALUES('', '{$name}', '{$postID}', '-1', '{$value}', '{$outof}', '" . ($value/$outof) . "')"); } } update_option("myrp_notChanged",0); } function myrp_save_hides($postID) { if(isset($_POST['_myrp_hide_set'])) { add_post_meta($postID, "_myrp_hide_float_left", $_POST['_myrp_hide_float_left'], true) or update_post_meta($postID, "_myrp_hide_float_left",$_POST['_myrp_hide_float_left']); add_post_meta($postID, "_myrp_hide_float_right", $_POST['_myrp_hide_float_right'], true) or update_post_meta($postID, "_myrp_hide_float_right",$_POST['_myrp_hide_float_right']); add_post_meta($postID, "_myrp_disable_traffic_tracking", $_POST['_myrp_disable_traffic_tracking'], true) or update_post_meta($postID, "_myrp_disable_traffic_tracking",$_POST['_myrp_disable_traffic_tracking']); add_post_meta($postID, "_myrp_disable_advanced_excerpts", $_POST['_myrp_disable_advanced_excerpts'], true) or update_post_meta($postID, "_myrp_disable_advanced_excerpts",$_POST['_myrp_disable_advanced_excerpts']); add_post_meta($postID, "_myrp_hide_microformats", $_POST['_myrp_hide_microformats'], true) or update_post_meta($postID, "_myrp_hide_microformats",$_POST['_myrp_hide_microformats']); add_post_meta($postID, "_myrp_allow_comments_without_ratings", $_POST['_myrp_allow_comments_without_ratings'], true) or update_post_meta($postID, "_myrp_allow_comments_without_ratings",$_POST['_myrp_allow_comments_without_ratings']); add_post_meta($postID, "_myrp_automatically_approve_comments", $_POST['_myrp_automatically_approve_comments'], true) or update_post_meta($postID, "_myrp_automatically_approve_comments",$_POST['_myrp_automatically_approve_comments']); } } ?&gt; </code>
Hi @ntechi: I think this is what you are looking for: <code> $sql =&lt;&lt;&lt; SQL SELECT id FROM myrp_ratings AS rat, INNER JOIN wp_comments AS com ON com.comment_ID = rat.comment_id WHERE 1=1 AND com.comment_author_email = '%s' AND rat.value != '0' AND rat.value != '1' LIMIT 1 SQL; $sql = $wpdb-&gt;prepare($sql,'whatever@whatever.com'); $id = $wpdb-&gt;get_var($sql); if (is_null($id)) { $wpdb-&gt;query("INSERT INTO `" . $wpdb-&gt;myrp_ratings . "`(`ID`, `category_id`, `post_id`, `comment_id`, `value`, `outof`, `weighted`) VALUES('', '{$name}', '{$postID}', '-1', '{$value}', '{$outof}', '" . ($value/$outof) . "')"); } </code> Note how I formatted the SQL so you could actually read it? (though admittedly I didn't go to the effort with the <code> INSERT </code> .) Also, note how I used <code> $wpdb-&gt;prepare() </code> to ensure that no SQL injection attacks were used from invalid email addresses? (Your plugin developer unfortunately did not do the same.) Also be careful modifying plugins; if you do you need to change the version number to something huge like 999 to ensure you or another user doesn't accidentally overwrite your changes when the vendor updates their plugin. Best if possible to get them to incorporate your changes into the next release of their plugin.
MySql database help for a plugin
wordpress
Say I link to http://www.glumbo.com on one of my posts. I want wordpress to automatically change the anchor text of the link to glumbo.com's title. How can I do this?
Decided to entertain the idea. Adapted from my snippet that changes anchors to collapsed domain names. Little too verbose, but seems to work. <code> add_filter( 'the_content', 'anchors_to_page_titles' ); function anchors_to_page_titles( $content ) { preg_match_all( '/&lt;a.*?href="(.*?)".*?&gt;(.*?)&lt;\/a&gt;/', $content, $matches ); array_shift( $matches ); foreach( $matches[0] as $key =&gt; $url ) { $anchor = $matches[1][$key]; if( $url == $anchor ) { $transient_key = 'page_title_'.md5($url); $anchor = get_transient($transient_key); if( !$anchor ) { $response = wp_remote_request($url); $body = wp_remote_retrieve_body($response); $pattern = '/title&gt;(.*?)&lt;/'; $title = array(); preg_match( $pattern, $body, $title); if( !empty( $title ) ) { $title = $title[1]; $anchor = $title; set_transient( $transient_key, $anchor, 60*60*24 ); } else { $anchor = $url; set_transient( $transient_key, $anchor, 60*60 ); } } $content = str_replace( "&gt;{$url}&lt;/a&gt;", "&gt;{$anchor}&lt;/a&gt;", $content ); } } return $content; } </code> PS maybe it would make sense to modify post on save rather than filtering on display... Well, as per my comment I don't think page titles are good for this anyway.
Plugin to automatically change anchor text of urls to the destinations title?
wordpress
I only want a post to be viewable by the administrator and one user. (So I would have a post for each user) I am thinking of using the Members plugin and meta-data/custom fields to restrict the content. This would effectively make the post private to only those with access and any one else would not even see the post and if they get the url, they will be denied. So would using the Members plugin be the best choice or should I try a different method? and how?
I am not expert on users, simplest way as for me would be to store ID (or IDs) of user in custom field and check for it if user is not admin. Some example code (not tested): <code> if(current_user_can('administrator') || in_array(get_current_user_id(), get_post_meta(get_the_id(), 'allowed_users', true))) { the_content(); } else { echo 'Post restricted'; } </code>
Restrict post to user_id
wordpress
Somehow the WordPress editor doesn't have a button to insert a horizontal line ( <code> &lt;hr /&gt; </code> in html). Is there a plugin that adds this button? Or an easy way to add such a button myself?
There's an easy way. Open functions.php and add this code. It works for many html entities <code> // got this form http://www.sycha.com/wordpress-add-hr-button-tinymce-visual-editor function enable_more_buttons($buttons) { $buttons[] = 'hr'; /* Repeat with any other buttons you want to add, e.g. $buttons[] = 'fontselect'; $buttons[] = 'sup'; */ return $buttons; } add_filter("mce_buttons", "enable_more_buttons"); //add_filter("mce_buttons_2", "enable_more_buttons"); // add to second row //add_filter("mce_buttons_3", "enable_more_buttons"); // add to third row </code>
Get a button for in the Editor
wordpress
From what I can tell the widget API is pretty straight forward and simple, yet for some reason my update code isn't taking effect properly. When I press [save] from the backend all fields are blanked, and nothing is actually saved. When I drag my widget onto the sidebar region, an entry is created in the database for the widget. <code> 1846, 0, 'widget_email-signup', 'a:2:{i:2;a:0:{}s:12:"_multiwidget";i:1;}', 'yes' </code> When I input values and save, none are saved. I've intercepted both <code> $new_instance </code> and <code> $old_instance </code> during the call to my update method and wrote their outputs to a file, but found nothing in them. Full Code: http://pastebin.com/gtrfuciZ Update Method <code> function update( $new_instance, $old_instance ) { $instance = $old_instance; $instance['title'] = $new_instance['title']; $instance['script'] = $new_instance['script']; file_put_contents( '/wp_results.txt', print_r( $old_instance, true ) ); file_put_contents( '/wp_results.txt', print_r( $new_instance, true ), FILE_APPEND ); return $instance; } </code> wp_results.txt (data found within update method) <code> Array ( [title] =&gt; [script] =&gt; ) Array ( ) </code>
You're using <code> get_field_id() </code> for the name attribute of the form elements, but you should use <code> get_field_name() </code> . The field names are of the form <code> widget-{$id_base}[{$number}][{$field_name}] </code> , but id's can't use <code> [] </code> , so they are like <code> widget-{$id_base}-{$number}-{$field_name} </code> .
Widget Update Code Not Working
wordpress
As a proof of concept, I'd like to create a simple plugin that loads some content, say "hello world" just after the_content on the home page only. How can I do this from a plugin?
You mean a filter and a check for <code> is_home() </code> ? <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>
How can I add/append content to the_content on the home page via a plugin?
wordpress
The code below creates a plugin that appends the contents of $content to "the_content" on the hompage. It works fine when I set $content to a static value. However, I'm trying to set it to draw out the site's active categories as a list. However, nothing happens when I set $content to wp_list_categories() Ultimately, I want to hack into the wp_list_categories function and display the thumbnail image that's been assigned to the category (still have to enable the code to do that as well). This is the first evolution of the plugin and I'm just attempting to get it to list the categories and descriptions before I build in the thumbnail support. <code> &lt;?php /* Plugin Name: List Categories with Thumbnail Images */ add_filter( 'the_content', 'cb_category_listing' ); function cb_category_listing( $content ) { if ( is_home() ) { // $content .= '&lt;p&gt;Hello World!&lt;/p&gt;'; $cat_args['title_li'] = ''; $myContent = wp_list_categories(apply_filters('widget_categories_args', $cat_args)); $content .= $myContent; } return $content; } add_action( 'init','cb_category_listing'); </code>
Hi @Scott B: Your example doesn't work for me when I use <code> if (is_home()) </code> but does when I use <code> if (is_front_page()) </code> . Is there any chance that is the problem? Other than that it seems to work fine on my WordPress v3.0.3 install. Do you have other plugins that might be disabling the output of <code> wp_list_categories() </code> ? P.S. I'm assuming you are using <code> add_action( 'init','cb_category_listing'); </code> just for debugging and not as part of your plugin?
List categories with descriptions via plugin
wordpress
i recently found that a login url filter is available but i can't find a solution for the forgot password as well, for the login url i use this: <code> function custom_login_url($login_url) { return ''.get_option('siteurl'). '/login'; } add_filter('login_url','custom_login_url'); </code> is it possible to do the same for the forgot password? thanks a lot, Philip
Yes it's also possible for the password, by running a filter on <code> lostpassword_url </code> , which is basically the password equivalent of the login url.. Example Basically the same as before, just changed the function and hook names. <code> add_filter( 'lostpassword_url', 'custom_lostpass_url' ); function custom_lostpass_url( $lostpassword_url ) { return get_option('siteurl'). '/lostpass'; } </code>
Is it possible to use a forgot password url filter?
wordpress
I am trying to add a form where users can submit post from front-end. I am Following this tutorial: http:// wpshout.com/wordpress-submit-posts-from-frontend/ What I am doing is adding this code to one of my page-template. The form shows up alright but when I click on the submit button it gives me " Page not found error " Many of the commenter saying it is not working. Can anyone point me to the right direction? Is the code incomplete?has flaws? Am I doing something wrong? Thanks Towfiq I.
<code> &lt;?php $postTitle = $_POST['post_title']; $post = $_POST['post']; $submit = $_POST['submit']; if(isset($submit)){ global $user_ID; $new_post = array( 'post_title' =&gt; $postTitle, 'post_content' =&gt; $post, 'post_status' =&gt; 'publish', 'post_date' =&gt; date('Y-m-d H:i:s'), 'post_author' =&gt; $user_ID, 'post_type' =&gt; 'post', 'post_category' =&gt; array(0) ); wp_insert_post($new_post); } ?&gt; &lt;!DOCTYPE HTML SYSTEM&gt; &lt;html&gt; &lt;head&gt; &lt;meta content="text/html; charset=utf-8" http-equiv="Content-Type" /&gt; &lt;title&gt;Untitled Document&lt;/title&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="wrap"&gt; &lt;form action="" method="post"&gt; &lt;table border="1" width="200"&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="post_title"&gt;Post Title&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input name="post_title" type="text" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;label for="post"&gt;Post&lt;/label&gt;&lt;/td&gt; &lt;td&gt;&lt;input name="post" type="text" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;input name="submit" type="submit" value="submit" /&gt; &lt;/form&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code> I found this at Themeforest it's working fine, you can do a lot of things with this, you have to add some extra code to check if a user is logged in or whatever you want to do, In the other hand you have to search in the WordPress plugins repo to find out some great plugins, Search for "frontend" hope it helps
Front-End Post Submission
wordpress
I'm trying to create sub-posts like this: /post/info/ /post2/info/ Using wp_insert_post() and I have almost succeeded. I'm setting post_parent to the parent post ID and the post_type needs to be "attachment". But! The problem is that the post_name needs to be unique so the sub page needs to be info, info2 etc and that's not what I want. So when settings the post_name to the same I'm getting all sub pages on one page when visiting /post/info/ and /post2/info/. Anyone knows if it's possible to accomplish this?
Hi @jonasl: I asked a clarifying question but I'm going to go ahead and at least start to answer. The function in WordPress core that controls post slugs and adds numbers to them in order to force them to be unique is <code> wp_unique_post_slug() </code> . In WordPress 3.0.3 you can find it on line 2530 in <code> /wp-includes/post.php </code> . I've copied it in full below for your review. You'll note it says "Attachment slugs must be unique across all types" so if your children are <code> post_type='attachments' </code> then this is what is forcing them to be unique. In addition you'll note that the post types must have <code> 'hierarchical'=&gt;true </code> or it will force them to be unique across all posts. <code> function wp_unique_post_slug( $slug, $post_ID, $post_status, $post_type, $post_parent ) { if ( in_array( $post_status, array( 'draft', 'pending', 'auto-draft' ) ) ) return $slug; global $wpdb, $wp_rewrite; $feeds = $wp_rewrite-&gt;feeds; if ( ! is_array( $feeds ) ) $feeds = array(); $hierarchical_post_types = get_post_types( array('hierarchical' =&gt; true) ); if ( 'attachment' == $post_type ) { // Attachment slugs must be unique across all types. $check_sql = "SELECT post_name FROM $wpdb-&gt;posts WHERE post_name = %s AND ID != %d LIMIT 1"; $post_name_check = $wpdb-&gt;get_var( $wpdb-&gt;prepare( $check_sql, $slug, $post_ID ) ); if ( $post_name_check || in_array( $slug, $feeds ) ) { $suffix = 2; do { $alt_post_name = substr ($slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix"; $post_name_check = $wpdb-&gt;get_var( $wpdb-&gt;prepare($check_sql, $alt_post_name, $post_ID ) ); $suffix++; } while ( $post_name_check ); $slug = $alt_post_name; } } elseif ( in_array( $post_type, $hierarchical_post_types ) ) { // Page slugs must be unique within their own trees. Pages are in a separate // namespace than posts so page slugs are allowed to overlap post slugs. $check_sql = "SELECT post_name FROM $wpdb-&gt;posts WHERE post_name = %s AND post_type IN ( '" . implode( "', '", esc_sql( $hierarchical_post_types ) ) . "' ) AND ID != %d AND post_parent = %d LIMIT 1"; $post_name_check = $wpdb-&gt;get_var( $wpdb-&gt;prepare( $check_sql, $slug, $post_ID, $post_parent ) ); if ( $post_name_check || in_array( $slug, $feeds ) || preg_match( '@^(page)?\d+$@', $slug ) ) { $suffix = 2; do { $alt_post_name = substr( $slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix"; $post_name_check = $wpdb-&gt;get_var( $wpdb-&gt;prepare( $check_sql, $alt_post_name, $post_ID, $post_parent ) ); $suffix++; } while ( $post_name_check ); $slug = $alt_post_name; } } else { // Post slugs must be unique across all posts. $check_sql = "SELECT post_name FROM $wpdb-&gt;posts WHERE post_name = %s AND post_type = %s AND ID != %d LIMIT 1"; $post_name_check = $wpdb-&gt;get_var( $wpdb-&gt;prepare( $check_sql, $slug, $post_type, $post_ID ) ); if ( $post_name_check || in_array( $slug, $feeds ) ) { $suffix = 2; do { $alt_post_name = substr( $slug, 0, 200 - ( strlen( $suffix ) + 1 ) ) . "-$suffix"; $post_name_check = $wpdb-&gt;get_var( $wpdb-&gt;prepare( $check_sql, $alt_post_name, $post_type, $post_ID ) ); $suffix++; } while ( $post_name_check ); $slug = $alt_post_name; } } return $slug; } </code> If you are not using attachments as children (which I fear you are based on your question) then you can possibly just define the post type as being <code> 'hierarchical'=&gt;true </code> . If you can't do that I might be able to suggest a have to fake it during insert of the post but I can't promise doing so will not cause other posts in WordPress to break. If you are using attachments and need this maybe you can explain more what you are trying to accomplish so that maybe we can suggest an alternative.
Sub posts and non unique post_name
wordpress
wp_list_pages seems to print out menus ok, but is there a way to alter the functionality so that i can display the menu in two colors..? So, if the titles of 3 actual pages are: <code> Big Cinema * Monaco Theatre * San Franciso Sport * Berlin </code> (each page really has two titles, the asterisk used to separate them. another character could be used..... or is there a way of entering two titles?) When these are displayed you would get the two titles for each page displayed a little differently: Big Cinema Monaco Theatre San Franciso Sport Berlin (the italics above representing blue, the rest green) Is there a way to alter the wp_list_pages behaviour, or is there a better technique to do this?
Hi @cannyboy: Unless I misunderstand, I think what you need is to use <code> 'the_title' </code> filter. If you simplly enter "Title 1 * Title2" into your title field, this code I've written for this hook should wrap your Title2 in a <code> &lt;span class="title2"&gt; </code> which will allow you to style it with CSS. You can put the following code into your theme's <code> functions.php </code> file: <code> add_filter('the_title','yoursite_the_title'); function yoursite_the_title($title) { $titles = explode('*',$title); $title = trim($title[0]); if (isset($title[1])) $title .= ' * &lt;span class="title2"&gt;' . trim($title[1]) . '&lt;/span&gt;'; return $title; } </code> Of course this will wrap your second title everywhere so you might have some places it does it that you don't want it to do it which case you'll need to figure out how to tell the function not run for only those cases.
Two-tone menu items
wordpress
I have my wordpress blog in the root of my website (example.org) and would like to store uploaded files in a subdomain depending on type of file, for example I currently have static.example.org/images, static.example.org/video and static.example.org/audio and was trying to find a way to put uploaded files in the subdomain through the Wordpress Interface. I've found a plugin which is quite dynamic in storing files, but it won't pass to subdomians, can anybody help or suggest anything?
Try changing the upload path by referring to following tutorial, then use the plugin again. http://7php.com/how-to-change-the-path-of-uploading-file-in-wordpress-2-8-x-2-9-x-without-touching-the-code-configurations/
inserting uploads into subdomain
wordpress
I've been going round and round with this so I hope someone can help! I've setup about 10 websites, all on Wordpress, for friends. At the moment, each of these sites are on separate wordpress installs. What i'd like to do is get to the stage where I have 1 install that can accomodate the 10 sites, but each site can't see the details/users/themes etc. of the other sites. Here is what i've tried so far: WP-Hive - This appeared to have some potential however it only caters to a single administrator. As i've just done these sites for friends, I generally give them a login to get in and edit the page content/post blogs themselves. So I don't think this will work. Wordpress 3.0.3 Network - I set this up with 2 sites however I had trouble with the domains and redirects as well as the level of access users had to everything (ie. Users can see all of the themes and plugins available, even when they aren't relevant to them). The last thing i've found to try is this: http://striderweb.com/nerdaphernalia/features/virtual-multiblog/ Does anyone know what I am doing wrong or how I can get this to work?
Option 2 should work, I just wrote http://wp.leau.co/2010/12/24/moving-a-weblog-to-a-wp3-multisite-weblog-system-on-mediatemple/ themes: you should NOT network activate all themes, only activate them on a specific site via the site settings for a blog plugins: disable the setting in the network admin to display plugin etc.. How to enable a theme for a specific site To network-enable or to not network-enable, that's the question! 1 click on network admin 2 click on themes 3 . Add your themes and make sure it says “network Enable” (so do NOT network enable them) (since then they would be available for all sites) 4 . click on sites 5 Click on “edit” beneath the site you want to give access to a theme (or a plugin) 6 Click on the tab “Themes” and find the theme you want to activate, then press “enable” beneath that theme. 7 You are done, the theme is now available for that blog.
Multiple sites with independent users
wordpress
I'm using the manage_users_columns to display a custom field I create in the usermeta database called company. My code is as follows: <code> function mysite_column_company( $defaults ) { $defaults['mysite-usercolumn-company'] = __('Company', 'user-column'); return $defaults; } function mysite_custom_column_company($value, $column_name, $id) { if( $column_name == 'mysite-usercolumn-company' ) { return get_usermeta($id, 'company'); } } add_action('manage_users_custom_column', 'mysite_custom_column_company', 15, 3); add_filter('manage_users_columns', 'mysite_column_company', 15, 1); </code> I'd like to get to display two other custom fields, but can't figure out the proper function. Duplicating this one doesn't work and I've not had any luck adding new functions within this one for each unique column, mostly because I can't seem to figure out how to properly define the $defaults variable. Any suggestions?
hummm... do you mean something like this : <code> function mysite_column_company( $defaults ) { $defaults['mysite-usercolumn-company'] = __('Company', 'user-column'); $defaults['mysite-usercolumn-otherfield1'] = __('Other field 1', 'user-column'); $defaults['mysite-usercolumn-otherfield2'] = __('Other field 2', 'user-column'); return $defaults; } function mysite_custom_column_company($value, $column_name, $id) { if( $column_name == 'mysite-usercolumn-company' ) { return get_the_author_meta( 'company', $id ); } elseif( $column_name == 'mysite-usercolumn-otherfield1' ) { return get_the_author_meta( 'otherfield1', $id ); } elseif( $column_name == 'mysite-usercolumn-otherfield2' ) { return get_the_author_meta( 'otherfield2', $id ); } } </code> by the way, you should use get_the_author_meta() instead of get_usermeta() as it is deprecated.
How to display multiple custom columns in the wp-admin users.php?
wordpress
I am building a mobile friendly plugin and put the theme directory inside the plugin directory. If it's a mobile browser, how can I redirect to the theme in the plugin directory? <code> /wp-content/plugins/mobview/theme/ </code> I've managed to use the following redirection: <code> wp_redirect( plugins_url('/mobview/theme/index.php') ); exit ; </code> But am kind of lost in the directory redirect inside WordPress structure.
Hi @Hamza: I think what you are looking to do is for your plugin to hook <code> 'template_include' </code> to tell it to load a file from your plugin directory. Here's starter code for your plugin: <code> &lt;?php /* Plugin Name: Mobile View Plugin */ if (is_mobile_user()) // YOU NEED TO DEFINE THIS FUNCTION class MobileViewPlugin { static function on_load() { add_filter('template_include',array(__CLASS__,'template_include')); } function template_include($template_file) { return dirname( __FILE__) . '/theme/index.php'; } } MobileViewPlugin::on_load(); } </code> Of course this will require that you somehow filter out when it is not a mobile user by defining the <code> is_mobile_user() </code> function (or similar) and it also means that your <code> /theme/index.php </code> will need to handle everything, included all URLs as you've basically bypassed the default URL routing by doing this (or your could inspect the values of <code> template_file </code> and reuse the logic by routing to equivalent files in your plugin directory.) Good luck. P.S. This does not provide a mobile solution for the admin. That would be 10x more involved.
Using a Theme inside a Plugin directory
wordpress
I'm building a Wordpress Plugin and it has two tables and some data. Right now, for displaying and changing the data, I'm using the wpdb function and manually creating the user interface (mimicking the Default one). However, I see that other plugins have a more consistent style with their tables and the same features (like the bulk button). I'm getting suspicious about Wordpress Taxonomies. I read, but so far, taxonomies seems to be related to posts in a way or the other. My data doesn't relate to posts, it's completely independent. Can I still use Wordpress Taxonomies? Can the taxonomy help me build a consistent interface?
check this out, I believe this might be what you're looking for. it helped me a lot.
Creating a custom Admin panel
wordpress
I've just moved to another theme, and it uses the custom field <code> bigimage </code> for associating an image with a post, instead of using WordPress's post thumbnails. How do I copy the URLs of all existing post-thumnails to their corresponding post's <code> bigimage </code> custom field? Could we possibly write a bunch of MySQL statements to achieve this?
I wouldn't bother doing that. I'd just find the places in your theme files that call the custom field (probably something like "echo get_post_meta('bigimage')" or something) and replace those with a the_post_thumbnail() tag. This saves you the trouble of messing with the data, and it makes administration much, much simpler going forward--which is kind of the point of post thumbnails. And it'll probably take less time than rigging some SQL to copy all that data.
Copying post thumbnail to custom field
wordpress
I really need a comprehensive solution to this, so I'm offering up almost a quarter of my rep in bounty :) I would like to have a plugin that creates a custom category listing on my home page. To do this, I'd like the "Category Edit" screen to be augmented with some additional functions as described below... Adds "Upload/Delete Image" handler to the Category Edit Screen for a Given Category (this allows the end user to upload an image that will be used to represent the category. Ideally, it should automatically be resized to 125 pixels wide by the plugin when uploaded. Adds "Category Title" input field to the Category Edit Screen for a Given Category. This is in addition to the existing default "Name" field. Adds a checkbox titled "Show on homepage listing" to allow selective display of each category on the home page listing. When the home page is viewed, the plugin appends the_content with the custom category listing, including each category's custom thumbnail and title. The resulting markup should be an unordered list with no nesting, like so... <code> &lt;ul class="custom-categories"&gt; &lt;li&gt; &lt;span&gt;&lt;a href="link-to-category-1"&gt;&lt;img src="the-category-1-image" /&gt;&lt;/a&gt;&lt;/span&gt; &lt;a href="link-to-category-1"&gt;Category 1 Title&lt;/a&gt; The category description text goes here &lt;/li&gt; &lt;li&gt; &lt;span&gt;&lt;a href="link-to-category-2"&gt;&lt;img src="the-category-2-image" /&gt;&lt;/a&gt;&lt;/span&gt; &lt;a href="link-to-category-2"&gt;Category 2 Title&lt;/a&gt; The category description text goes here &lt;/li&gt; etc... &lt;/ul&gt; </code> Here's a stub file I've started... <code> add_filter( 'the_content', 'cb_category_listing' ); function cb_category_listing( $content ) { if ( is_home() ) { $cat_args['title_li'] = ''; $cat_args['exclude_tree'] = 1; $cat_args['exclude'] = 1; $myContent = wp_list_categories(apply_filters('widget_categories_args', $cat_args)); $content .= $myContent; } return $content; } </code>
Here's how to add fields and save the values on the category edit screen as well as a method of adding an image upload field. Adding fields to category edit screen To start we need to get some code showing up on the category edit screen. <code> add_action( 'edit_category_form_fields', 'my_category_custom_fields' ); add_action( 'edit_category', 'save_my_category_custom_fields' ); function my_category_custom_fields( $tag ) { // your custom field HTML will go here // the $tag variable is a taxonomy term object with properties like $tag-&gt;name, $tag-&gt;term_id etc... // we need to know the values of our existing entries if any $category_meta = get_option( 'category_meta' ); ?&gt; &lt;tr class="form-field"&gt; &lt;th scope="row" valign="top"&gt;&lt;label for="category-title"&gt;&lt;?php _e("Title"); ?&gt;&lt;/label&gt;&lt;/th&gt; &lt;td&gt; &lt;input id="category-title" name="category_meta[&lt;?php echo $tag-&gt;term_id ?&gt;][title]" value="&lt;?php if ( isset( $category_meta[ $tag-&gt;term_id ] ) ) esc_attr_e( $category_meta[ $tag-&gt;term_id ]['title'] ); ?&gt;" /&gt; &lt;span class="description"&gt;&lt;?php _e('Enter an alternative title for this category.'); ?&gt;&lt;/span&gt; &lt;/td&gt; &lt;/tr&gt; &lt;!-- rinse &amp; repeat for other fields you need --&gt; &lt;?php } </code> The simplest way to store our custom values is in the options table (there should be a taxonomy-meta table really but never mind). This way we only need to make one query to get the meta data for all of our categories. If anyone has a better idea for storage then speak up! <code> function save_my_category_custom_fields() { if ( isset( $_POST['category_meta'] ) &amp;&amp; !update_option('category_meta', $_POST['category_meta']) ) add_option('category_meta', $_POST['category_meta']); } </code> For a checkbox you're simply storing true or false so you'd use <code> category_extras[$tag-&gt;term_id][show_on_home] </code> for the name attribute and use the value stored in <code> $category_meta </code> to determine if it's checked or not. You may want to add some extra processing or sanitisation to the save function - mine is just a quick n dirty example. The image field This is a fair bit of code and quite complicated so I won't explain it all here but the comments describe the purpose of each function. We can discuss in the comments if you want to. The following functions add a link to the category edit screen which brings up the wordpress media library/image upload popup. You can then upload a picture and click to use it. You'll then have the image ID and thumbnail url available to you with the other meta above. <code> // add the image size you need add_image_size( 'category_thumb', 125, 125, true ); // setup our image field and handling methods function setup_category_image_handling() { // add the image field to the rest add_action( 'edit_category_form_fields', 'category_image' ); global $pagenow; if ( is_admin() ) { add_action( 'admin_init', 'fix_async_upload_image' ); if ( 'edit-tags.php' == $pagenow ) { add_thickbox(); add_action('admin_print_footer_scripts', 'category_image_send_script', 1000); } elseif ( 'media-upload.php' == $pagenow || 'async-upload.php' == $pagenow ) { add_filter( 'media_send_to_editor', 'category_image_send_to_editor', 1, 8 ); add_filter( 'gettext', 'category_image_replace_text_in_thickbox', 1, 3 ); } } } add_action( 'admin_init', 'setup_category_image_handling' ); // the taxonomy edit screen image field function category_image( $tag ) { // get our category meta data $category_meta = get_option('category_meta'); ?&gt; &lt;tr class="form-field hide-if-no-js"&gt; &lt;th scope="row" valign="top"&gt;&lt;label for="taxonomy-image"&gt;&lt;?php _e("Image"); ?&gt;&lt;/label&gt;&lt;/th&gt; &lt;td&gt; &lt;div id="taxonomy-image-holder"&gt; &lt;?php if( !empty($category_meta[$tag-&gt;term_id]['image']) ) { ?&gt; &lt;img style="max-width:100%;display:block;" src="&lt;?php echo esc_attr( $category_meta[ $tag-&gt;term_id ]['image']['thumb'] ); ?&gt;" alt="" /&gt; &lt;a id="taxonomy-image-select" class="thickbox" href="media-upload.php?is_term=true&amp;amp;type=image&amp;amp;TB_iframe=1"&gt;&lt;?php _e('Change image'); ?&gt;&lt;/a&gt; &lt;a class="deletion" id="taxonomy-image-remove" href="#remove-image"&gt;Remove image&lt;/a&gt; &lt;?php } else { ?&gt; &lt;a id="taxonomy-image-select" class="thickbox" href="media-upload.php?is_term=true&amp;amp;type=image&amp;amp;TB_iframe=1"&gt;&lt;?php _e('Choose an image'); ?&gt;&lt;/a&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;input type="hidden" name="category_meta[&lt;?php echo $tag-&gt;term_id ?&gt;][image][id]" value="&lt;?php if( isset($category_meta[ $tag-&gt;term_id ]['image']['id']) ) echo esc_attr($category_meta[ $tag-&gt;term_id ]['image']['id']); ?&gt;" class="tax-image-id" /&gt; &lt;input type="hidden" name="category_meta[&lt;?php echo $tag-&gt;term_id ?&gt;][image][thumb]" value="&lt;?php if( isset($category_meta[ $tag-&gt;term_id ]['image']['thumb']) ) echo esc_attr($category_meta[ $tag-&gt;term_id ]['image']['thumb']); ?&gt;" class="tax-image-thumb" /&gt; &lt;span class="description"&gt;&lt;?php _e('A category image.'); ?&gt;&lt;/span&gt;&lt;/td&gt; &lt;/tr&gt; &lt;?php } // required for uploading images on non post/page screens function fix_async_upload_image() { if(isset($_REQUEST['attachment_id'])) { $GLOBALS['post'] = get_post($_REQUEST['attachment_id']); } } // are we dealing with the taxonomy edit screen? function is_category_context() { if ( isset($_SERVER['HTTP_REFERER']) &amp;&amp; strpos($_SERVER['HTTP_REFERER'],'is_term') !== false ) { return true; } elseif ( isset($_REQUEST['_wp_http_referer']) &amp;&amp; strpos($_REQUEST['_wp_http_referer'],'is_term') !== false ) { return true; } elseif ( isset($_REQUEST['is_term']) &amp;&amp; $_REQUEST['is_term'] !== false ) { return true; } return false; } // replace Insert Into Post text with something more appropriate function category_image_replace_text_in_thickbox($translated_text, $source_text, $domain) { if ( is_category_context() ) { if ('Insert into Post' == $source_text) { return __('Use this image', MB_DOM ); } } return $translated_text; } // output a script that sets variables on the window object so that they can be accessed elsewhere function category_image_send_to_editor( $html, $id, $attachment ) { // context check might not be necessary, and, might not work in all cases if ( is_category_context() ) { $item = get_post($id); $src = wp_get_attachment_image_src($id,'thumbnail',true); // 0 = url, 1 = width, 2 = height, 3 = icon(bool) ?&gt; &lt;script type="text/javascript"&gt; // send image variables back to opener var win = window.dialogArguments || opener || parent || top; win.TI.id = &lt;?php echo $id ?&gt;; win.TI.thumb = '&lt;?php echo $src[0]; ?&gt;'; &lt;/script&gt; &lt;?php } return $html; } // write out the javascript that handles what happens when a user clicks to use an image function category_image_send_script() { ?&gt; &lt;script&gt; self.TI = {}; var tb_position; function send_to_editor(h) { // ignore content returned from media uploader and use variables passed to window instead jQuery('.tax-image-id').val( self.TI.id ); jQuery('.tax-image-thumb').val( self.TI.thumb ); // display image jQuery('#taxonomy-image-holder img, #taxonomy-image-remove').remove(); jQuery('#taxonomy-image-holder') .prepend('&lt;img style="max-width:100%;display:block;" src="'+ self.TI.thumb +'" alt="" /&gt;') .append('&lt;a class="deletion" id="taxonomy-image-remove" href="#remove-image"&gt;Remove image&lt;/a&gt;'); jQuery('#taxonomy-image-select').html('Change image'); // close thickbox tb_remove(); } (function($){ $(document).ready(function() { tb_position = function() { var tbWindow = $('#TB_window'), width = $(window).width(), H = $(window).height(), W = ( 720 &lt; width ) ? 720 : width; if ( tbWindow.size() ) { tbWindow.width( W - 50 ).height( H - 45 ); $('#TB_iframeContent').width( W - 50 ).height( H - 75 ); tbWindow.css({'margin-left': '-' + parseInt((( W - 50 ) / 2),10) + 'px'}); if ( typeof document.body.style.maxWidth != 'undefined' ) tbWindow.css({'top':'20px','margin-top':'0'}); }; return $('a.thickbox').each( function() { var href = $(this).attr('href'); if ( ! href ) return; href = href.replace(/&amp;width=[0-9]+/g, ''); href = href.replace(/&amp;height=[0-9]+/g, ''); $(this).attr( 'href', href + '&amp;width=' + ( W - 80 ) + '&amp;height=' + ( H - 85 ) ); }); }; $(window).resize(function(){ tb_position(); }); $('#taxonomy-image-select').click(function(event){ tb_show("Choose an image:", $(this).attr("href"), false); return false; }); $('#taxonomy-image-remove').live('click',function(event){ $('#taxonomy-image-select').html('Choose an image'); $('#taxonomy-image-holder img').remove(); $('input[class^="tax-image"]').val(""); $(this).remove(); return false; }); }); })(jQuery); &lt;/script&gt; &lt;?php } </code> Accessing the information In your <code> my_function </code> bit taken from your own answer you would then access the metadata like so: <code> function my_function(){ $args=array( 'orderby' =&gt; 'name', 'order' =&gt; 'ASC' ); $categories=get_categories($args); // get our category meta data and exit out if there isn't any $category_meta = get_option('category_meta'); if ( !$category_meta ) return; echo '&lt;ul style="list-style-type:none;margin:0;padding:0"&gt;'; foreach($categories as $category) { // skip unticked categories &amp; categories with no meta data if ( !isset( $category_meta[ $category-&gt;term_id ] ) || ( isset( $category_meta[ $category-&gt;term_id ] ) &amp;&amp; !$category_meta[ $category-&gt;term_id ]['show_on_home'] ) ) continue; echo '&lt;li&gt;&lt;a style="display:block;margin-top:20px;" href="' . get_category_link( $category-&gt;term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category-&gt;name ) . '" ' . '&gt;' . $category_meta[ $category-&gt;term_id ]['title'].'&lt;/a&gt;'; if ( "" != $category_meta[ $category-&gt;term_id ]['image']['id'] ) echo wp_get_attachment_image( $category_meta[ $category-&gt;term_id ]['image']['id'], 'category_thumbnail', false, array( 'alt' =&gt; $category-&gt;name, 'class' =&gt; '' ) ); echo $category-&gt;description . '&lt;/li&gt;'; } echo '&lt;/ul&gt;'; } </code>
Category listing with thumbnail and description on home page
wordpress
I am currently a CS student and an aspiring programmer/web developer. I am wondering whether it is worth taking the time to master html and css to make websites when CMS services/wysiwyg like wordpress and various others seem to be becoming more and more functional. Does anyone think these publishing services might eventually make the need to design websites from raw code unnecessary? If not, please explain why. If designing a website eventually becomes as simple as using Photoshop I would much rather invest my time in programming languages.
I think your question conflates design and development , though they're not even close to the same thing. Sites are rarely "designed from code"...they're designed in Photoshop by designers and translated into code by developers (of course, there are exceptions to this, but it's usually the case). But I'll assume you're just saying, "since WordPress does a lot of the work for me upfront, do I really need to know how it works?" Wordpress is a great framework to build on top of, but the system itself is made of "raw" css, php, html and JavaScript. If you don't understand all of these things (at least at a basic level), you'll never be able to develop your own themes and plugins, or even to customize existing ones. And in general, you won't be able to translate finished designs to functioning sites. Because WordPress is so full-featured right out of the box (and because awesome support communities like this exist!), a lot of non-professionals get by as "copy-and-pasters"; never really understanding the code, but able to hack their way through issues as they pop up. This is fine if you're running a single, personal website. But if you plan to develop WordPress sites for other people (ie. professionally), you cannot get by without a solid understanding of php, html, css and JavaScript. In fact, there's even MORE stuff you need to know. SQL, XML, JSON, AJAX, http protocol basics, apache configuration, SEO techniques, basic *nix commands, domain configuration...the list gets longer every day, not shorter. So in short--yes, you need to have at least a basic understanding of how all of that stuff works if you plan to make websites for a living. No WYSIWYG or RAD tool will (in the foreseeable future, anyway) come along to replace the expertise of professional web designers and developers.
raw code vs wordpress
wordpress
I know that there is a way to crosspost from WP to Blogger but I am curious if there is a way to essentially mirror WP blog on Blogger completely, in other words crosspost both posts and comments?
Hi @Alex: Your client wants to mirror on Blogger this "In case WordPress fails?!?" OMG!!!! Do they not understand how WordPress works? Set him up a second WordPress site on a different web host or on WordPress.com! Don't put up with Blogger. A simple solution would be to use Windows Live Writer or Qumana to write the posts and then just having them submit to both sites using those programs. A programming solution would be to monitor RSS feeds on a psuedo-cron task and then import them with <code> wp_insert_post() </code> : Import and Display RSS Feeds in WordPress Pseudo Cron Jobs with WordPress Function Reference/wp_insert_post But whatever you do get them to stick with WordPress on the multiple sites; doing anything else is madness!
Crossposting from WP to Blogger with comments
wordpress
I'm planing to create a plugin called Goodbye Dolly. Once installed, it will take care for the installation to remove the auto-installing Hello Dolly (Wordpress Plugin) shipping with wordpress. This is due to popular request. Some folks have asked for it. I like the idea. I never cared so far because I removed it manually. But I like the idea to save the hassles and have this removal automated for the future. I wanted to just delete the file when it exists basically. But I'm unsure a bit about file system abstraction. And I would like to do this on install / update already, so this does not needs to be checked for all the time. So which hooks are to be considered? Any best practice ideas? Update: Homepage: http://hakre.wordpress.com/plugins/goodbye-dolly/ Repository: http://wordpress.org/extend/plugins/goodbye-dolly/
While I appreciate the idea, isn't this just replacing one plugin with another? Rarst's link already has the answer -- it just needs to be reworked a bit to check for the plugin periodically, like so: <code> function goodbye_dolly() { if (file_exists(WP_PLUGIN_DIR.'/hello.php')) { require_once(ABSPATH.'wp-admin/includes/plugin.php'); require_once(ABSPATH.'wp-admin/includes/file.php'); delete_plugins(array('hello.php')); } } add_action('admin_init','goodbye_dolly'); </code> Slap that into your functions.php file (in a child theme if you aren't already using a custom theme) and you should be good to go.
How to delete the Hello Dolly plugin automatically?
wordpress
i asked this on SO but got no where. i will try asking here. this works fine in category.php <code> &lt;?php echo category_description(the_category_id()); ?&gt; </code> but it does not work in single.php, just the category id shows up not the description. any ideas, how to get this done? thanks in advance Edit: in category: <code> &lt;?php echo strip_tags(category_description(4)); ?&gt; </code> in single <code> &lt;?php echo category_description(the_category_id()); ?&gt; </code> cat id = 4 i know i'm not striping the tags..for single i'm just trying to display the cat desc when in the single post page.
Hi @andrewk - Try the code that follows the screenshot: <code> &lt;?php $categories = get_the_category(); foreach($categories as $key =&gt; $category) { $url = get_term_link((int)$category-&gt;term_id,'category'); $categories[$key] = "&lt;dt&gt;&lt;a href=\"{$url}\"&gt;{$category-&gt;name}&lt;/a&gt;&lt;/dt&gt;" . "&lt;dd&gt;{$category-&gt;category_description}&lt;/dd&gt;"; } echo "&lt;dl&gt;\n" . implode("\n",$categories) . "\n&lt;/dl&gt;"; ?&gt; </code> Also, <code> &lt;?php echo category_description(the_category_id()); ?&gt; </code> doesn't do what you think it does. What follows will work on your category pages because it assumes the category ID for the category page: <code> &lt;?php echo category_description(); ?&gt; </code> FYI, <code> the_category_id() </code> will echo the value of the current category ID, it doesn't actually pass anything to <code> category_description() </code> is looks like was your assumption. Besides, <code> the_category_ID() </code> is deprecated so you wouldn't want to use it anyway. By the way, I'll bet you are seeing an errant number being displayed just before the category description is displayed?
echo category description in single.php
wordpress
I'd like to add a page that does not appear anywhere on the site (especially not in the header or wherever your pages are listed) unless the URL is typed in directly. Additionally, the page/post should be password-protected. I know how to add a password, but I found no way to remove the page from being listed.
Hi @mafutrct: There are a lot of ways to do this; picking one is actually the challenge! I'm going to suggest a few options and let you explore (the ones at the top look most promising) : Page Protection Plugin Password Protect enhancement Plugin Better Protected Pages Simply Exclude Plugin ( Article ) Hide Pages Plugin Creating ‘hidden’ pages in wordpress which don’t appear in the navigation menu I'm assuming your are using <code> wp_list_pages() </code> for your menus? If so consider moving to the new menus in v3.0 where you'll get full control of what appears in those menus: Everything you wanted to know about WordPress 3.0 Menu Management
Is there a way to create invisible pages?
wordpress
I've been trying to figure out why we have the constants <code> BLOG_ID_CURRENT_SITE </code> and <code> SITE_ID_CURRENT_SITE </code> (vs. hardcoding them to be equal to <code> 1 </code> ) , what exactly the differences are, and when either of them will not equal 1? Any insight will be appreciated. Thanks in advance.
I addressed a similar question on StackOverflow stackexchange-url ("last month"). In MultiSite, "blog" is a reference to an individual website. "Site" is a reference to a network of "blogs." In the future, there's the likelihood that WordPress will be able to power multiple networks ("site"s) in addition to its current state of multiple "blog"s. Update I've done some more digging, and discovered a plug-in that easily allows you to split your multi-site installation into a multi-network one: WP Multi Network .
BLOG_ID_CURRENT_SITE vs. SITE_ID_CURRENT_SITE in WordPress Multisite?
wordpress
I'm following this to make my plugin auto-create a table when the plugin is activated, but what happens is that while all the tables (the whole db) are utf8_general_ci, the newly created table is latin1_swedish_ci... Why isn't it also utf8? I thought it would also be utf8 by default since I have: <code> define('DB_COLLATE', 'utf8_general_ci'); </code> in my wp-config.php... I have everything exactly the same like in the link provided, except the function name, and I have different SQL fields... How to make the newly created table utf8 by default? this is my function: <code> function duende_install() { global $wpdb; global $duende_db_version; $table_name = $wpdb-&gt;prefix . "duendes"; if($wpdb-&gt;get_var("show tables like '$table_name'") != $table_name) { $sql = "CREATE TABLE " . $table_name . " ( id mediumint(9) NOT NULL AUTO_INCREMENT, shape tinytext NOT NULL, integrity tinytext NOT NULL, length tinytext NOT NULL, drone tinytext NOT NULL, wood tinytext NOT NULL, mouth tinytext NOT NULL, rim tinytext NOT NULL, bell tinytext NOT NULL, loud tinytext NOT NULL, mass tinytext NOT NULL, finish tinytext NOT NULL, inlay tinytext NOT NULL, price smallint DEFAULT '0' NOT NULL, sold tinytext NOT NULL, UNIQUE KEY id (id) );"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); add_option("duende_db_version", $duende_db_version); } } </code> Thank you
You're missing the point that there is collation not only for the DB but as well for tables and even fields. Therefore from your point of view, I assume that your CREATE TABLE statement is "not complete". Before using SQL statements, please learn the language first. See <code> CREATE TABLE </code> Syntax (MySQL Manual) . Especially <code> table_options </code> / <code> table_option </code> and <code> [DEFAULT] COLLATE [=] collation_name </code> there in. UPDATE: Please see Wordpress Database Charset and Collation Configuration for an in-depth description where and how to setup wordpress regarding charset and collation.
Default table collation on plugin activation?
wordpress
how are you ? I have in my site (post_type called = books).. I need to make some users for example (Library) to create a books (post_type = books) .. this is the code to add rols (called = library) .. <code> $library = add_role('library', 'library', array( 'read' =&gt; true, 'edit_posts' =&gt; true, 'delete_posts' =&gt; false, )); </code> The library Role can create (any type of post) , I want it to create books (post_type) .. I wish you understand me .. thank you very much ^_^
You can add your own capabilities for custom post types. The default behvaiour for a post type is to inherit capabilities from the default post post-type. See the capabilities parameter in register_post_type (Wordpress Codex) , that has more information about how that can be done.
using add_role function to make some users to create a selected type post
wordpress
For example, I want to use add_menu_page() function to add a menu item to the dashboard. To control which users will be able to access it, I'm supposed to use capabilities... <code> &lt;?php add_menu_page( $page_title, $menu_title, $capability, $menu_slug, $function, $icon_url, $position ); ?&gt; </code> So, if I want to grant access to that menu page to - superadmin, admin, editor and author so that all users with one of these roles could access it, what am I supposed to put as $capability? I'm looking at this table and as far as I figure, I should put one of these four as $capability: edit_published_posts upload_files publish_posts delete_published_posts So if roles&amp;capabilities haven't been altered via some plugin, picking one of these four should grant access to all the four roles just like I want it? Is this the usual practise, or am I supposed to do it in some other way? Am I supposed to somehow add more than one capability into $capability, or is just one enough? If only one is enough, which one of these four would be the best choice, or it does not matter as long as roles are not altered to be different than default? thank you
In case someone needs a sollution - I just put <code> 'publish_posts' </code> as $capability parameter and it works as I thought it would - it gives you all the capabilitis that are below the one used (below publish_posts in my case)...
How to determine which capability to use?
wordpress
Say a theme "foo" is used on across a network of sites. In each site, all the theme resources ( <code> .css </code> , <code> .js </code> , etc.) will have distinct URLs: http://network/siteA/wp-content/themes/foo/style.css http://network/siteB/wp-content/themes/foo/style.css http://network/siteC/wp-content/themes/foo/style.css I want these to all be: http://network/wp-content/themes/foo/style.css What's the best way to do this? I can fix URLs directly output in the theme, but how do I normalize the URLs in enqueued scripts/stylesheets? Aside : What's the benefit of having expressions like <code> get_bloginfo('template_url') </code> create URLs that differ across sites?
Hi @mrclay: Good questions. WordPress Multisite is Many Independant Sites, not Many Dependant Sites To answer your aside, WordPress multisite was designed to be a collections of independent WordPress installs collected into one where each site is likely to be very different, unlike your use-case. So each site has it's own theme and WordPress wants those themes to work on both single site installs and for sites in a multisite install. WordPress Out-of-the-Box: Decisions, not Options, but Change with Plugins While WordPress could have had an option for doing what you want built in the philosophy at WordPress is to make decisions for you instead of giving you a thousand options you'll feel you need to understand, and then letting plugin developers changes those decisions if needed. Yes: Central Resources = Better Load Times Still, it would be nice to be able to do what you are asking as it would improve average load times by leveraging HTTP GET caching for multisites with common themes. No Need to "Rewrite" URLs To start, there's no need to "rewrite" the URLs, just make sure the stylesheet and other resources you want are part of the theme assigned to the main site and then they will be located at the URLs you want. Creating the "Hook" for <code> style.css </code> In WordPress you change the out-of-the-box decisions by adding "hooks" ; i.e. references to functions that will let you modify values. One such hook is <code> 'stylesheet_uri' </code> which modifies the URL for the <code> 'style.css' </code> file that you explicitly referenced. You can copy this code to your theme's <code> functions.php </code> file or you can put into the .PHP file of a WordPress plugin you might be writing. Note that I coded this to support either subdomain installs or subdirectory installs: <code> function normalize_resource_url($url) { if (MULTISITE) { $site_url = get_site_url(BLOG_ID_CURRENT_SITE); if (SUBDOMAIN_INSTALL) { $url = preg_replace("#^(https?://[^/]+)(/wp-.*\.(css|js))?$#","{$site_url}\\2",$url); } else { $url = preg_replace("#^({$site_url})(/[^/]+)(/wp-.*\.(css|js))?$#",'\1\3',$url); } } return $url; } </code> Other Resource URLs May Need Their Own Hooks The code above only modifies the main stylesheet URL; if you need other URLs modified you may not to use other hooks. For example, you may end up needing to use <code> 'style_loader_src' </code> and/or <code> 'plugins_url' </code> too but I didn't have my test system set up with enough use-cases to verify if it's needed or not: <code> add_filter('style_loader_src','normalize_resource_url'); add_filter('plugins_url','normalize_resource_url'); </code> Enqueued Scripts and Styles use a <code> base_url </code> Property And it turns out that the enqueued scripts and styles use a property named <code> base_url </code> of the global variables <code> $wp_scripts </code> and <code> $wp_styles </code> , respectively to determine their location if a full URL is not passed explicitly by the developer. The property of <code> base_url </code> is only set once for scripts and left blank for styles; the former is set upon instantiation of a <code> WP_Scripts </code> object that is then assigned to the global variable <code> $wp_scripts </code> . Set the <code> base_url </code> Property in an Early <code> 'init' </code> Hook If you instantiate and assign those early before any calls to <code> wp_enqueue_script() </code> or <code> wp_enqueue_style() </code> you can then set the <code> base_url </code> property immediately after which you can do with an <code> init </code> hook with a priority of <code> 1 </code> ( <code> 1 </code> priorities run very early, before most hooks) . Here's the <code> 'init' </code> hook to accomplish this: <code> add_filter('init','normalize_base_urls',1); function normalize_base_urls() { $GLOBALS['wp_scripts'] = new WP_Scripts(); $GLOBALS['wp_styles'] = new WP_Styles(); $base_url = normalize_resource_url(get_site_url(BLOG_ID_CURRENT_SITE)); $GLOBALS['wp_scripts']-&gt;base_url = $base_url; $GLOBALS['wp_styles']-&gt;base_url = $base_url; } </code> Or Set the <code> base_url </code> Property in a Late <code> 'init' </code> Hook It's also possible to use a very high number for the priority for the <code> 'init' </code> hook (such as 100) after all <code> wp_enqueue_script() </code> or <code> wp_enqueue_style() </code> have been called by (higher numbered priority hooks run after those with lower numbers) . If so you don't need to instantiate the globals, just assign the <code> base_url </code> property: <code> add_filter('init','normalize_base_urls',100); function normalize_base_urls() { $base_url = normalize_resource_url(get_site_url(BLOG_ID_CURRENT_SITE)); $GLOBALS['wp_scripts']-&gt;base_url = $base_url; $GLOBALS['wp_styles']-&gt;base_url = $base_url; } </code> Might Need to Adjust <code> 'init' </code> Hook Priorities if Conflicting Plugins Whichever your preference, I believe either of those two (2) <code> 'init' </code> hooks will work for you, but if you have plugins that use conflicting priorities you might need to lower the priority number to 0 or less with the first approach, or raise the priority above 100 for the second approach. Again I didn't have enough use-case test scenarios to 100% verify so let me know if some use cases are not working for you.
Outputting Canonical Resource URLs Across a Multisite Network?
wordpress
I am trying to insert html into the HTML view.What i have done is to have tinymce advanced(a wordpress plugin) button that throws a popup and in it is all the necessary things to insert the html.The tinymce buttons are however only visible on the visual view. Question 1: Is it a plugin or hack that can allow one to parse html inside the visual view Question 2: Is it possible to insert html code to the html view from a popup initiated from the visual view
Question 1: Is it a plugin or hack that can allow one to parse html inside the visual view Neither of both. The visual view is the visual view and not the HTML view. If you want to paste HTML, use the HTML view. Question 2: Is it possible to insert html code to the html view from a popup initiated from the visual view Technically this should be possible, but it would mean that you need to create a plugin with javascript for that first. In case "hack" from your first question is about writing a plugin, then well, this could be done for visual view as well. The TinyMCE API is a good start for doing that stuff. stackexchange-url ("This answer to the "Want to have the Post editor remembering the last editing position"") question might be helpful as well.
Inserting code to HTML view from a pop up initiated from visual view
wordpress
I have two domains www.domain1.com and www.domain2.com, both pointing to the same host. What I want to do is redirect www.domain2.com to www.domain1.com/domain2. I got this code for a .htaccess from the hosting provider but is giving me a error "500 Internal Server Error" when I install it. What is the problem? <code> RewriteEngine On RewriteCond% {HTTP_HOST} ^ [www.] domain1.com $ [NC] RewriteCond% {REQUEST_URI}! ^ / domain2 / .* ^(.*) RewriteRule / index / $ 1 [L] </code>
<code> What I want to do is redirect www.domain2.com to www.domain1.com/domain2. </code> Then you don't want to do it via <code> htaccess </code> . You need to use the WordPress MU Domain Mapping plugin. Map any blog/site on a WordPressMU or WordPress 3.X network to an external domain. Also see: WordPress 3.0: Multisite Domain Mapping Tutorial The other day, Klint Finley wrote a very good walkthrough of using the new Multisite functionality of WordPress 3.0. In the comments, a lot of people wanted to know how to use your own domain names. Since I’m doing that now, here’s a quick walkthrough/how-to guide.
Domain redirect in Wordpress multisite
wordpress
I have Twitter's own widget set to load on my website, which works just fine. However, on my WP-powered blog the script is included but not rendered. I call it inside an empty <code> div </code> like this: <code> &lt;?php include $_SERVER['DOCUMENT_ROOT'].'/twtr-widget.html' ?&gt; </code> But it appears in the page source as HTML (I'm putting '...' to save room): <code> &lt;script src="http://widgets.twimg.com/j/2/widget.js"&gt;&lt;/script&gt; &lt;script&gt; new TWTR.Widget({... ...&lt;/script&gt; </code> In other words, the script is not being executed. Why is this? EDIT: The blog is located here .
It is hard to say for sure with those floating sidebars, CSS is huge pain to work through. On the outer layer whole <code> div </code> that holds your widget has <code> display: none; </code> property applied and there are couple more places with same property applied to parts of twitter widget. Overall this seems like a huge CSS conflict.
Why isn't my Twitter widget working in my theme?
wordpress
I have two Custom Post Types, "event", and "opportunity". They share a custom hierarchal taxonomy, "location". My client had added a handful of terms (United States (parent), then a few States (children)). I decided to save them time by adding the rest of the States via wp_insert_term. This worked great! Or, so it seemed. The terms showed up fine for me as an admin. When logging into a "Contributor" account, I can go and create a new "Opportunity", and all the terms show as expected. When going to create a new "Event", the only terms that show up are the ones that were created by hand. You can add a new term on the spot via "Event" and it shows up just fine in the location manager. Its as if WordPress is caching the older terms. Any ideas what might be causing this or where I should look? Details: WordPress 3.0.3 Role Scoper 1.3.20
There are some bugs related to hierarchical term caching, indeed: http://core.trac.wordpress.org/ticket/14704 http://core.trac.wordpress.org/ticket/14485
Custom Taxonomy Term Caching?
wordpress
how can i use multiple meta_key and meta_value in query_posts? For example, I want to find multiple content with two different meta_key and meta_value. How do I do this? i using this code but not effective: <code> query_posts('meta_key=test2&amp;meta_value=hello&amp;meta_key=test2&amp;meta_value=bye'); </code> please help me...
This is not currently possible with query arguments alone (realm of filtering raw SQL query and such). If your task is not time-critical then I suggest to wait for upcoming WP 3.1 release. It will feature much more flexible querying capabilities for custom fields. See Advanced Metadata Queries for post on upcoming improvements.
using multiple meta_key and meta_value in query_posts
wordpress
I want to add different class (css) in widgets in site sidebar . For example: First widget in Sidebar -> class=sidebar-top1 Second widget in Sidebar -> class=sidebar-top2 third widget in Sidebar -> class=sidebar-top3 <code> i want to add class in &lt;div&gt; tag. </code> how i can to do?
Check out this post I wrote on the wordpress.org board... it has some functioning code you can work from: http://wordpress.org/support/topic/how-to-first-and-last-css-classes-for-sidebar-widgets
different class (css) for sidebar widgets
wordpress
I have a few function. For both of them need javascript code. I need to add javascript code in header only when function is active. At this time I have all my javascript code in header for all my function and newermind which one of them is active. I tried to make this code but nothing is changed: All I have in scripts.php <code> function my_scripts() { if (!is_admin()) { wp_enqueue_script('jquery'); wp_enqueue_script( 'custom', get_bloginfo('template_directory').'/js/custom.js', array( 'jquery' ), '', true ); if (is_front_page()) { if (function_exists('function_one')) wp_enqueue_script( 'jquery1', get_bloginfo('template_directory').'/js/jquery.plugin.js', array( 'jquery' )); else if (function_exists('function_two')) wp_enqueue_script('jquery2', get_bloginfo('template_directory').'/js/jquery.plugin2.js', array( 'jquery' )); else if (function_exists('function_three')) wp_enqueue_script( 'jquery3', get_bloginfo('template_directory').'/js/jquery.plugin3.js', array( 'jquery' )); } } } add_action('wp_print_scripts', 'my_scripts'); </code> mycode.php This code include all my three functions. Looks like: <code> function function_one() { ?&gt; ...code.. &lt;?php } function function_two() { ?&gt; ...code.. &lt;?php } function function_three() { ?&gt; ...code.. &lt;?php } </code> This two files are defined in <code> functions.php </code> . I'm new in php, please help me how should I need to do? Thank you! UPDATE Function for choosing slider's looks like this <code> function sliders { $sliders = get_option('src_switcher'); // array in theme options with sliders name if($sliders == 'First slider') { function_one(); } if($sliders == 'Second slider') { function_two(); } if($sliders == 'Third slider') { function_three(); } } </code>
Hi @Denis Belousov: Okay, based on your responses I'm going to ask why tie it to the function existing, why not just test the return value of <code> get_option('src_switcher') </code> like this? <code> function my_scripts() { if (!is_admin()) { wp_enqueue_script('jquery'); wp_enqueue_script( 'custom', get_bloginfo('template_directory').'/js/custom.js', array( 'jquery' ), '', true ); if (is_front_page()) { $sliders = get_option('src_switcher'); if ($sliders == 'First slider') wp_enqueue_script( 'jquery1', get_bloginfo('template_directory').'/js/jquery.plugin.js', array( 'jquery' )); else if ($sliders == 'Second slider') wp_enqueue_script('jquery2', get_bloginfo('template_directory').'/js/jquery.plugin2.js', array( 'jquery' )); else if ($sliders == 'Third slider') wp_enqueue_script( 'jquery3', get_bloginfo('template_directory').'/js/jquery.plugin3.js', array( 'jquery' )); } } } add_action('wp_print_scripts', 'my_scripts'); </code> Alternately if you must use the function testing you'll want the code that defines your functions to look like this: <code> $sliders = get_option('src_switcher'); if ($sliders == 'First slider') function function_one() { ...code.. } else if($sliders == 'Second slider') function function_two() { ...code.. } else if($sliders == 'Third slider') function function_three() { ...code.. } </code>
How to Add Javascript Only When a Function Exists?
wordpress
I'm thinking of blocking all IP adresses indicated by Akismet as containing spam. Something like cronning <code> select distinct wp_comments.comment_author_IP FROM `wp_commentmeta` JOIN `wp_comments` WHERE wp_commentmeta.comment_id = wp_comments.comment_id AND wp_commentmeta.meta_value='true' ORDER BY wp_comments.comment_author_IP </code> and then adding the IP's automatically to .htaccess. Even better, I would like to post the current list of 524 IP's to a webservice to be sure hundreds of other people are also blocking the same IP. Is that smart? update now checking with http://www.dnsbl.info/ . Interesting e.g. 109.105.192.194 is listed with one of the spam database but not others. So I probably need to write a plugin that auto blocks the IP and then refer them to DSNBL if they want to unblock themselves. IS there already a DSNBL plugin? update apparantly (ofcourse) there is : http://wordpress.org/support/topic/visitors-checked-by-dnsbl
Personally I highly recommend to not use IP blocks at .htaccess level. There are simply too many false positives possibilities for that to work reliably. I had encountered WP blogs (luckily wave of those seem to have faded) that just shut me out, accusing my IP of belonging to evil spamer... Static IP that belonged to me for years. I especially don't recommend to use Akismet as source of data. Your mileage may differ, but as commenter I had experienced so many false positives with Akismet that I will never touch it as blogger. What I do recommend: use spam filtering methods or sources you are 100% confident will not produce excessive amounts of false positives; do not block out by IP, send matched IP to spam and display informational message about why it was blocked and your means of contact.
Auto block ALL IP's indicated by Akismet?
wordpress
My theme has a "function_exists" wrapper around the is_multisite() call as seen below... <code> if(function_exists(is_multisite())) { //do something } </code> However, I'm still getting this error on theme install... <code> Fatal error: Call to undefined function is_multisite() </code> What am I missing?
the quotes: <code> if(function_exists('is_multisite')) </code>
Fatal error: Call to undefined function is_multisite()
wordpress
My Wordpress blog suddenly seems to have started giving me 404 errors when accessing category pages. For example, http://blog.rtwilson.com/category/tok-related/ . Interestingly, this doesn't happen for child categories (such as GIS and Remote Sensing, shown in the sidebar on the above link) but does happen for parent categories (eg. Academic) and categories with no children (like TOK-related). Does anyone have any ideas why this might have happened? I recently changed the permalink structure for my blog posts themselves, but not for the categories. Do I need to rebuild the category list somehow? If so, how? Update .htaccess file content: <code> # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code>
Apparently this is a common problem with WordPress 3.1+ (just had to fix it on a site I built too). You can get a plugin or a code snippet for your functions.php to fix the problem here: http://wpcodesnippets.info/blog/how-to-fix-the-wp-3-1-custom-permalinks-bug.html
Category links suddenly started giving 404 errors
wordpress
Hey guys, I have been spending the longest time trying to figure out this issue. I would like to know what the file permissions should look like in WordPress in order to use the autoupdate feature . As of now, my wordpress installation keeps asking me for my FTP information and I do not want to use that method of upgrading/installing, I want to use pure/direct PHP. Some context: webserver and php fcgi daemons run as <code> www-data:www-data </code> wordpress installation is at <code> /home/blaenk/sites/domain.tld/ </code> At first, I read that all files/folders should be owned by my user (blaenk) and writable by my user. But this wasn't working, after spending many hours researching, someone on the IRC channel told me to try setting everything to ownership <code> www-data:www-data </code> and this worked. I was no longer asked for FTP information and the plugin installation worked automatically. However, I originally placed the site files in my home directory precisely because I wanted to be able to write/create them as my user. I even added myself to the <code> www-data </code> directory as stated in this guide . Question I already know that files should be 644 and directories should be 755. However, this seems more of an issue of ownership. I don't want to have to set <code> www-data:www-data </code> on everything in my wordpress installation, so I'm wondering what files/directories specifically require this ownership level? EDIT : I believe that the reason for which everything seems to work on my shared hosting wordpress installation despite all of the files being owned by my user is that the shared host I use seems to use suexec which presumably runs PHP as me, so in other words, the files are owned by the webserver, so to speak.
In my question, I stated confusion at the fact that everything worked seamlessly on my shared-hosted despite all of the files being owned by my user, whereas on my VPS, the auto upgrade would not work unless all files were owned by the webserver. I am fairly certain that this is a result of my shared host using suexec which essentially runs the scripts as my user. So essentially, the files on my shared host were owned by the 'web server' (really, the CGI daemon). I am actually running nginx and php-fpm on my VPS, so I do not have access to Apache's suexec. However, I simply configured php-fpm to run as myself, to test my theory, and it did indeed worked seamlessly with all of the files owned by my user. I believe this would be considered a security risk (not sure), so I will investigate further to see what I can do in this regard to avoid running it as my user, but at least now I know what the problem is!
Recommended File Permissions
wordpress
I am using Wordpress 3.0 and would like to organize the directory where uploads are made. Is there any way to change where the files get uploaded or is the only real organization the Media tag plugin? What would be ideal is when a user uploads a file, they can specify a sub directory where to dump the file (or default to date). So a user could say "flowers" and the file would go in uploads/flowers. Thanks!
Please see if Custom Upload Dir (Wordpress Plugin) does the job for you. With that plugin you can configure the upload path based on numerous settings.
Wordpress 3.0 Media Upload Directory
wordpress
In my site i have a navbar which is created by using the new feature of wordpress 3 - "the menus ".In my site this navbar conatins both categories and pages. When I'm in a single post / sub-page , the navbar doesn't give the parent category /page the class of "current-menu-item" and therefore that item in the navbar is not highlighted. I found stackexchange-url ("this") but it really doesn't help me because the menu is not built on category_ID like a regualr navbar created by wp_categories_list(), but on item_ID , which I don't understand how is generated. I would like to know either how the item_ID is generated, and/or how to highlight the right item in the navbar Here is a printscreen of my navbar's HTML and here is a printscreen of navbar created by wp_categories_list() thanks!!
The filter you need is nav_menu_css_classes . You should be able to test for *in_category* on single post and archive pages, and add the appropriate class there.
How to highlight the right item in the navbar
wordpress
I have a WordPress multisite installation. I need to create a sitewide tagcloud on the main blog. How can I do that ?
Use this plugin http://wordpress.org/extend/plugins/wordpress-mu-sitewide-tags/ and this tutorial http://wpmututorials.com/how-to/make-a-tags-page-like-wordpress-dot-com/ It says wpmu, but it is exactly the same.
How can I create a multisite global tag cloud?
wordpress
This is for a personal-use plugin I'm trying to make. I want to submit a comment from site A to my blog (sort of like sending trackbacks/pingbacks but a full comment). For instance, on site A I have a form with a name, url, and comment field. The data I enter in site A, I want to submit to site B (my blog) via URL parameters or the POST method. I assume that I'll need an action hook on my blog to retrieve data sent from site A and insert it in the wp comment table. Is this possible?
Hi @wpStudent:: In WordPress, almost anything is possible. It all depends at times how hard you want to work for it. :) The Comment Post form of course uses HTTP POST to submit to <code> /wp-comments-post.php </code> so you could use that except for the NONCEs if you want to post unfiltered HTML. You'd have to write a page to give you an acceptable NONCE which Site A would need to HTTP GET in order to be able to submit back to to the comment post form but I think if you don't mind the filters it should work fine. Another option is to use a function stackexchange-url ("designed for AJAX") but have it capture your HTTP POST from your form and then save your comment to Site B by calling <code> wp_insert_comment() </code> . Or you could use AJAX on Site B to talk to Site A. Of course you'll be opening up a bit of a security hole by doing that, but if your code isn't distributed you can decide if that creates a real concern or not. (Normally I would write up an example but have run out of time today. Hopefully the above sends you in the right direction.)
Are there action hooks for comments?
wordpress
I am planning on building a plugin and i need to know if the data stored in the options table i will create for the plugin will be serialized or it will be in the ordinary sql format.
It totally depends on what data is being stored in the option, <code> maybe_serialize </code> will determine in the option is holding a singular static value, such as <code> true/false </code> , <code> 0/1 </code> , <code> empty string </code> , whatever(it's called when an option is created or updated).. it will serialize when dealing with objects and arrays, singular values are not serialized. The <code> get_option </code> function is equipped to deal with this however and will unserialize(or not) as necessary for you(using <code> maybe_unserialize </code> ) when it's called, which basically does the inverse of <code> maybe_serialize </code> . Hope that helps.. EDIT: Confirmed - checked source, above information is correct regarding serialization.
Plugin options table,is the data serialized
wordpress
A client of mine runs a Buddypress-based site (BP 1.2.6 on WP 3.0.2). We'd like to give users the ability to publish blogs of their own, but we don't want them to be able to execute PHP code (we make extensive use of the Exec-PHP plugin on the site), activate/deactivate plugins, or basically anything but use the site and publish blogs. How can we lock things down such that only users with "admin" level privileges and higher can execute PHP code, activate/deactivate plugins, manage users, and the like?
Kit, I'd say that if you make extensive use of Exec-PHP what you really need is a developer that can make stuff happen without it. In reality, that plugin is a crutch that is easily replaced with proper widgets, plugins and template code. So, the best advice I can give you about securing that plugin is to remove it.
Best practices for securing a Buddypress installation?
wordpress
I've got two custom post types: CD and Track. Each of them has got some metadata associated with them. What I'm trying to do is to add Track posts to a CD post when the CD post is being edited. On the CD edit page I have "Add Track" link. When clicking on it, I would like a "New Track Form" to appear under the link that will ask for a Track (custom-post-type) information, along with all metadata that needs to be specified for a Track - as if "Add Track" link was clicked from the left WP menus. Hope that makes sense.CD My CD and Track custom-post-types are registered as following: http://wordpress.pastebin.com/Y6aagTVs On the edit CD page I have the following link <code> &lt;a class="addTrack" href=""&gt;Add Track&lt;/a&gt; </code> I'm missing AJAX and the function that will handle the addition of the "New Track form". Here is what I've got so far in the AJAX function: <code> // Add Tracks $("a.addTrack").click(function () { opts = { url: ajaxurl, // ajaxurl is defined by WordPress and points to /wp-admin/admin-ajax.php type: 'POST', async: true, cache: false, dataType: 'json', data:{ action: 'track_add', // Tell WordPress how to handle this ajax request }, success: function(response) { return false; }, error: function(xhr,textStatus,e) { // This can be expanded to provide more information alert("There was an error adding a track."); return false; } }; $.ajax(opts); }); </code> And the function that will handle the insertion of the "New Track Form" is <code> // Add Tracks add_action('wp_ajax_track_add', 'my_ajax_admin_add_track'); function my_ajax_admin_add_track() { } </code> I don't know how to go on about the AJAX and my_ajax_admin_add_track() functions. Would really appreciate any help and tips!!! Many thanks, Dasha
For your my_ajax_admin_add_track() function, grab the form field data from the $_POST array, populate the required data in an array to call wp_insert_post(), then call wp_insert_post() passing it the post data. It should return the new post ID number if successful.
How to add a custom-post-type post within another custom-post-type post edit screen using AJAX?
wordpress
So i'm trying to create a WordPress plugin and I've created some menu pages using this provided function: <code> add_submenu_page('my_plugin_menu', 'Edit record page', 'Edit record page', 'manage_options', 'edit_record_page', array(&amp;$this, 'display_edit_record_page'); </code> and when I go to the page I notice on the address bar on the browser it reads something like this: <code> http://mydomain.com/wp/wp-admin/admin.php?page=edit_record_page </code> What I want to do is to be able to link this page but I find I have to hardcode the link for lack of a better way of doing it and I'm working on a dev site. So I was wondering how I could dynamically generate the link I saw on my browser so that when I copy this plugin code onto the production server it will work. Namely, is there a WordPress function that will generate the link portion of the submenu page create. <code> page=edit_record_page </code> Also, if I want to append query strings to the to the link is it as simple as adding it manually like so: <code> http://mydomain.com/wp/wp-admin/admin.php?page=edit_record_page&amp;rec_id=1 </code> or is there an appropriate WordPress function for doing that too?
<code> admin_url() </code> gets you the correct administration page URL (and <code> network_admin_url() </code> to get a network administration page URL) Optionally, you can use <code> add_query_arg() </code> to append arguments to an URL, using an associative array: <code> $page = 'edit_record_page'; $rec_id = 1; $record_url = add_query_arg(compact('page', 'rec_id'), admin_url('admin.php')); </code>
On the WordPress Admin section how do I link to submenu pages created for a plugin?
wordpress
( Moderator's Note: The original title was "using archive by date with a custom date") I'm adding an additional date to posts as a custom field. Now I want the archive to show posts by the custom date and not by the published date. For example I've got a post published today (22nd December) but the custom date is set to 1st January . When I load the URL <code> archives/date/2011/01 </code> in the browser the posts with the custom date that match are not displayed (obviously). Is there a way to modify the behavior of page generated for the <code> archives/date/2011/01 </code> URL in order to retrive the posts by the custom date? Thanks.
Hi @Dalen: As with many things in WordPress there are several ways to do what you want. I'm going to explain one of them. Remove the <code> 'year' </code> , <code> 'monthnum' </code> and <code> 'day' </code> Query Variables You can modify the parameters to the query WordPress uses on the archive URLs inside the <code> 'pre_get_posts' </code> hook. Those parameters are captured as an associative array by the rewrite rules into the property of the <code> WP_Query </code> object called <code> query_vars </code> variables <code> 'year' </code> , <code> 'monthnum' </code> and <code> 'day' </code> . When <code> $wp_query-&gt;query_vars </code> has values for <code> 'year' </code> , <code> 'monthnum' </code> and <code> 'day' </code> WordPress will use them when querying the list of posts so the first step is to remove those key-value pairs from the query array using PHP's <code> unset() </code> function (note that <code> $wp_query </code> is a global variable in WordPress that contains the current query object as an instance of the <code> WP_Query </code> class.) The <code> yoursite_pre_get_posts() </code> function below triggered by the <code> 'pre_get_posts' </code> hook will remove those variables from the <code> query_vars </code> array but only when the query is the main query *(i.e. the <code> $query </code> passed to the hook is exactly equal to the global <code> $wp_the_query </code> or <code> $query===$wp_the_query </code> ) and only when the query is an archive query. If you add this to your theme's <code> functions.php </code> file you'll find your archive pages display all posts, not just the ones for the date (so we are halfway to what you want...) : <code> add_action('pre_get_posts', 'yoursite_pre_get_posts' ); function yoursite_pre_get_posts( $query ) { global $wp_the_query; if ($query===$wp_the_query &amp;&amp; $query-&gt;is_archive) { unset($query-&gt;query_vars['year']); unset($query-&gt;query_vars['monthnum']); unset($query-&gt;query_vars['day']); } } </code> Add Query Variables for Your Custom Field Now is where it gets a little tricky. In v3.0.x WordPress only allows you to query for custom field using the values in the <code> query_var </code> array and it doesn't allow us to apply functions to those criteria either. The following modification to <code> yoursite_pre_get_posts() </code> would allow your archive query to match an exact date assuming you stored the date in <code> 'YYYY-MM-DD' </code> format in the custom field: <code> add_action('pre_get_posts', 'yoursite_pre_get_posts' ); function yoursite_pre_get_posts( $query ) { global $wp_the_query; if ($query===$wp_the_query &amp;&amp; $query-&gt;is_archive) { $qv = &amp;$query-&gt;query_vars; $date = mktime(0,0,0,$qv['monthnum'],$qv['day'],$qv['year']); $qv['meta_key'] = 'Custom Date'; $qv['meta_value'] = date("Y-m-d",$date); unset($qv['year']); unset($qv['monthnum']); unset($qv['day']); } } </code> And here's what that looks like in a screenshot: Of course that's not really want you want. You want to query for year &amp; month instead of just the specific day, or even for just the year. As I said before, that's where it gets tricky. Use the <code> 'posts_where' </code> Hook to Modify the SQL <code> WHERE </code> Clause Basically you need to go deeper into hooks and and call the <code> 'posts_where' </code> hook, which I always try to avoid if possible since when you are doing text find and replace on SQL query fragments it's very easy to write code that will be incompatible with another plugin that modifies the same SQL query. Nonetheless, if you need it and nothing else will work then it's there for you as a last resort. So the <code> yoursite_posts_where() </code> function searches the <code> WHERE </code> clause that WordPress builds for the text <code> "AND wp_postmeta.meta_value = '2011-01'" </code> and replaces it with the text <code> "AND SUBSTRING(wp_postmeta.meta_value,1,7) = '2011-01'" </code> , and here's the code: <code> add_action('posts_where','yoursite_posts_where',10,2); function yoursite_posts_where( $where, $query ) { global $wp_the_query; if ($query===$wp_the_query &amp;&amp; $query-&gt;is_archive) { $meta_value = $query-&gt;query_vars['meta_value']; $length = strlen($meta_value); $find = "AND wp_postmeta.meta_value = '{$meta_value}'"; $replace = "AND SUBSTR(wp_postmeta.meta_value,1,{$length}) = '{$meta_value}'"; $where = str_replace($find,$replace,$where); } return $where; } </code> Modify <code> yoursite_pre_get_posts() </code> to support multiple Year-Month-Day Options Of course that will require we modify our <code> yoursite_pre_get_posts() </code> function to support different length meta values: <code> 'YYYY' </code> , <code> 'YYYY-MM' </code> and <code> 'YYYY-MM-DD' </code> (Note the use of what appears to be complex use of PHP's <code> mktime() </code> and <code> date() </code> functions are merely to avoid having to worry about these patterns: <code> 'YYYY-M' </code> , <code> 'YYYY-MM-D' </code> and <code> 'YYYY-M-D' </code> ): <code> add_action('pre_get_posts','yoursite_pre_get_posts' ); function yoursite_pre_get_posts( $query ) { global $wp_the_query; if ($query===$wp_the_query &amp;&amp; $query-&gt;is_archive) { $qv = &amp;$query-&gt;query_vars; // Make it less tedious to reference if ($qv['monthnum']==0) // Just search on YYYY $date = $qv['year']; else if ($qv['day']==0) // Search on YYYY-MM $date = date('Y-m',mktime(0,0,0,$qv['monthnum'],1,$qv['year'])); else $date = date('Y-m-d',mktime(0,0,0,$qv['monthnum'],$qv['day'],$qv['year'])); $qv['meta_key'] = 'Custom Date'; $qv['meta_value'] = $date; unset($qv['year']); unset($qv['monthnum']); unset($qv['day']); } } </code> And that gives us the following which pretty much wraps up what you were looking for: Code to Display the Custom Date in the Theme BTW, here's the code I used in the theme to grab the Custom Date meta value: <code> &lt;?php if ($custom_date = get_post_meta($post-&gt;ID,'Custom Date',true)): ?&gt; &lt;h2&gt;Custom Date: &lt;?php echo $custom_date; ?&gt;&lt;/h2&gt; &lt;?php endif; ?&gt; </code> P.S. Remember the User Must Enter in <code> 'YYYY-MM-DD' </code> format Remember the user needs to enter the Custom Date in the <code> 'YYYY-MM-DD' </code> format for this to work. Of course you can make it friendlier to the user via several different methods, i.e. in the SQL code or via a <code> 'save_post' </code> hook that reformats the date but I'll leave that as an exercise for someone else. P.P.S. Option: Save Multiple Meta Values Instead Another approach would have been to use the <code> 'save_post' </code> hook to save three (3) hidden meta values in the right format for matching to <code> 'YYYY-MM-DD' </code> , <code> 'YYYY-MM' </code> and <code> 'YYYY' </code> maybe with the meta keys <code> '_custom_date' </code> , <code> '_custom_date_year_month' </code> <code> '_custom_date_year' </code> which would be more resilient to other plugins that might also want to modify the SQL <code> WHERE </code> clause but would add three (3) additional hidden custom fields for every post so that might not be a good idea for a blog with a large number of posts and it is possible they could get out of sync somehow.
Archive Listings Filtered by Date Values in a Custom Field/Post Meta?
wordpress
I am trying to display different things to new users that have not created a post versus users who have created a post. I tried this, but it did not work for custom post types (only normal posts) and it does not account for drafts or pending posts: <code> &lt;?php if (count_user_posts(1)&gt;=1) { blah blah blah } else {Welcome, blah blah blah }; ?&gt; </code>
Hi @Carson: A simple function to address what you are asking for might be the function <code> yoursite_user_has_posts() </code> which leverages the built in <code> WP_Query </code> class: <code> function yoursite_user_has_posts($user_id) { $result = new WP_Query(array( 'author'=&gt;$user_id, 'post_type'=&gt;'any', 'post_status'=&gt;'publish', 'posts_per_page'=&gt;1, )); return (count($result-&gt;posts)!=0); } </code> You can then call it from your theme like this: <code> &lt;?php $user = wp_get_current_user(); if ($user-&gt;ID) if (yoursite_user_has_posts($user-&gt;ID)) echo 'Thank you for writing!'; else echo 'Get Writing!'; ?&gt; </code>
Display text if current user has written 1 or more posts in a custom post type
wordpress
after successful import of ~4000 users and their blogs &amp; posts from Liftype I have a rights problem: all users only are subscribers in their own blog. How can I mass change it to blog (not sitewide!) administrator privileges? All known functions I found in Codex gives Admin rights for the main blog, that's not what I want. Thanks Uwe Edit: What's wrong here? <code> include 'wp-load.php'; global $wpdb; for ( $blog_id = 393; $blog_id &lt;=4091; $blog_id++ ){ $bloguser= get_users_of_blog ($blog_id); foreach ($bloguser as $usr) { // maybe there is more than one $user_id = $usr-&gt;ID; echo 'Blog No. '.$blog_id.' is property of user: '.$user_id; //control check if ($user_id != '') { $user = new WP_User($user_id); $user-&gt;for_blog($blog_id); $user-&gt;remove_role('editor'); $user-&gt;add_role('administrator'); } } } echo 'Done!'; </code> Code is well running, but there is no change to user's role. Edit: code typo edited, no changes to result @EAMann Are you sure, add_role is the right function? I understand this is for adding a new role to WP system. Edit: Updated the code again. Using update_user_meta. $check gives back 'administrator' (right!), but if I call the user's blog properties, the user is always 'editor'.
From your question, I'm assuming these are users on a specific blog within a MultiSite installation, correct? In that case, do the following: Go to the blog for which you want to make these users administrators. Click on the "Users" button in the left-side admin sidebar This will present you with a display of about 20 users at a time (the display is paged) Click the checkbox next to the users you wish to promote At the top of the list is a dropdown box that says "Change role to..." - Select "Administrator" from this select box Click the "Change" button to the right of the select box You'll have to do this for each page of users, and with 4000 users you'll have about 160 pages of results. But it's doable. Update If you want some specific code, I recommend looking at the <code> WP_User </code> class. This class defines two methods that you'd need to use iteratively: <code> for_blog() </code> and <code> add_role() </code> . Basically, you'll need to loop through your users based either on their IDs or usernames. Consider this untested example code: <code> $ids = [1,2,3,4]; foreach($ids as $id) { $user = new WP_User($id); $user-&gt;for_blog( ... user's blog id ... ); $user-&gt;remove_role('subscriber'); $user-&gt;add_role('administrator'); } </code> By default, the <code> add_role() </code> method of the <code> WP_User </code> class will act on the current blog ... you use <code> for_blog() </code> to switch to a specific blog before running the <code> add_role() </code> method. So if you have the ids of your users and the ids of the blogs they're supposed to be administrators for, you can loop through them pretty easily and set them up as administrators for their specific sites.
Change user role after bulk-import
wordpress
Right now, my login page shows the Wordpress logo. How do I change it to my logo?
Here is a pretty simple approach to changing the logo. Mark Jaquith of WordPress released a plugin that allows you to upload an image which will be shown on the login page instead of the WP logo. Customize the WordPress Login Screen Logo
How do I change the logo on the login page?
wordpress
I'm having a custom sidebar called Footer. I'm displaying this sidebar using this code: <code> &lt;?php if ( !function_exists('dynamic_sidebar') || !dynamic_sidebar('Footer') ) : ?&gt; (maybe I should do something in this line?) :) &lt;?php endif; ?&gt; </code> This works smoothly, but almost every theme nowadays allow users to place their widgets in columns, just like there: http://kaptinlin.com/themes/striking/ My markup looks like: <code> &lt;footer&gt; &lt;li id="plugin-name" class="widget widget_name"&gt;[widget]&lt;/li&gt; &lt;li id="plugin-name" class="widget widget_name"&gt;[widget]&lt;/li&gt; &lt;li id="plugin-name" class="widget widget_name"&gt;[widget]&lt;/li&gt; &lt;/footer&gt; </code> And I want it to look like: <code> &lt;footer&gt; &lt;div id="column_1"&gt; &lt;li id="plugin-name" class="widget widget_name"&gt;[widget]&lt;/li&gt; &lt;/div&gt; &lt;div id="column_2"&gt; &lt;li id="plugin-name" class="widget widget_name"&gt;[widget]&lt;/li&gt; &lt;/div&gt; &lt;/footer&gt; </code> How to achieve that? (btw I don't want to give width/height to my plugins, I want to create containers for them only) I don't know what plugins will user activate so I'm not able to use direct plugin linking. I have to grab 1st plugin, 2nd plugin, 3rd plugin etc., but I see no code allowing me to in Codex.
Use three sidebars an let them float. Anything else will break depending on the widgets your users insert.
Dividing widgets in sidebar?
wordpress
I have a site with FORCE_SSL_ADMIN turned on. When I'm editing a post with an embedded image, or when I'm viewing images through the media library, they are loaded using the http:// protocol rather than https. This causes a mixed-content warning in IE, which clients kind of freak out about. Does anyone have a recommended approach for finding/replacing these non-secure image URLs while viewing them through the admin? The frontend loads over regular http, so I don't want to do any replacing in the DB that will force images to load over https outside of the admin. I figure this has to be a common problem, so I'd appreciate any advice, even if it's "you can't do that".
You can't right now. This needs to be fixed in wordpress core. Probably this can be temporarily circumvented for a fraction of the problems with a plugin, but it's much more valuable to invest the time developing something in an actual fix of wordpress.
How to get the post editor and media library to respect HTTPS administration mode?
wordpress
The search form at the top of the users listing in the Admin area (wp-admin/users.php) is limited and does not search all of the user meta fields, such as bio, instant messenger handles, etc. I've not been able to find a plugin that can add this. Is anyone aware of a plugin or a function I could create that could expand this search for all the date in the _usermeta DB -- ideally even extra fields create by a plugin or function.
Hi @user2041: Clearly as you know you need to modify the search that's performed which you can do by modifying the values in the instance of the <code> WP_User_Search </code> class used for the search (you can find the source code at <code> /wp-admin/includes/user.php </code> if you'd like to study it.) The <code> WP_User_Search </code> Object Here's what a <code> print_r() </code> of that object looks like with WordPress 3.0.3 when searching for the term " <code> TEST </code> " and without any other plugins that might affect it: <code> WP_User_Search Object ( [results] =&gt; [search_term] =&gt; TEST [page] =&gt; 1 [role] =&gt; [raw_page] =&gt; [users_per_page] =&gt; 50 [first_user] =&gt; 0 [last_user] =&gt; [query_limit] =&gt; LIMIT 0, 50 [query_orderby] =&gt; ORDER BY user_login [query_from] =&gt; FROM wp_users [query_where] =&gt; WHERE 1=1 AND (user_login LIKE '%TEST%' OR user_nicename LIKE '%TEST%' OR user_email LIKE '%TEST%' OR user_url LIKE '%TEST%' OR display_name LIKE '%TEST%') [total_users_for_query] =&gt; 0 [too_many_total_users] =&gt; [search_errors] =&gt; [paging_text] =&gt; ) </code> The <code> pre_user_search </code> Hook To modify the values of the <code> WP_User_Search </code> object you'll use the <code> 'pre_user_search' </code> hook which receives the current instance of the object; I called <code> print_r() </code> from within that hook to get access to its values which I displayed above. The following example which you can copy to your theme's <code> functions.php </code> file or you can use in a PHP file for a plugin you are writing adds the ability to search on the user's description in addition to being able to search on the other fields. The function modifies the <code> query_from </code> and the <code> query_where </code> properties of the <code> $user_search </code> object which you need to be comfortable with SQL to understand. Careful Modifying SQL in Hooks The code in the <code> yoursite_pre_user_search() </code> function assumes that no other plugin has modified the <code> query_where </code> clause prior to it; if another plugin has modified the where clause such that replacing <code> 'WHERE 1=1 AND (' </code> with <code> "WHERE 1=1 AND ({$description_where} OR" </code> no longer works then this will break too. It's much harder to write a robust addition that cannot be broken by another plugin when modifying SQL like this, but it is what it is. Add Leading and Trailing Spaces when Inserting SQL in Hooks Also note that when using SQL like this in WordPress it's always a good idea to include leading and trailing spaces such a with <code> " INNER JOIN {$wpdb-&gt;usermeta} ON " </code> otherwise your SQL query might contain the following where there is no space before <code> "INNER" </code> , which would of course fail: <code> " FROM wp_postsINNER JOIN {$wpdb-&gt;usermeta} ON " </code> . Use <code> "{$wpdb-&gt;table_name"} </code> instead of Hardcoding Table Names Next be sure to always using the <code> $wpdb </code> properties to reference table names in case the site has changed the table prefix from <code> 'wp_' </code> to something else. Thus it is better to refer to <code> "{$wpdb-&gt;users}.ID" </code> (with double quotes, not single ones) instead of hardcoding <code> "wp_users.ID" </code> . Limit the Query to Only When Search Terms Exist Lastly be to only modify the query when there is a search term which you can test by inspecting <code> search_term </code> property of the <code> WP_User_Search </code> object. The <code> yoursite_pre_user_search() </code> Function for <code> 'pre_user_search' </code> <code> add_action('pre_user_search','yoursite_pre_user_search'); function yoursite_pre_user_search($user_search) { global $wpdb; if (!is_null($user_search-&gt;search_term)) { $user_search-&gt;query_from .= " INNER JOIN {$wpdb-&gt;usermeta} ON " . "{$wpdb-&gt;users}.ID={$wpdb-&gt;usermeta}.user_id AND " . "{$wpdb-&gt;usermeta}.meta_key='description' "; $description_where = $wpdb-&gt;prepare("{$wpdb-&gt;usermeta}.meta_value LIKE '%s'", "%{$user_search-&gt;search_term}%"); $user_search-&gt;query_where = str_replace('WHERE 1=1 AND (', "WHERE 1=1 AND ({$description_where} OR ",$user_search-&gt;query_where); } } </code> Searching Each Meta Key-Value Pair Requires a SQL <code> JOIN </code> Of course the likely reason WordPress doesn't let you search on usermeta fields is that each one adds a SQL <code> JOIN </code> to the query and to a query with too many joins can be slow indeed. If you really need to search on many fields then I'd create a <code> '_search_cache' </code> field in usermeta that collects all the other information into one usermeta field to require only one join to search it all. Leading Underscores in Meta Keys tell WordPress Not to Display Note that leading underscore in <code> '_search_cache' </code> tells WordPress that this is an internal value and not something to ever display to the user. Create a Search Cache with the <code> 'profile_update' </code> and <code> 'user_register' </code> Hooks So you'll need to hook both <code> 'profile_update' </code> and <code> 'user_register' </code> that are triggered on saving a user and registering a new user, respectively. You can grab all the meta keys and their values in those hooks (but omit those with values that are serialized or URL encoded arrays) and then concatenate them to store as one long meta value using the <code> '_search_cache' </code> key. Store Meta as <code> '|' </code> Delimited Key-Value Pairs I decided to grab all the key names and all their values and concatenate them into one big string with colons (":") separating the keys from the values and vertical bars ("|") separating the key-value pairs like this (I've wrapped them across multiple lines so you can them without scrolled to the right): <code> nickname:mikeschinkel|first_name:mikeschinkel|description:This is my bio| rich_editing:true|comment_shortcuts:false|admin_color:fresh|use_ssl:null| wp_user_level:10|last_activity:2010-07-28 01:25:46|screen_layout_dashboard:2| plugins_last_view:recent|screen_layout_post:2|screen_layout_page:2| business_name:NewClarity LLC|business_description:WordPress Plugin Consulting| phone:null|last_name:null|aim:null|yim:null|jabber:null| people_lists_linkedin_url:null </code> Enables Specialized Searches on Meta Using <code> key:value </code> Adding the key and values as we did allows you to do searches like " <code> rich_editing:true </code> " to find everyone who has rich editing, or search for " <code> phone:null </code> " to find those with no phone number. But Beware of Search Artifacts Of course using this technique creates possibly unwanted search artifacts such as search for "business" and everyone will be listed. If this a problem then you might not want to use such a elaborate cache. The <code> yoursite_profile_update() </code> Function for <code> 'profile_update' </code> and <code> 'user_register' </code> For function <code> yoursite_profile_update() </code> , like <code> yoursite_pre_user_search() </code> above can be copied to your theme's <code> functions.php </code> file or you can use in a PHP file for a plugin you are writing: <code> add_action('profile_update','yoursite_profile_update'); add_action('user_register','yoursite_profile_update'); function yoursite_profile_update($user_id) { $metavalues = get_user_metavalues(array($user_id)); $skip_keys = array( 'wp_user-settings-time', 'nav_menu_recently_edited', 'wp_dashboard_quick_press_last_post_id', ); foreach($metavalues[$user_id] as $index =&gt; $meta) { if (preg_match('#^a:[0-9]+:{.*}$#ms',$meta-&gt;meta_value)) unset($metavalues[$index]); // Remove any serialized arrays else if (preg_match_all('#[^=]+=[^&amp;]\&amp;#',"{$meta-&gt;meta_value}&amp;",$m)&gt;0) unset($metavalues[$index]); // Remove any URL encoded arrays else if (in_array($meta-&gt;meta_key,$skip_keys)) unset($metavalues[$index]); // Skip and uninteresting keys else if (empty($meta-&gt;meta_value)) // Allow searching for empty $metavalues[$index] = "{$meta-&gt;meta_key }:null"; else if ($meta-&gt;meta_key!='_search_cache') // Allow searching for everything else $metavalues[$index] = "{$meta-&gt;meta_key }:{$meta-&gt;meta_value}"; } $search_cache = implode('|',$metavalues); update_user_meta($user_id,'_search_cache',$search_cache); } </code> Updated <code> yoursite_pre_user_search() </code> Function enabling a Single SQL <code> JOIN </code> for Searching All Interesting Meta Values Of course for <code> yoursite_profile_update() </code> to have any effect you'll need to modify <code> yoursite_pre_user_search() </code> to use the <code> '_search_cache' </code> meta key instead of the description, which we have here (with the same caveats as mentioned above): <code> add_action('pre_user_search','yoursite_pre_user_search'); function yoursite_pre_user_search($user_search) { global $wpdb; if (!is_null($user_search-&gt;search_term)) { $user_search-&gt;query_from .= " INNER JOIN {$wpdb-&gt;usermeta} ON " . "{$wpdb-&gt;users}.ID={$wpdb-&gt;usermeta}.user_id AND " . "{$wpdb-&gt;usermeta}.meta_key='_search_cache' "; $meta_where = $wpdb-&gt;prepare("{$wpdb-&gt;usermeta}.meta_value LIKE '%s'", "%{$user_search-&gt;search_term}%"); $user_search-&gt;query_where = str_replace('WHERE 1=1 AND (', "WHERE 1=1 AND ({$meta_where} OR ",$user_search-&gt;query_where); } } </code>
How to search all user meta from users.php in the admin
wordpress
I would like to know why my page navigation within a particular category doesn't work. The code seems correct but I never see the pagination links. <code> &lt;?php $my_query = new WP_Query('cat=18&amp;showposts=8'); while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt; &lt;article id="post-&lt;?php the_ID(); ?&gt;" &lt;?php post_class(); ?&gt;&gt; &lt;?php the_content(); ?&gt; &lt;/article&gt;&lt;!-- #post-&lt;?php the_ID(); ?&gt; --&gt; &lt;?php endwhile; ?&gt; &lt;?php if ( $wp_query-&gt;max_num_pages &gt; 1 ) : ?&gt; &lt;nav id="nav-below"&gt; &lt;h1 class="section-heading"&gt;&lt;?php _e( 'Post navigation', 'themename' ); ?&gt;&lt;/h1&gt; &lt;div class="nav-previous"&gt;&lt;?php next_posts_link( __( '&lt;span class="meta-nav"&gt;&amp;larr;&lt;/span&gt; Older posts', 'themename' ) ); ?&gt;&lt;/div&gt; &lt;div class="nav-next"&gt;&lt;?php previous_posts_link( __( 'Newer posts &lt;span class="meta-nav"&gt;&amp;rarr;&lt;/span&gt;', 'themename' ) ); ?&gt;&lt;/div&gt; &lt;/nav&gt;&lt;!-- #nav-below --&gt; &lt;?php endif; ?&gt; </code>
For this particular problem you need to change this.. <code> &lt;?php if ( $wp_query-&gt;max_num_pages &gt; 1 ) : ?&gt; </code> For.. <code> &lt;?php if ( $my_query-&gt;max_num_pages &gt; 1 ) : ?&gt; </code> However, like Rarst said, if you're looking to change the "main" query, then <code> query_posts </code> is really what you're looking for, and the change above wouldn't be required under those conditions(simply update your query to call <code> query_posts </code> and not <code> WP_Query </code> ). It's hard to tell what you're doing just from what's posted though, so if you're unsure, just make the above change.
Page navigation within a category
wordpress
(My first WP question ever asked! Be gentle!) I'm building a site that is mostly pages (i.e., static), using WP as CMS. At the bottom of several of the pages, there will appear 1, 2, or 3 "promo boxes" -- basically button-images that link to other parts of the site. Though only up to 3 promo boxes will appear on any given page, there will be ~30 different ones to choose from. When my client creates a new page, I'd like him to be able to choose promo boxes from something like a dropdown list of all of the possible promo boxes. Seems to me this should work like this: Create a custom post type called "promo-box". (Though it could just as easily be a tag for regular posts.) Use a tool like Custom Field Template to create a dropdown on the page editor, where the values of the dropdown options are dynamically generated from the list of all existing promo-box posts. ( This is the part I don't know how to do. ) Access the resulting metadata (post number is really all I need, then I can get everything else) on the page template. Based on responses to other questions here, I have taken initial looks at WPAlchemy MetaBox, Posts-2-Posts, and SLT Custom Fields, but I confess the documentation for each of them is slightly geekier than I am, so I haven't delved too deeply. Advice? Is one of the above tools the right solution for me, and I just have to figure it out? Am I missing something here?
As the author of WPAlchemy, I'm a bit bias, but you essentially have a good working model outlined to follow depending on what ever route you choose. However, if using WPAlchemy, you would basically do something like the following (step #2): <code> // functions.php include_once 'WPAlchemy/MetaBox.php'; if (is_admin()) { // a custom style sheet if you want to do some fancy styling for your form wp_enqueue_style('custom_meta_css', TEMPLATEPATH . '/custom/meta.css'); } // define the meta box $custom_metabox = new WPAlchemy_MetaBox(array ( 'id' =&gt; '_custom_meta', 'title' =&gt; 'My Custom Meta', 'template' =&gt; TEMPLATEPATH . '/custom/meta.php' )); </code> <code> custom/meta.css </code> can contain styles that you can style your form with and <code> custom/meta.php </code> is essentially an HTML file with the FORM contents of the meta box, in this case your drop down, to generate your drop down you would do a custom wp query to get all your custom post types. WPAlchemy has some special helper functions to aid in creating your form elements. There is additional documentation to assist you when working in the template. The main goal of WPAlchemy was to keep control in the hands of the developer, from styling (look + feel) to meta box content definition. And myself and others are always willing to help those who comment and ask questions.
Custom field/meta populated by dropdown of existing posts?
wordpress
Does anyone know how the navigation on this site was made? http://www.thinkingforaliving.org
That sliding navigation is a feature built-in to the theme used by the Thinking for a Living website. If you view the source code, you can see that each panel in the slider is defined by similar code starting with: <code> &lt;div id="covers" scope="Covers"&gt; &lt;div class="cover-index grid4 column page"&gt; &lt;div class="cover grid3 cover-quote"&gt; ... </code> A quick look further through the code finds the page defining a couple of specific JavaScript files for the site (custom-built for the site means it's not a publicly available plug-in): <code> &lt;!-- ORG.TFAL.JS --&gt; &lt;script type="text/javascript" src="http://www.thinkingforaliving.org/wp-content/themes/TFAL/lib/js/org.tfal.plugins.js?0.1.0.9"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://www.thinkingforaliving.org/wp-content/themes/TFAL/lib/js/org.tfal.js?0.1.0.7"&gt;&lt;/script&gt; </code> Digging deeper shows that the site is selecting the items inside <code> scope="Covers" </code> and loading them for use elsewhere: <code> /* ---------------------------------- */ /* COVERS */ $('div[scope=Covers]').TFALCovers(); $('.cover-quote').TFALCoverQuote(); /* ---------------------------------- */ </code> The other JavaScript file defines both <code> TFALCovers() </code> and <code> TFALCoverQuote() </code> as jQuery extensions that control the look, layout, and behavior of the home page. So to answer your question, the navigation of this page was built with some cleverly-constructed, custom jQuery extensions. You can poke around in the code yourself and try to simulate the behavior on your own site, or you can use one of any freely available jQuery slideshow/sliding navigation plug-ins: jQuery Slideshow Scripts jQuery Coda Slider
How is this sliding/scrolling navigation made?
wordpress
What is the best way to pass arguments to another page in wordpress. I did it this way : <code> &lt;a href="get_permalinka(id_of_page).'/&amp;i=2&amp;j=3&amp;k=4'"&gt;Link/a&gt; </code> I get this arguments with $_GET['i'],$_GET['j'],$_GET['k'],problem is : this works just with default permalinks,but when I change it to some other permalink type,it does not work any more.Note - I'm passing these arguments from homepage to another page(template page). Thank you for your time.
Use add_query_arg() to do this. Here's a useful function if you need to get the current page URL (when get_permalink is inaccesible, like on Archives): <code> function get_current_page_url() { $request = esc_url($_SERVER["REQUEST_URI"]); $pageURL = (is_ssl() ? 'https' : 'http').'://'; if ($_SERVER["SERVER_PORT"] != "80") $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$request; else $pageURL .= $_SERVER["SERVER_NAME"].$request; if (false === strpos(get_option('home'), '://www.')) $pageURL = str_replace('://www.', '://', $pageURL); if (false !== strpos(get_option('home'), '://www.') &amp;&amp; false === strpos($pageURL, '://www.')) $pageURL = str_replace('://', '://www.', $pageURL); return $pageURL; } </code>
Best way to pass arguments to another page in Wordpress
wordpress
I see a lot of plugins making use of object-oriented coding when there isn't really necessary. But what's even worse is that theme developers are starting to do the same thing. Commercial themes and free popular themes like Suffusion, even my favorite theme - Hybrid, stuff all their functions inside a class, instantiate it once in functions.php and run its functions in a procedural manner :) Wtf? What's the point of doing this? Obviously you won't be using two or more instances of the same theme, at the same time. Let's assume that the plugins do this for the namespace (which is ridiculous), but what's the theme excuse? Am I missing something? What's the advantage of coding a theme like this?
I can understand your confusion based on the example you provided. That's really a poor way to use a class ... and just because a class is used, doesn't make a system OOP. In the case of Hybrid, they're just using a class to namespace their functions. Considering Hybrid is a theme framework , this is done so that child themes can re-use function names without the developer having to worry about name collision. In many cases, a theme framework (parent theme) is so complex, many child theme developers will never understand exactly what goes on under the hood. If Hybrid didn't use a class structure, child theme developers would need to know what all of the existing function calls were so they could avoid re-using names. And yes, you could just prefix all of your functions with a unique slug, but that makes the code hard to read, hard to maintain, and inherently non-reusable should you develop further systems that want to make use of the same functionality. To Answer Your Questions Wtf? What's the point of doing this? Obviously you won't be using two or more instances of the same theme, at the same time. No, you won't be using two or more instances of the same theme. But like I said, think of the class structure in this case as namespacing the functions, not creating a traditional object instance. Lumping everything together in a class and either instantiating it to call methods ( <code> myClass-&gt;method(); </code> ) or calling methods directly ( <code> myClass::method(); </code> ) is a very clean way to namespace things in a readable, reusable fashion. Of course you could always use something like <code> myClass_method(); </code> instead, but if you want to re-use any of this code in another theme, in a plug-in, or in antoher framework you have to go back through and change all of your prefixes. Keeping everything in a class is cleaner and allows you to redevelop and redeploy much more quickly. Let's assume that the plugins do this for the namespace (which is ridiculous), but what's the theme excuse? Am I missing something? In the majority of situations I'd agree with you. However, that majority is quickly waning. I host several sites on a MultiSite installation that use variations of the same theme. Rather than re-create the same theme over and over again with minor differences, I have a single "class" for the parent theme and all of the child themes extend that class. This allows me to define custom functionality for each site while still maintaining a general sense of uniformity across the entire network. On the one hand, theme developers may choose a class-based approach to namespace their functionality (which isn't ridiculous if you work in an environment where you re-use chunks of the same code over and again). On the other hand, theme developers may choose a class-based approach for easy extensibility by child themes. What's the advantage of coding a theme like this? If you're only using Hybrid on your site, there's little to know advantage for you as the end user. If you're building a child theme for Hybrid there are advantages from namespacing and extensibility. If you work for ThemeHybrid, the advantage lies in quick, efficient code reuse across your other projects (Prototype, Leviathan, etc). And if you're a theme developer who likes a specific feature of Hybrid but not the entire theme, the advantage lies in quick, efficient code reuse in your non-Hybrid project (assuming it's also GPL).
Using OOP in themes
wordpress
I have a WordPress multisite installation. The client wants an email update form on the sidebar of every blog. I want to use a widget there so I need to assign it to the sidebar. Is there any way to do that on the theme install ?
yes. preset widgets: stackexchange-url ("Possible to preset a widget's contents via a plugin script?") post your widget code here if you need specific instructions
How can i initialize a widgetized sidebar (with widgets)
wordpress
To put it like this: I have created a WordPress theme for myself which consists of the following: PHP code - GPL v2 licensed like WordPress CSS files - All rights reserved JS files - All rights reserved image files required for the theme - All rights reserved As far as I understand I can copyright all non PHP files in the theme, so my question is: Does this licensing scheme (for file groups) violates the WordPress license? Do I have to publish the PHP code of the theme so it is available to everyone? If I were to make a WordPress powered website with my theme (with the same licenses as above) for someone else (who pays for the service), do I have to publish the PHP code of the theme so it is available to everyone, just the buyer, or anything else?
Does this licensing scheme (for file groups) violates the WordPress license? No, only the PHP code needs to be GPL'd. A popular example is Thesis: http://mashable.com/2010/07/22/thesis-relents/ http://markjaquith.wordpress.com/2010/07/17/why-wordpress-themes-are-derivative-of-wordpress/ Do I have to publish the PHP code of the theme so it is available to everyone? You don't have to publish it if your intention is to use the theme only for yourself. The GPL licence applies only when you distribute the theme to others. do I have to publish the PHP code of the theme so it is available to everyone, just the buyer, or anything else? Just the buyer.
What does exactly GPL license mean for my WordPress theme?
wordpress
I have a Wordpress database which was installed in a development environment... thus, all references to the site itself have a fixed IP address (say 192.168.16.2). Now, I have to migrate that database to a new Wordpress installation on a hosting. The problem is that the SQL dump contains a lot of references to the IP address, and I have to replace it with: my_domain.com. I could use <code> sed </code> or some other command to change the that from the command line, the problem is that there are a lot of configuration data which uses JSON. So what? Well, as you know, JSON arrays uses things like: <code> s:4: </code> to know how many chars an element has, and thus, if I just replace the IP with the domain name, the configuration files will get corrupted. I used an app for Windows some years ago that allows to change values in a database and takes care of the JSON arrays. Unfortunately, I forgot the name of the app... so the question is: do you know any app that allows me to do what I want?
The data you're looking at is not JSON formatted. JSON doesn't (normally) store value types and lengths like that. What you're looking at is SERIALIZED data. A google search for "mysql replace serialized" yields this page, which might help: http://davidcoveney.com/mysql-database-search-replace-with-serialized-php/
How to replace the domain name in a Wordpress database?
wordpress
I don't like the grey one and i'd rather not change each user. Thanks.
I don't see easy way to change default so far, <code> fresh </code> color scheme seems to be hardcoded in plenty of places. If you just need to force some specific scheme for all users it can be done with this: <code> add_filter('get_user_option_admin_color','change_admin_color'); function change_admin_color($result) { return 'classic'; } </code>
Default admin color scheme as "blue"
wordpress
I would like to query posts from a taxonomy created by a plugin (WP Business Directory Manager). How would I do this? I want the query to create html listing of the posts and allow me to list a certain amount, show the associated image to the posts, and a small excerpt. Some examples on wp stack exchange seem like they would help, but might be different in my case. Thanks a lot.
To query by taxonomy you need to know its <code> query_var </code> that is used in its <code> register_taxonomy() </code> call. It defaults to taxonomy name so usually equal to that. Then you use that info in query argument: <code> query_posts( array( 'query_var' =&gt; 'term' ) ); </code> See Querying by taxonomy in Codex. It is hard to suggest more without specifics of your taxonomy and where you need it done (template, standalone function, etc).
How to list posts from a plugin taxonomy?
wordpress
How to filter WP_Query for posts having a certain meta-value, without using a Custom Select Query? I have a custom posttype with meta-key: "open", and meta-value options: "yes" or "no". I would like to show posts only with meta_value = yes, for meta_key = "open". <code> function filter_where($where = '') { $open = "yes"; //$where .= " AND post_date &gt; '" . date('Y-m-d', strtotime('-2 days')) . "'"; return $where; } add_filter('posts_where', 'filter_where'); </code>
I am not sure from your wording if you hadn't tried it with query argument or it didn't work? <code> $the_query = new WP_Query(array( 'meta_key' =&gt; 'open', 'meta_value' =&gt; 'yes' )); </code> Custom Field Parameters in Codex.
Filter WP_Query for posts having a certain meta-value
wordpress
I have a custom plugin which queries users and usermeta, but I now need to filter admins out of the results. A very simplified version of my sql query is: <code> SELECT * FROM usermeta LEFT JOIN users ON users.ID = user_id WHERE meta_key = 'last_name' AND user_role != 'admin' ORDER BY meta_value ASC LIMIT 0, 25 </code> user_role is not a field, and i saw how it is stored as a config string, but i don't see how to make an equivalent query to this. am i missing something? thanks.
You can use this function: <code> // get users with specified roles function getUsersWithRole( $roles ) { global $wpdb; if ( ! is_array( $roles ) ) $roles = array_walk( explode( ",", $roles ), 'trim' ); $sql = ' SELECT ID, display_name FROM ' . $wpdb-&gt;users . ' INNER JOIN ' . $wpdb-&gt;usermeta . ' ON ' . $wpdb-&gt;users . '.ID = ' . $wpdb-&gt;usermeta . '.user_id WHERE ' . $wpdb-&gt;usermeta . '.meta_key = '' . $wpdb-&gt;prefix . 'capabilities' AND ( '; $i = 1; foreach ( $roles as $role ) { $sql .= ' ' . $wpdb-&gt;usermeta . '.meta_value LIKE '%"' . $role . '"%' '; if ( $i &lt; count( $roles ) ) $sql .= ' OR '; $i++; } $sql .= ' ) '; $sql .= ' ORDER BY display_name '; $userIDs = $wpdb-&gt;get_col( $sql ); return $userIDs; } </code>
query users by role
wordpress
What (if any) is the hook or method for including named categories into the wp_list_pages function? The end result would be that the categories are added onto the end of the list of pages (along with any child categories that exist, with proper ul/li nesting for drop down css to act on)... Home | About | Contact | Category 1 | Category 2
Wouldn't it be even easier to call <code> wp_nav_menu() </code> and customize your menu as you please from the admin menu?
How to add categories to wp_list_pages()
wordpress
I've got a great Comment Form and Threaded Comments setup by using the native WordPress functions: <code> comment_form </code> and <code> wp_list_comments </code> . However, I'm trying to also create a custom Contest Comment template for certain posts. I call <code> comments_template('/contest-comments.php', true); </code> conditionally based on whether a certain custom field exists or not. It works great. I'm trying to make it look along the lines of http://2010.sf.wordcamp.org/attendees/ I only want to show the person's name wrapped in a link and their avatar. Therefore, I want my comment form to only show the Name, Email, and URL fields. The text area should be hidden. For the Comment Form, I am passing an empty value for the <code> comment_field </code> key in the <code> $args </code> array I'm passing into <code> comment_form </code> . This makes the comment form look okay, but when someone submits a comment, they get a warning from WordPress saying that their message was blank. Any solutions on how to solve this? Thanks!
Short answer: It doesn't, but you can get around this: <code> add_filter('comment_form_field_comment', 'my_comment_form_field_comment'); function my_comment_form_field_comment($default){ return false; } add_action('pre_comment_on_post', 'my_pre_comment_on_post'); function my_pre_comment_on_post($post_id){ $some_random_value = rand(0, 384534); $_POST['comment'] = "Default comment. Some random value to avoid duplicate comment warning: {$some_random_value}"; } </code> If you want this only for certain pages, then you should create a custom page template , for eg "boo.php", and in the code I posted above, only add these filters if the current page template is boo (use <code> $post-&gt;page_template </code> to get the current page template when doing the check). Related questions: stackexchange-url ("Removing the "Website" Field from Comments and Replies?") stackexchange-url ("Comment form validation")
Does WordPress Allow Blank/Empty Comment Submissions In WordPress?
wordpress
I just noticed 55.000 entries(!) in my wp_options table. I had not been there for a while. So I ran: <code> delete from `wp_options` where `option_name` like '_transient_timeout_rss%' delete from `wp_options` where `option_name` like '_transient_rss_%' </code> And... it is now back to 645 entries... How can I have these older RSS entries removed automatically since transient seems to be eternal. Could It be that on my webhost cron is not working?
Yep, this does seem like a cron issue. Core Control plugin is good to diagnose cron tasks (among other things). I am still unsure what is the reason of you getting overrun with feed transients. However I had written some stackexchange-url ("code that might help with automatic cleanup").
Transient RSS feeds in wp_options not removed automatically?
wordpress
When I deal with Multisite installation.Some themes like mystique and aparatus provide the widget areas with in the theme-settings page to enter Advertising codes in the form of HTML or java script .But I want the 'Ad code Boxes' to access only by super admin(Me on my Multisite) and not by Normal admins .Can I make that boxes available only to me?
If that is custom functionality in theme options page then it is highly specific to that theme. Likely you will need to edit theme files and/or create child theme. Plus option pages can be simply in WordPress API but just as well can be built with help of theme framework or other kind of third party code. I think your first stop should be developers of themes and information on how to best work with their option pages.
Editing theme files and access to the Code pages only to super-admin?
wordpress
Hi to the community, is it possible to change the default username slug to nickname if is available? By default the url is something like: http://domain.tld/author/(admin ) , is it possible to rewrite and change to http://domain.tld/author/(nickname ) so if a user change his nickname from the profile page the slug it will change also to the new name given by the user? thanks a lot! Philip
I see two ways to solve this problem: changing the data that forms the author URL, or changing the author URL. You probably should handle redirects too, so old URLs to user archives keep working when a user changes their nickname. Changing the author URL There are two parts to this question: handle incoming links with the author nickname instead of the author slug, and generate author post urls with the nickname instead of the standard slug. The first part is solved by hooking into the <code> request </code> filter, checking whether it is an author request, and looking up the author by nickname instead of slug. If we find an author, we change the query parameters to use the author ID. <code> add_filter( 'request', 'wpse5742_request' ); function wpse5742_request( $query_vars ) { if ( array_key_exists( 'author_name', $query_vars ) ) { global $wpdb; $author_id = $wpdb-&gt;get_var( $wpdb-&gt;prepare( "SELECT user_id FROM {$wpdb-&gt;usermeta} WHERE meta_key='nickname' AND meta_value = %s", $query_vars['author_name'] ) ); if ( $author_id ) { $query_vars['author'] = $author_id; unset( $query_vars['author_name'] ); } } return $query_vars; } </code> The second part is done by hooking into the <code> author_link </code> filter and replacing the standard author part (indicated by <code> $author_nicename </code> ) with the nickname. <code> add_filter( 'author_link', 'wpse5742_author_link', 10, 3 ); function wpse5742_author_link( $link, $author_id, $author_nicename ) { $author_nickname = get_user_meta( $author_id, 'nickname', true ); if ( $author_nickname ) { $link = str_replace( $author_nicename, $author_nickname, $link ); } return $link; } </code> Changing the data that forms the author URL A maybe easier way would be to update the otherwise unused <code> user_nicename </code> field in the database. I think it is generated from the user login and never changed after that. But I'm not an expert in user management, so use it at your own risk. <code> add_action( 'user_profile_update_errors', 'wpse5742_set_user_nicename_to_nickname', 10, 3 ); function wpse5742_set_user_nicename_to_nickname( &amp;$errors, $update, &amp;$user ) { if ( ! empty( $user-&gt;nickname ) ) { $user-&gt;user_nicename = sanitize_title( $user-&gt;nickname, $user-&gt;display_name ); } } </code>
Change the Author Slug from Username to Nickname
wordpress
I'm using the WP Business Directory Manager plugin and I'm having some problems. The developer hasn't been supporting the plugin lately, so here I am. I need to change the field order. Currently the option is there, but it doesn't work. I need to target the field for CSS purposes, with custom classes/ids And I need to be able to query the post from certain categories from its directory. I would want to post different list on throughout the site and Im not sure how to do that. The plugin is very useful, I just need some help with these issues...PLEASE. Thanks for any help that can be provided.
To change the field order, you can delete all the fields and then add them again in the order of your choosing. Sucks to have to do it that way, but whatever. It's a free program.
Help with WP Business Directory Manager Plugin?
wordpress
I have a widget-less WordPress theme to which I want to add Subscribe by Email functionality. Unfortunatly the plugin only comes in the form of a widget. How can I use the widget functionality without widget support.
It is a little bulky for complex widgets, but you can call any widget in any place (no sidebar required) with <code> the_widget() </code> function.
How to use widget in a widget-less WordPress theme?
wordpress
I'd like this code to only run inside the admin area as it is resorting the items on the public side admin bar too. <code> /* Reorder Admin Menu to put "Pages" at the top */ function menu_order_filter($menu) { $content_menu = array('edit.php?post_type=page'); array_splice($menu, 2, 0, $content_menu); return array_unique($menu); } add_filter('custom_menu_order', create_function('', 'return true;')); add_filter('menu_order', 'menu_order_filter'); </code>
There is very little overhead to assigning couple of filters on hooks that simply won't fire on front end. In general it would be something like this: <code> add_action('init', 'admin_only'); function admin_only() { if( !is_admin() ) return; // filter assignemnts and such go here } </code> Also <code> create_function() </code> is not recommended for performance and some other reasons. It is better to use more modern Anonymous Functions , but for cases like this WordPress provides ready-made <code> __return_true() </code> function.
Run functions only in the admin area?
wordpress
i am having a wordpress function to display the latest 5 tweets of the user, this tweets can be displayed by two ways one is through direct entering the user ID in admin menu which i created, and second is through custom fields, here i want to avoid custom fields and want to start with shortcode, i know i am weak in short-code cause this is my second question related with it but need short-code in this function here is the code <code> function tweet_fetcher(){ global $post; $doc = new DOMDocument(); if((get_option('tweetID'))!=null){ $meta=get_option('tweetID'); $feed = "http://twitter.com/statuses/user_timeline/$meta.rss"; $doc-&gt;load($feed); } elseif((get_option('tweetID'))==null){ if ( $meta =get_post_meta($post-&gt;ID, 'username:', true) ) { $feed = "http://twitter.com/statuses/user_timeline/$meta.rss"; $doc-&gt;load($feed); } } $outer = "&lt;ul&gt;"; $max_tweets = 5; $i = 1; foreach ($doc-&gt;getElementsByTagName('item') as $node) { $tweet = $node-&gt;getElementsByTagName('title')-&gt;item(0)-&gt;nodeValue; //if you want to remove the userid before the tweets then uncomment the next line. //$tweet = substr($tweet, stripos($tweet, ':') + 1); $tweet = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '&lt;a href="$1"&gt;$1&lt;/a&gt;', $tweet); $tweet = preg_replace("/@([0-9a-zA-Z]+)/", "&lt;a href=\"http://twitter.com/$1\"&gt;@$1&lt;/a&gt;", $tweet); $outer .= "&lt;li&gt;". $tweet . "&lt;/li&gt;\n"; if($i++ &gt;= $max_tweets) break; } $outer .= "&lt;/ul&gt;\n"; return $outer; } function append_the_content($content) { $content .="&lt;p&gt;Latest Tweets".tweet_fetcher($meta)."&lt;Script Language='Javascript'&gt; &lt;!-- document.write(unescape('%3C%61%20%68%72%65%66%3D%22%68%74%74%70%3A%2F%2F%6D%62%61%73%2E%69%6E%2F%22%20%74%61%72%67%65%74%3D%22%5F%62%6C%61%6E%6B%22%3E%50%6F%77%65%72%65%64%20%62%79%20%4D%42%41%73%3C%2F%61%3E')); //--&gt; &lt;/Script&gt;&lt;/p&gt;"; return $content; add_filter('the_content', 'append_the_content'); require_once ('tweet-fetcher-admin.php'); </code>
Here you go: <code> add_shortcode('latest_tweets', 'latest_tweets'); function latest_tweets($atts){ extract(shortcode_atts(array( 'max' =&gt; 5 ), $atts)); $twitter_id = esc_attr(strip_tags($atts[0])); // try to get data from cache to avoid slow page loading or twitter blocking if (false === ($output = get_transient("latest_tweets_{$twitter_id}"))): $doc = new DOMDocument(); $feed = "http://twitter.com/statuses/user_timeline/{$twitter_id}.rss"; $doc-&gt;load($feed); $output = "&lt;ul&gt;"; $i = 1; foreach ($doc-&gt;getElementsByTagName('item') as $node) { $tweet = $node-&gt;getElementsByTagName('title')-&gt;item(0)-&gt;nodeValue; //if you want to remove the userid before the tweets then uncomment the next line. //$tweet = substr($tweet, stripos($tweet, ':') + 1); $tweet = preg_replace('@(https?://([-\w\.]+)+(:\d+)?(/([\w/_\.]*(\?\S+)?)?)?)@', '&lt;a href="$1"&gt;$1&lt;/a&gt;', $tweet); $tweet = preg_replace("/@([0-9a-zA-Z]+)/", "&lt;a href=\"http://twitter.com/$1\"&gt;@$1&lt;/a&gt;", $tweet); $output .= "&lt;li&gt;{$tweet}&lt;/li&gt;\n"; if($i++ &gt;= $max) break; } $output .= "&lt;/ul&gt;\n"; set_transient("latest_tweets_{$twitter_id}", $output, 60*10); // 10 minute cache endif; return $output; } </code> Usage: <code> [latest_tweets "DarthVader" max=5] </code> PS: you have some exploit in the code you posted in your question. You should take care of that... PPS: for people who want to do something like this: use Yahoo Query Language , requests should be faster theoretically, and you have less chances to be limited by the service you're requesting data from use the JSON format for the data you request use WP's HTTP API to make external requests
shortcode help require
wordpress
For a WP Theme with multiple admin screen (got its own main menu and some submenus), I want to add a common Js script to load on (only) all these pages. I know how to acheive this using the pagehooks of the individual (sub)pages lioke this: <code> add_action('admin_print_scripts-' . $page, 'my_plugin_admin_script'); </code> but this way I need to reåeat this for each admin page (for each submenu pagehook) Is there a way smarter way to add the scripts, testing for the PARENT menu? so that I just need to add it with one line of admin_print_scripts-* code?
It would be easiest to run some conditional logic on <code> $parent_file </code> inside a callback hooked onto <code> admin_print_scripts </code> , and would go a little something like this.. <code> add_action( 'admin_print_scripts', 'possibly_enqueue_script' ); function possibly_enqueue_script() { global $parent_file; if( 'my-slug' == $parent_file ) wp_enqueue_script( ... your enqueue args .. ); } </code> You'll need to replace <code> my-slug </code> with the handle of your parent page, it's the fourth parameter in <code> add_menu_page </code> ... The script will then enqueue for both the parent page and any of it's children pages.. Hope that helps...
add JS to multiple plugin admin pages
wordpress
WP loops are widely used to print lists of posts in Wordpress: <code> &lt;?php $loop = new WP_Query( array( 'post_type' =&gt; 'ff', 'ff' =&gt; 'show_ff', 'orderby' =&gt; 'menu_order', 'order' =&gt; 'ASC' )); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;!-- here we're going to have all posts from show_ff category of ff type. --&gt; &lt;?php endwhile; ?&gt; </code> Is there a way of displaying for example 3 first posts then some element (div in my case) and again 3 next posts? I know I could do 6 loops in each div, but maybe there's another way of breaking this code? Maybe some if loops inside of while loop? Here's my concept: <code> (...) while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); echo '3 first posts'; echo '&lt;div class="special"&gt;&lt;/div&gt;'; echo '3 last posts'; endwhile; ?&gt; </code>
I don't think i've fully grasped how you want this to work, but if i assume for a moment that as long as the loop has at least 6 posts, you want to insert extra markup after the third result in the loop.. Example Insert extra markup after the third post, when the current iteration has at least 6 posts <code> &lt;?php if( $loop-&gt;have_posts() ) : //$post_count = $loop-&gt;found_posts; // &lt;-- think this is the total, corrected below $post_count = $loop-&gt;post_count; // should be the result count for the current page $loop_count = 0; while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); $loop_count++; ?&gt; &lt;!-- your regular loop markup, eg. title, content, etc.. --&gt; &lt;?php if( $post_count &gt;= 6 &amp;&amp; $loop_count == 3 ) : ?&gt; &lt;!-- extra markup to put in when it's the end of the third post of this loop --&gt; &lt;?php endif; endwhile; endif; ?&gt; </code> This way you avoid the need to use an offset and can using paging if necessary. I havn't tested the code, but i've given numerous examples like this before, simply let me know of any problems and i'll re-examine(and test) the code.
Breaking the loop?
wordpress
What is the difference between feeds served by my WordPress install vs feeds served by FeedBurner? How to disable hosted Wiordpress feed completely and use feedburner?
Here are some reasons I think FB does well: feed statistics: subscribers, item view and clicks email subscription: control email template, subscribers sharing posts on social networks with FeedFlare monitize with Google Adsense reduces CPU usage on your host. Some of above features you can do with plugins, but it costs CPU usage and sometimes host space. With FB, you let FB do all of these stuff without any prices. FB has its own plugin that redirects WP feed to FB automatically, you can find it in FB.
What is the difference between feeds served by my WordPress install vs feeds served by FeedBurner?
wordpress
I am using wordpress Multisite installation . 1)I want to run my website faster .Especially the main site.There are near about 50 plugins .I want to exclude many of these plugins on Main site and activate to other sub-sites.Could any body tell me how to do it? I have other three questions related to plugins on multisite installation: 2)Is there any chance for too much load on server or trouble loading pages if I Use 50 + plugins? 3)For two months I installed many plugins and un-installed them .Now i doubt that if the traces of these deleted plugins affect the server load. Is that true? If so how can I get rid of them ? 4)Some of the plugins would be activated on some sub-sites and active on some other sub-sites.So does the plugins on the sub-sites which are not active affect the server load? Thanks in Advance !
I only recently started to poke multisite, as far as I understand you activate plugins per-site by activating theme in that site's admin area. You can switch between backend of different sites in <code> Super Admin &gt; Sites &gt; (hover cursor on site) &gt; Backend </code> . Server load is not about quantity of plugins, but quality and performance specific of plugins used, amount of page views and caching. You can try plugin like Clean Options to check for leftover settings, but it is still manual work to properly determine and safely remove options. Leftover database tables are even more of a mess. Inactive plugins are not processed in any way. WordPress stores information about active plugins in database and only loads those on the list. Rest are merely ignored files on hard drive when inactive.
Exclude plugins on Main site on Multisite installation?
wordpress
To simplify the Media Library layout to users when uploading an image, sometimes i hide the following fields: <code> function myAttachmentFields($form_fields, $post) { if ( substr($post-&gt;post_mime_type, 0, 5) == 'image' ) { $form_fields['image_alt']['value'] = ''; $form_fields['image_alt']['input'] = 'hidden'; $form_fields['post_excerpt']['value'] = ''; $form_fields['post_excerpt']['input'] = 'hidden'; $form_fields['post_content']['value'] = ''; $form_fields['post_content']['input'] = 'hidden'; $form_fields['url']['value'] = ''; $form_fields['url']['input'] = 'hidden'; $form_fields['align']['value'] = 'aligncenter'; $form_fields['align']['input'] = 'hidden'; $form_fields['image-size']['value'] = 'thumbnail'; $form_fields['image-size']['input'] = 'hidden'; $form_fields['image-caption']['value'] = 'caption'; $form_fields['image-caption']['input'] = 'hidden'; } return $form_fields; } add_filter('attachment_fields_to_edit', 'myAttachmentFields'); </code> Question: How do I hide the Insert into post button and the Set image text link. Thanks in advance
Jose, give this a shot and see if that's the kind of thing you had in mind.. EDIT: Done a little bit of testing and copying of core code to archieve this, but i think the new example i've added below should do what you've described, remove the buttons, "Insert into Post", etc..., but keep a delete link. I've left the original example i provided because it may be useful to someone. New Example Remove buttons, but keep a delete link <code> function myAttachmentFields($form_fields, $post) { // Can now see $post becaue the filter accepts two args, as defined in the add_fitler if ( substr( $post-&gt;post_mime_type, 0, 5 ) == 'image' ) { $form_fields['image_alt']['value'] = ''; $form_fields['image_alt']['input'] = 'hidden'; $form_fields['post_excerpt']['value'] = ''; $form_fields['post_excerpt']['input'] = 'hidden'; $form_fields['post_content']['value'] = ''; $form_fields['post_content']['input'] = 'hidden'; $form_fields['url']['value'] = ''; $form_fields['url']['input'] = 'hidden'; $form_fields['align']['value'] = 'aligncenter'; $form_fields['align']['input'] = 'hidden'; $form_fields['image-size']['value'] = 'thumbnail'; $form_fields['image-size']['input'] = 'hidden'; $form_fields['image-caption']['value'] = 'caption'; $form_fields['image-caption']['input'] = 'hidden'; $form_fields['buttons'] = array( 'label' =&gt; '', 'value' =&gt; '', 'input' =&gt; 'html' ); $filename = basename( $post-&gt;guid ); $attachment_id = $post-&gt;ID; if ( current_user_can( 'delete_post', $attachment_id ) ) { if ( !EMPTY_TRASH_DAYS ) { $form_fields['buttons']['html'] = "&lt;a href='" . wp_nonce_url( "post.php?action=delete&amp;amp;post=$attachment_id", 'delete-attachment_' . $attachment_id ) . "' id='del[$attachment_id]' class='delete'&gt;" . __( 'Delete Permanently' ) . '&lt;/a&gt;'; } elseif ( !MEDIA_TRASH ) { $form_fields['buttons']['html'] = "&lt;a href='#' class='del-link' onclick=\"document.getElementById('del_attachment_$attachment_id').style.display='block';return false;\"&gt;" . __( 'Delete' ) . "&lt;/a&gt; &lt;div id='del_attachment_$attachment_id' class='del-attachment' style='display:none;'&gt;" . sprintf( __( 'You are about to delete &lt;strong&gt;%s&lt;/strong&gt;.' ), $filename ) . " &lt;a href='" . wp_nonce_url( "post.php?action=delete&amp;amp;post=$attachment_id", 'delete-attachment_' . $attachment_id ) . "' id='del[$attachment_id]' class='button'&gt;" . __( 'Continue' ) . "&lt;/a&gt; &lt;a href='#' class='button' onclick=\"this.parentNode.style.display='none';return false;\"&gt;" . __( 'Cancel' ) . "&lt;/a&gt; &lt;/div&gt;"; } else { $form_fields['buttons']['html'] = "&lt;a href='" . wp_nonce_url( "post.php?action=trash&amp;amp;post=$attachment_id", 'trash-attachment_' . $attachment_id ) . "' id='del[$attachment_id]' class='delete'&gt;" . __( 'Move to Trash' ) . "&lt;/a&gt;&lt;a href='" . wp_nonce_url( "post.php?action=untrash&amp;amp;post=$attachment_id", 'untrash-attachment_' . $attachment_id ) . "' id='undo[$attachment_id]' class='undo hidden'&gt;" . __( 'Undo' ) . "&lt;/a&gt;"; } } else { $form_fields['buttons']['html'] = ''; } } return $form_fields; } // Hook on after priority 10, because WordPress adds a couple of filters to the same hook - added accepted args(2) add_filter('attachment_fields_to_edit', 'myAttachmentFields', 11, 2 ); </code> Original Example Example of how to remove all buttons, but provide an insert into post button. <code> function myAttachmentFields($form_fields, $post) { if ( substr( $post-&gt;post_mime_type, 0, 5 ) == 'image' ) { // .. $form_fields code here(per above example), trimmed for illustration .. $form_fields['buttons'] = array( 'label' =&gt; '', // Put a label in? 'value' =&gt; '', // Doesn't need one 'html' =&gt; "&lt;input type='submit' class='button' name='send[$post-&gt;ID]' value='" . esc_attr__( 'Insert into Post' ) . "' /&gt;", 'input' =&gt; 'html' ); } return $form_fields; } // Hook on after priority 10, because WordPress adds a couple of filters to the same hook add_filter('attachment_fields_to_edit', 'myAttachmentFields', 15, 2 ); </code> Set the filter to priorty 15, so it's hooked on after WordPress has hooked it's own filters on(because it adds them at the default priority of 10). Not sure you wanted the insert button, just wanted to give an example of replacing the original buttons with a singular insert one.. Hope that helps..
Trying to hide buttons from Attachment window
wordpress