wp_handle_upload() - how to upload to a custom subdirectory within uploads

wp_handle_upload() works for me, but uploads files where it wants (uploads/year/month). Question: Is there any way to tell it to upload files to a custom dir (uploads/mycustomdir)? Or is there some other function which could do this? What I tried:   1. php's move_uploaded_file() (wasn't able to figure the target directory parameter - this is for a plugin and I need it to work for everyone regardless of their dir structure).   2. https://yoast.com/smarter-upload-handling-wp-plugins I pasted this code into my plugin's core file. Nothing happened. But I see in the comments this seems to work for people. PLEASE if you have an answer, give a complete one. I'm able to get $_FILES['myfile']. What steps to take from there to make that file go to uploads/mycustomfolder?


Display custom field in Media library according to a custom type

I have a custom field that follows any picture in the media library. It's added like this:               function add_image_attachment_field( $form_fields, $post ) {         $form_field["xxxx"] = array(             "label" => __('something'),             "input" => "textarea",             "value" => esc_attr( get_post_meta($post->ID, "xxxx", true))         );              return $form_field;     }     add_filter("attachment_fields_to_edit", "add_image_attachment_field", null, 2);      It works great but I would like to display this field only for the pictures related to a specific custom post type. Is it possible?


Does Google detect files in the Wordpress plugin directory

Will Google detect files in the Wordpress plugin directory? Example:               /wp-content/plugins/random-image-gallery-with-fancy-zoom/js/          /wp-content/plugins/revslider/rs-plugin/videojs/demo.html      I put blank index.php's on the folder and directory, and a meta noindex in the HTML. Will this keep Google from indexing it?


Javascript on Registration Page

I've been trying to figure out how to implement javascript on my registration page with no luck. I've read the documentation on wordpress about properly including js, have searched for relevant answers, and believe I have followed all steps correctly, however it's not working. Basically I call a .js file in functions.php, and it doesn't load in the page header. Here is the implementation in functions.php (on line 156): http://pastebin.com/ZtK3Kw2E Here is the js file contents:               function forceNumber(event){     var keyCode = event.keyCode ? event.keyCode : event.charCode;     if((keyCode < 48 || keyCode > 58) && keyCode != 8 && keyCode != 9 && keyCode != 32 &&     keyCode != 37 && keyCode != 39 && keyCode != 40 && keyCode != 41 && keyCode != 43 &&     keyCode != 45 && keyCode != 46)     return false;     }      Here is the page it is implemented on: https://jannus.org/wp- login.php?action=register Again, it seems as if I followed the directions correctly but the page does not seem to be loading the file. Any assistance on this would be greatly appreciated! Also, thank you for opening a stack forum for wordpress! Kindly, Helena


Cleaning up bloated wp_postmeta table by removing multiple _thumbnail_id's?

On a very old site (7 yrs) with a lot of posts (30k) I've been trying to whittle down the database tables. The postmeta table is 1.5m rows, 750k of those rows are for a meta_key named '_thumbnail_id'. I know this sets the featured image for each post, but I'm confused as to why there are 750,000 of these set when there are only 30,000 posts. Many post_id's appear to have 5-6 featured images set (http://cl.ly/image/0S3Z2M1V2c0M). That was generated by this               SELECT *       FROM `wp_postmeta` WHERE `meta_key` = '_thumbnail_id'     ORDER BY `wp_postmeta`.`post_id`  ASC      They aren't duplicates (ie two rows with the same post_id and meta_value). I'm guessing the featured image was changed multiple times and the old values are not removed but am unsure. Two questions really, is this normal behavior or something I need to track down and fix? Whether this is normal or not, if they're not being used, can they be removed? Bonus question, what's the safe MySQL query to remove only the unused ones?


How to add admin functionality to allow ability to choose different field group to display on webpage using Advanced Custom Fields?

Currently I have a field group defined using the ACF plugin, showing: title and icon and a link, on a specif area of my page. I want to give one of my Content Contributors the ability to choose from two different field groups for that same area of my page depending on their needs. Is this possible? If so how would I go about it doing? Thank you.               <h2 class="icon" style="background:url(<?php the_field('top_left_icon');?>) no-repeat left center;"><?php the_field('top_left_title');?>
     <?php the_field('top_left_text');?>          <?php if( (get_field('top_left_button_text')) && (get_field('top_left_button_link'))){?>     <a class="button" href="<?php the_field('top_left_button_link'); ?>"><?php the_field('top_left_button_text'); ?>     <?php } ?>      And here is a screen grab of what that looks like implemented in the ACF plugin admin side of things: ![enter image description here](http://i.stack.imgur.com/ScTWj.png)


View list of all attachments on site

I'm new to WordPress theme development and I'm trying to figure out if there is a way to display a list of public attachments similar to how you can view a list of posts with a specific tag or author. That is, if I want to retrieve a list of posts with a specific tag, I can submit something like '?tag=mytag' in the URL and Wordpress will spit out all the posts tagged with 'mytag'. So what is the equivalent of this for viewing attachments? Or is there one? What I'm specifically wanting to do is allow the user to click a link and have a gallery of attachments (images, video, music, etc) display. I want attachments from ALL posts on the site, not just attachments of one specific post. I've looked into the attachment.php file, but this seems to only be to display the details of a specific attachment with a given attachment_id value (ie: '?attachment_id=246'). Can someone steer me in the right direction?


How to remove file versions from the file source links in wp_head?

I observed the inside the `wp_head` function in the source links of every `.css`, `.js` files a `?ver=1` ( _or other number based on the file's/library version_ ) is added. How can I overwrite them, to remove them? This issue I think is causing problems on the cache manifest part.


Speed optimization on WP site, Remove query strings from static resources

I am using GTMetrix to test the speed of one of my sites. The report says that I should 'Remove query strings from static resources' Resources with a "?" in the URL are not cached by some proxy caching servers. Remove the query string and encode the parameters into the URL for the following resources... How can I do that and is it recommended?


Wordpress setup one database with two different website?

Hello Friends I want to setup two website `first.com` and `second.in` that are different domain and server. I want to a same data base in both site with the same content.               means we enter new posts in first.com then after that posts show in both sites.      i want to share every thing in both site like posts,page,comment,etc....


Subfolder index.php 404 Errors

I'm looking for help troubleshooting why subfolder pages return a 404 error if "index.php" is appended after the subfolder. I do not experience this behavior on other WordPress sites. I have inherited this site from previous developers, so I don't know what may have caused this. Here are some examples and additional information: **WORKS:** www.mydomain.com/parentpage/   **404 PAGE:** www.mydomain.com/parentpage/childpage/index.php **WORKS:** www.mydomain.com/category/slug/   **404 PAGE:** www.mydomain.com/category/slug/index.php **PERMALINK SETTING:**   Custom Structure: www.mydomain.com/%category%/%postname%/ **HTACCESS:**               <IfModule mod_rewrite.c>     RewriteEngine On     RewriteBase /     RewriteRule ^index\.php$ - [L]     RewriteCond %{REQUEST_FILENAME} !-f     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule . /index.php [L]     </IfModule>


Wordpress Widget - Saving multidimensional arrays into $instance

In my wp widget, `$instance` has an attribute called `order` which will the listing order of libraries/services. I'd like to store a multidimensional associative array that will hold the id of each location/service, its type (i.e. if it's a location or a service), and it's name. I'd like it to look something like this:                array(          [0] => ( 'id' => 1, 'type' => 'location', 'name' => 'University Library'),          [1] => ( 'id' => 7, 'type' => 'service', 'name' => 'Circulation Desk') );      Below is the html markup for the wp widget admin pane and `$instance['order']`:               <label>       <?php _e( 'Select ordering', 'olh' ); ?>:     </label>          <select       name='select-hours-order'       class='select-hours-order'>       <!-- dynamically populated by jQuery -->     </select>          <a        class='add-location-service'>       <i>+</i>     </a>          <ul       name='<?php echo $this->get_field_name( 'order' ) ?>[]'       id='<?php echo $this->get_field_id( 'order' ) ?>'       class='location-service-order' >            <?php          foreach ($instance['order'] as $order ) : ?>              <li           class="<?php echo $order['class'] ?>"           value="<?php echo $order['value'] ?>">           <?php echo $order['name'] ?>         </li>       <?php endforeach; ?>          </ul>      The user can choose what locations/services s/he wants to display with a multi-select dropdown. Whenever the user selects a library/service, it automatically populates `select.select-hours-order`. The user can then click the `+` button of `a.add-location-service` to add it to `ul.location-service- order`. From there, I'd like to save the `li`s of `ul.location-service-order` with the attributes I specified above. Thank you gals/guys for any and all info.


Add class to items in wp_list_categories()

I have this in my `category.php` to show sub-subcategories:               <?php if (is_category()) {       $this_category = get_category($cat);       if (get_category_children($this_category->cat_ID) != "") {         echo "
";         wp_list_categories('orderby=id&show_count=0&title_li=     &use_desc_for_title=1&child_of='.$this_category->cat_ID);         echo "
";       }     }?>      * * *

     subcategory

sub-subcategory1

sub-subcategory2

      Is it possible to add a class with the sub-subcategory name?
sub-subcategory1


Taxonomy query for children of parents

I am stuck on this. I thought I had it correct but then realized it's not. I have a custom hierarchical taxonomy based on location. States are top level and counties are children. I have the top level states in a right side menu and when chosen take me to the taxonomy page for that state. Within that state page the right hand menu should display the counties for only that particular state. Instead it is retrieving all the children of the states and displaying. Since this is a taxonomy page for the state is their a query to determine the current top level page and just display the children as links? My current code is below.               <?php     $taxonomyName = "location";     //This gets top layer terms only.  This is done by setting parent to 0.       $parent_terms = get_terms($taxonomyName, array('parent' => 0, 'orderby' => 'slug', 'hide_empty' => false));        echo '
';     foreach ($parent_terms as $pterm) {     //Get the Child terms     $terms = get_terms($taxonomyName, array('parent' => $pterm->term_id,'orderby' => 'slug', 'hide_empty' => false));     foreach ($terms as $term) {         echo '

name, $taxonomyName ) . '">' . $term->name . '

';       }     }     echo '
';     ?>      Thanks for any assistance.


Custom function for "Submit for Review" hook

So I manage a blog of about 15 contributors and 5 editors. I wanted to implement a system so that each time a contributor hits the 'Submit for Review' button, and email is sent to the editors to proof. I've cooked up an action, but it seemed to fire off at "edit post" time and not "submit" time. My workaround was to put a check for the post status, only fire the email of it's "pending", but before they hit submit, the status is still 'draft'... this means it only works on the second they hit submit for review. Here's my snippet so far. Please help!               function submit_send_email() {         global $post;         if ( current_user_can('contributor') && $post->post_status == 'pending' ) {             $user_info = get_userdata ($post->post_author);             $strTo = array ('email@example.com');             $strSubject = 'Fstoppers: ' . $user_info->user_nicename . ' submitted a post';             $strMessage = '"' . $post->post_title . '" by ' . $user_info->user_nicename . ' was submitted a post for review at ' . wp_get_shortlink ($post->ID) . '&preview=true. Please proof.';             wp_mail( $strTo, $strSubject, $strMessage );         }     }     add_action('edit_post','submit_send_email');      UPDATE: I tried to make Frankenstein setup, having my action schedule an event that would get run 15 seconds later, no dice.               function submit_send_email ($post) {         if ( $post->post_status == 'pending' ) {             $user_info = get_userdata ($post->post_author);             $strTo = array ('email@example.com');             $strSubject = 'Fstoppers: ' . $user_info->user_nicename . ' submitted a post';             $strMessage = '"' . $post->post_title . '" by ' . $user_info->user_nicename . ' was submitted a post for review at ' . wp_get_shortlink ($post->ID) . '&preview=true. Please proof.';             wp_mail( $strTo, $strSubject, $strMessage );         }     }     function submit_for_review() {         global $post;         if ( current_user_can('contributor') ) {             wp_schedule_single_event( time() + 15, 'submit_send_email_event', $post );         }     }     add_action('submit_send_email_event','submit_send_email', 10, 1);     add_action('save_post','submit_for_review');


Migrating old posts to new wp, how to extrapolate infos from the post body to custom fields?

I need to migrate some information that are store in the post body (like "price:200$"), extrapolate them somehow and put them into custom fields. how do I do that? The blog is about restaurants and the location and prices are written in the body of the posts, I need to have them into custom fields so I can perform searches on them.


Display term description on hover using get_the_term_list

I have a custom taxonomy called services. Each service term will have a description. I am using get_the_term_list to show all the terms attached to each post. When hovering over the term link in the front-end I would like to show the term description just like WordPress does within the back-end when you hover over any link.


Display Random Author with Details in Sidebar

PHP newbie here, recently decided to have a stab at cobbling together a kooky little 'Random Author Spotlight' feature into my current WordPress theme. I'm almost done, but I've hit something of a snag: I need to somehow make it so that my 'spotlight' will only select users with 1 post or more. Everyone whom registers on my blog immediately becomes a Subscriber and is able to post news directly on the front page, but most are content with just being regular, post-less members. I'll only be able to incorporate the 'spotlight' into my theme if I can get it to randomly select a user whom has submitted 1 post or more. Here's the code so far:
         <?php $users = get_users(); $id = array_rand( $users, 1 ); $user = $users[$id]; ?>         Hey, have you met...
<a class="" href="<?php echo the_permalink(); ?>"><?php echo $user->display_name; ?>

<?php echo get_avatar( $user->ID, '60' ); ?>
         Mods: <?php echo count_user_posts($user->ID); ?>         <?php echo $register_date = date("F d, Y", strtotime(get_the_author_meta('user_registered'))); ?>

             <?php $random_author_box = new WP_Query(array('author' => $user->ID,'posts_per_page' => '5')); if ($random_author_box->have_posts() ) : while ($random_author_box->have_posts() ) : $random_author_box->the_post(); ?>
                     <a class="sidebarPostTitle" href="<?php echo the_permalink(); ?>"><?php echo the_title(); ?>
             <?php endwhile; endif; ?>

      Ideally, I'd also love to be able to tweak the registration date to some 'X registered Y days ago', but I'm happy to cross that bridge at a later time. At the moment, I'm in desperate need of getting the above code to filter out users with 0 posts, and only pull users -- or rather _a_ user -- with 1 or more posts. If anyone could help, I would be so eternally grateful. As someone whom is only now starting to learn the basics of PHP, I can honestly say that I'm in over my head at this point. I look forward to hearing from you guys and thank you each for reading and looking into my plight. Woe is me! Edit: I am so silly! I should probably explain what the code above _does_ do: the code above does indeed display a random user and provides them with a 'spotlight' area in the sidebar, but it will pull users even with a post count of 0. As explained previous: if it pulled only users with a post count of 1 or more, it would be near-flawless.


Diplay content from custom type as widget or sidebar?

I am wanting to display the title, featured image, excerpt, and read more link for posts from my custom post type in a horizontal manner. Some other things I want to do here is limit the post count to 3. I've looked for plug ins to do this, but all seem to fall a little short. For example, since i want to display these horizontally, I would need a plug in to be able to offset posts. I haven't found one that does all those things. The only one is for the Genesis framework and Im not using that. :( Can someone make a suggestion? I've also tried using a php call `<?php include("recent-portfolio-items.php"); ?>` instead of a widget area, but I'm not a PHP guru so am running into issues with that as well. For an example of what I'm trying to do, visit this link and scroll down to the Portfolio section http://www.streetfiredesigns.com/testsite/ Right now I am just using text widgets to give the look I'm going for.


2 loops in blog homepage

I would like to have to query loops running on my blog homepage:   1. Featured posts on top displaying 3 posts from the category : **"Featured"**   2. Underneath it just the basic loop of wordpress which display the latest (10 or other, whatever is selected within the admin) with "next" and "previous" buttons for archive posts (paged) Important: The top part will display only 3 posts of the **"Featured"** category but the regular blog loop underneath will display **ALL** the posts **including the "Featured" ones** (even if it's a duplication - the featured posts **have to appear also in the regular blog loop** ) it seems prety easy but when I tried it couple of times even using `rewind_posts` it broke the pagination. This is the code I originally used:               // Featured posts section

Featured

                      <?php query_posts('showposts=3&category_name=featured'); ?>      <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
     <a href="<?php the_permalink() ?>"><?php the_post_thumbnail('post-featured'); ?>
<a href="<?php the_permalink() ?>"><?php the_title(); ?>

<?php excerpt('20'); ?>

<a href="<?php the_permalink() ?>">Continue Reading

                 <?php endwhile; else: ?>
Sorry, no posts matched your criteria.
      <?php endif; ?>      <?php wp_reset_query(); ?>
               // Regular normal posts section
       <?php if (have_posts()) : while (have_posts()) : the_post(); ?>

             <?php     $category = get_the_category();     echo $category[0]->cat_name;     ?>

           <?php the_post_thumbnail('post-thumb'); ?>

<a href="<?php the_permalink() ?>">             <?php the_title(); ?>

           <?php include (TEMPLATEPATH . '/inc/meta.php' ); ?>

             <?php excerpt('50'); ?>             ...
           <?php include(TEMPLATEPATH . '/inc/share.php'); ?>           <a href="<?php the_permalink() ?>" class="more">Continue Reading >>

       <?php endwhile; ?>       <?php include (TEMPLATEPATH . '/inc/nav.php' ); ?>       <?php else : ?>

       <?php endif; ?>
      hope someone can help Thanks


How to save user meta on custom admin page

I have removed the edit profile page from WP admin as I don't want users to be able to edit their details as this is a closed intranet and their details are fed from AD. However I do want them to be able to publish their own user description (Biography). So I've set out to add a new admin page to give the user the ability to do that:               add_action('admin_menu', 'sc_stace_user_bio_page');     function sc_stace_user_bio_page() {         $page = add_menu_page( "Your Biography", "Biography", "read", "user-bio", "sc_stace_user_bio_page_content", "", 50 );     }          function sc_stace_user_bio_page_content() {         global $current_user;         get_currentuserinfo();         ?>

Your Biography
             <form action="options.php" method="post">                 <textarea rows="10" cols="100" name="user_description"><?php echo esc_textarea($current_user->user_description); ?></textarea>                 <?php submit_button( "Save", "primary", "submit", true ); ?>             </form>
         <?php     }     ?>      As far as I know I cannot use the Settings API here as this info needs saving into the logged in users meta not into options table. So now I'm stuck as I don't know where the form should be saving to and how to check for form submission the correct way. So where should I be submitted the form to? What nonces if any should I be putting in the form? What do I need to hook into for checking form submission and if correct data is being sent save to user's meta?


CPT Metabox with email notification

I have a custom post type just for contacts, I want to create a metabox with the contacts birthday and have it notify the site admin when it comes up (Or a day/week/month before the date if possible).


URL rewriting for WordPress Network (Multisite) subsite

We have an install of WordPress Network (Multisite) that has multiple blogs running under the url blogs.exampleurl.com where each subsite is blogs.exampleurl.com/site1 /site2 etc... We have a user that already has a URL (www.exampleurl.com/usersite/) and would like to keep his URL but also use our install of WordPress. Can this be done with any settings in WordPress, any plugins, or something else on the server? For clarification, he doesn't want his URL to just redirect to the blogs. URL but instead maintain his URL while being served from the WordPress instance.


I've got a function that auto creates taxonomy terms - Can it auto delete them as well?

I've got this inside my functions.php file.                   function add_product_category_automatically($post_ID) {     global $wpdb;     if(!has_term('','product_relation',$post_ID)){         $cat = get_the_title($post_ID);         wp_set_object_terms($post_ID, $cat, 'product_relation');     }     }     add_action('publish_product', 'add_product_category_automatically');      It creates terms in the 'product_relation' taxonomy when a product is published. Is it possible to also have the terms automatically deleted when the product is moved to the trash? Thanks


Website is slow: advice on optimization

This WordPress-based website i just released is dead slow. I've optimised my theme a lot and get a pagespeed of 91/100 but the first time to byte is the culprit: it takes 8 up to 20 seconds. I've installed W3 Total Cache, memcache, APC, eAccelerator, xCache, but the site keeps being super slow. Server: CentOS 5.7 (x86_64), 2G RAM, CPU: 1 Intel(R) Celeron(R) CPU 2.80GHz Mysql 5.1 PHP: 5.2.7 Apache 2.2


disable defaault wordpress comments from a plugin

I am modifying the facebook comments plugin to my purposes. What I'd like to do is have it remove Wordpress native comments automatically if it is enabled- in fact what I'd really like it to do is use the Wordpress comments settings in the item itself and/or general settings to decide whether it should show or not. Disqus works like this and its just how you would expect a comments replacement system to work by default- I think this plugin should work like that unless you tell it to do otherwise. Does anyone have any ideas how disqus achieves this? D


Custom Post Type Child Pages

I'm getting a 404 page when viewing child-pages of a custom post type. Right now I have a pages (let's call it 'Books') that displays every 'book', and in the menu have other pages listed under Books which are currently giving me a 404 error. Here is my custom post type registration:               $args = array(         'labels' => $labels,         'public' => true,         'exclude_from_search' => false,         'publicly_queryable' => true,         'show_ui' => true,          'query_var' => true,         'capability_type' => 'post',         'hierarchical' => true,         'menu_link' => 5,         'supports' => array('title','editor','thumbnail','author', 'page-attributes'),         'rewrite' => array( 'slug' => __('books', 'sproingcreative') )       );      I've tried removing 'query_var' => true and even setting it to false, and although setting it to false stopped the 404 error, the individual posts within the CPT no longer work. Has anyone had this issue before? UPDATE: Changing the page's slug did the trick, it works fine now!


Change the properties of a custom post type after it's been registered?

The specific use case is that I have a CPT added through a plugin, and I'd like it to be hierarchical, but the post type options are hardcoded into the plugin. Is it possible to change the properties of a custom post type after it's been added via `register_post_type`?


Problems with Bootstrap 3 Carousel Integration

I'm building a theme for the first time, using Bootstrap 3 integrated with Wordpress to do so. I have a carousel partially working. Right now it shows the slides in reverse order, i.e. Slide 3, Slide 2, Slide 1. Then it breaks and goes to a blank screen. This is the code I'm using. Any ideas why this is happening or what I could try to both make it go in the right order and make it loop infinitely?

              <?php $new_query = new WP_Query('post_type=slide&posts_per_page=3');          $i = 1;          while ( $new_query->have_posts()) : $new_query->the_post(); ?>                  <div class="item <?php if ($i == 1) echo 'active'; ?>" >                    <img src="<?php the_field('slide_image'); ?>" >

<?php the_field('slide_caption'); ?>

          <?php         $i++;     endwhile;     wp_reset_postdata();     ?>


WordPress Multisite logout conflict

I have a WordPress Multisite setup with several sub sites. I am having an issue when logging out of one of the sub sites that leaves the user logged into the main site which was the entry point or site by which I logged in. I have an example recorded in this video: http://www.screencast.com/t/fM9prj7KOS I am using a Twenty Twelve theme with minimal plugins -- none of which in the video are affecting any kind of authentication/login (i.e. a membership plugin). This is causing problems when I do activate my membership plugin. I have all members log into a common portal (mysitedotcom/member as in the video) from which they can then easily access all of their network sites nicely. Logging out of any of the sub sites (ones not used to log in initially) does in fact log the user out of the sub site, however navigating back to the original member login portal shows the user completely logged into that particular network subsite/blog. This seems to be a bug. Can anyone else confirm this and help find a solution?


Custom post type yearly/ monthly archive permalinks

I have a custom post type "news" in my Wordpress site. I am using Advanced Custom Fields plugin to add meta data to each post. I want to create an array of news items as an archive:               [2013]         [January] => 5     [2012]         [January] => 20         [February] => 10     [2011]         [April] => 30      I managed to get this working using:                   global $wpdb;         $news = $wpdb->get_results(             "SELECT wp_posts.post_date, COUNT(wp_posts.ID) as count              FROM $wpdb->posts              WHERE              wp_posts.post_type = 'news' AND              wp_posts.post_status = 'publish' AND              wp_posts.post_date <= CURDATE() AND              wp_posts.post_date >= DATE_SUB(CURDATE(), INTERVAL 3 YEAR)              GROUP BY YEAR(wp_posts.post_date), MONTH(wp_posts.post_date)              ORDER BY wp_posts.post_date DESC",               ARRAY_A);              $archive = array();         foreach ($news as $post):             $year = date('Y', strtotime($post['post_date']));                   $month = date('m', strtotime($post['post_date']));                  $month_name = date('F', strtotime($post['post_date']));             $post['url'] = 'NOT SURE ABOUT URL';             $archive[$year][$month_name] = $post;         endforeach;      I need to be able to link to specific years and months using `http://example.com/news/2012/` and `http://example.com/news/2012/10/`. I tried using the plugin Custom Post Type Archives but when I goto `/news/2012/` I get the standard news listing with no filter applied. Here is my Custom Post Type Code               register_post_type('news',        array(             'label' => 'News',         'description' => 'Latest News',         'public' => true,         'show_ui' => true,         'show_in_menu' => true,         'capability_type' => 'post',         'hierarchical' => true,         'rewrite' => array('slug' => '','with_front' => '1'),         'query_var' => true,         'has_archive' => true,         'menu_position' => 120,         'menu_icon' => /assets/img/icon-custom.png       )     );


un-loading https

I'm using this code in functions.php to load https on my events-manager pages:               function my_em_force_ssl( $template ) {         if ( ! is_ssl() && em_is_event_page() ) {             wp_redirect( str_replace( 'http:', 'https:', get_permalink() ) );             die();         }              return $template;     }          add_filter( 'template_redirect', 'my_em_force_ssl', 10 );      Is there a way to unload or revert back to http when leaving those pages?


Localize URL bases

I run a non-English blog. I love that WordPress has been translated to Spanish and currently I use the Spanish translated version of WordPress. One thing that I'd really like to change is the URL structure for my blog. For example, instead of `sitio.com/category/gatos`, I'd like to change the URL to `sitio.com/categoria/gatos`. I know you can set the category base and tag base in Settings/Permalinks, but I'd like to know how to do this in code. Also, I want to translate `search/` to `busqueda/` and `page/` to `pagina/`. I want to translate all of these to Spanish.   * category_base   * author_base   * pagination_base   * feed_base   * search_base   * comments_base I'd like to be able to make these this just within my own theme (that I've made from scratch), that way these changes could be more portable. I've read the WordPress Codex for `WP_Rewrite` and have experimented with `add_rewrite_rule`, but I'm still stuck. Does anyone know where else I could look? **Update:** With this function, your search form can still use `name="s"`, but the user will be redirect to the appropriate location on submit.               function redirectSearch()     {         // Make sure you redirect to whatever your search_base is.         if(!empty($_GET['s'])){             wp_redirect(home_url('/busqueda/').urlencode(get_query_var('s')));         }     }     add_action('template_redirect', 'redirectSearch');


Difference in Get Variable Location

I have noticed that in some instances in WordPress (such as in my custom post types), GET variables appear as following in the URL: www.url.com/events/cool-event?action=edit&message=1 However, in other instances (such as when I am pointing to my login 'virtual' page which I created using the rewrite API), the urls look like this: www.url.com/login/?action=login As you can see, there is a forward slash before the first variable. What is causing this? Which one is the normal way for them to appear? Is there any functional difference? And finally, assuming that it makes sense, how can I make them both behave in a similar manner?   * William ## Update               add_action( 'init', 'add_virtual_page_template' );     function add_virtual_page_template()     {         global $wp, $wp_rewrite;              $wp->add_query_var( 'template' );              add_rewrite_endpoint( 'login', EP_PERMALINK | EP_PAGES );         add_rewrite_rule( 'login/?', 'index.php?template=login', 'top' );              $wp_rewrite->flush_rules();     }          add_action( 'template_redirect', 'add_virtual_page_redirect' );          function add_virtual_page_redirect()     {         global $wp;              $queryvar = get_query_var('template');              if ($queryvar && $queryvar == 'login')         {             include(site_url('wp-login.php'));             exit;         }     }


change the icon of a custom post type in WordPress to use twitter boostrap

Using jquery, the icons of WordPress admin menu have been changed to use the twitter boostrap icons, done such as:               jQuery('#icon-themes.icon32').replaceWith('

 ');      But I have custom post type icons that I want to replace with icons from twitter boostrap. The problem is I am not sure what to target. The source code for one looks such as: (this is for one menu item, which is a custom post type)

         Mini-Feed

Mini-Feed

All Mini-Feeds

New Mini-Feed

      any ideas?


Using the echo command adds unwanted br tags to source

I am making a simple HTML form in a plugin I am writing. I was thinking of using `echo` for all output, but I can't seem to control the formatting of the HTML outputted (for debugging, neat looking HTML, NOT talking about how the page looks to the user). If I have an echo like:                 echo '<sometag>           <otherTag>';      It generates HTML like:                <sometag><br><otherTag>      So I changed the echo statement to:                echo '<sometag>';      echo '<otherTag>';      and got HTML like:                <sometag><otherTag>      Lastly I changed the echo statement to:                echo "<sometag>\n<otherTag>"      But then WordPress turns the `\n` into a `<br>`! Is the only way to have nicely formatted HTML to output the text with HTML outside of php? Or is there a way to get `echo` (or `print`) just output what I send it? OK - I found some code that points to a 'why'. It appears to me that the makers of this theme are using wptexturize and wpautop on all shortcodes, likely assuming that all shortcodes are their OWN (button, ui widget) shortcodes, and having wptexturize work on the shortcodes helps with some theme settings. I can think of perhaps better ways to do this... I am writing a plugin for this theme, and will not be editing the theme, so I think I will tell them to use the [raw] shortcode route. Theme code from /themename/functions/shortcodes/setup.php                <?php      // Remove WordPress automatic formatting      function theme_formatter ($content) {          $new_content = '';          $pattern_full = '{(\[raw\].*?\[/raw\])}is';          $pattern_contents = '{\[raw\](.*?)\[/raw\]}is';          $pieces = preg_split ($pattern_full, $content, -1, PREG_SPLIT_DELIM_CAPTURE);               foreach ($pieces as $piece) {             if (preg_match ($pattern_contents, $piece, $matches)) {                 $new_content .= $matches[1];              }              else {             $new_content .= wptexturize (wpautop ($piece));              }          }               return $new_content;      }           remove_filter ('the_content', 'wpautop');      remove_filter ('the_content', 'wptexturize');           add_filter ('the_content', 'theme_formatter', 99);                     // Enable shortdoces in sidebar default Text widget      add_filter ('widget_text', 'do_shortcode');


Targeting categories in custom fields

I was hoping somebody could help me out with custom fields. I created a custom post type called game-type in WordPress. In this I have the categories "Android", "iOS" and "PC", then within these I have categories for types of games "3D Action", "Classics", "Platform" etc. So an example hierarchy for each post works like this: Games > Android > 3D Action > Post (Game) So far I've managed to call a list of categories using the code: `               $taxonomy     = 'game-type';     $orderby      = 'name';     $show_count   = 0;      // 1 for yes, 0 for no     $pad_counts   = 0;      // 1 for yes, 0 for no     $hierarchical = 1;      // 1 for yes, 0 for no     $title        = '';          $args = array(      'taxonomy'     => $taxonomy,      'orderby'      => $orderby,      'show_count'   => $show_count,      'pad_counts'   => $pad_counts,      'hierarchical' => $hierarchical,      'title_li'     => $title     );     ?>          <ul>     <?php wp_list_categories( $args ); ?>     </ul>`      But this lists all the categories in my custom field. Is there a way to target just the categories in "android"? Your help would be much appreciated. Thanks Site: http://www.sugartree.org.uk/company


Orderby custom field for custome post type

I am trying to order a custom post type called "Teachers" by a field called sort_by. I am not sure why this isn't working. Here is my code:               $args = array( 'post_type' => 'teacher', 'posts_per_page' => 30, 'order_by' => 'sort_by' ,'order'=>'ASC' );     $loop = new WP_Query( $args );     while ( $loop->have_posts() ) : $loop->the_post();         echo '

';         the_title();         echo '
';         the_excerpt();         echo  '
';     endwhile;


Change /add items in menu on the inner sidebar

I have a home sidebar menu of items and I need to add an item (post) so it displays. There is no add button availalble. How do you add another post so it shows on the home inner sidebar menu list


Displaying posts based on category

I recently got some help here on getting a few posts to display in block format. I was wondering if someone could assist me with modifying the code to limit the posts that show up either by category or by tag. I've listed the code below:

     <? $args = array(         'post_type' => 'post',         'posts_per_page' => 4     );          $loop = new wp_Query($args);          while($loop->have_posts()) : $loop->the_post();         echo '';         echo get_the_post_thumbnail($post->ID, 'category-thumb');         the_title( '
', '
' );         echo '';     endwhile;          wp_reset_query(); ?>


Can not pass the value of google pie chart from custom meta box

I am trying to build a google pie chart in my wordpress site based on user input . Hence I have created custom meta box , and use wp_localize_script . Here is what I have done to pass custom metabox value to wordpress .               function pie_load_scripts() {         global $post;         $title = get_post_meta($post->ID, 'title', true);          $telecom = get_post_meta($post->ID, 'telecommunications-it', true);               $business = get_post_meta($post->ID, 'business-professional', true);          $retail = get_post_meta($post->ID, 'retail', true);          $other = get_post_meta($post->ID, 'other', true);          $media = get_post_meta($post->ID, 'media-entertainment', true);          $financial = get_post_meta($post->ID, 'financial', true);          $government = get_post_meta($post->ID, 'government', true);          $educational = get_post_meta($post->ID, 'educational', true);               wp_enqueue_script('pie-script', plugin_dir_url( __FILE__ ) . 'js/3dpiechart.js');         wp_localize_script('pie-script', 'pie_script_vars', array(                 'telecom' =>$telecom ,                 'title' =>$title ,                 'business' =>$business ,                 'retail' =>$retail ,                 'other' =>$other ,                 'media' =>$media ,                 'financial' =>$financial ,                 'government' =>$government ,                 'educational' =>$educational ,             )         );          }     add_action('wp_enqueue_scripts', 'pie_load_scripts');      Here is my Js file ,                 function drawChart() {         var data = google.visualization.arrayToDataTable([                ['Sector', 'Cost'],           ['Telecomunications & Information Technology',       pie_script_vars.telecom],           ['Business Services & Professional',                 pie_script_vars.business],           ['Retail (head office & storefront)',                pie_script_vars.retail],           ['Others',                                           pie_script_vars.other],           ['Media & Entertainment',                            pie_script_vars.media],           ['Financial Services',                               pie_script_vars.financial],           ['Government',                                       pie_script_vars.government],           ['Educational & Institutional',                      pie_script_vars.educational]                   ]);        var options = {           is3D: true,           title: pie_script_vars.title              };      The above code is the modification from google developers site (https://developers.google.com/chart/interactive/docs/gallery/piechart?hl=fr) . Here I also want to set value of the title from meta box , which works fine , but in case of pie chart value it doesn't work .


"edit_published_posts" and "edit_other_post" issue

I need to modify a roles capabilities for post editing:   * User can modify his own post (publish status doesn't matter)   * User can modify others posts (only as long as they are not published) I played around with `edit_posts` \+ `edit_other_posts` \+ `edit_published_posts` but that not work as I expected. Here a schema of what I try to do:                 Modify =>   |own post | other user post     not published |    √    |        √     published     |    √    |        X


Help with Wordpress Query

I'm sort of a noob when it comes to Wordpess; I've only recently started building themes and I've run into a wall. I'm trying to feature 3 different articles at the top of my site using wpquery and for some reason it's only displaying one. I'll include my code below and if anyone can help my figure out what's wrong I would be very grateful! Code included in pastebin: http://pastebin.com/1DB7vent I'm trying to get a setup similar to this: [div class="site_width"] [ul] [li] [a h*ref="FeaturedLink1"] [i*mg s*rc="FeaturedLink1 Featured Image] [/a] [label] [a h*ref="FeaturedLink1"] "Featured Link Title" [/a] [/label] [/li] [Repeat format for two more posts] [/ul] [/div] []'s & *'s included to prevent se from thinking I'm spamming


Getting attributes from custom_post input

I'm having custom field created like that:               function woocommerce_form_field_numeric_2( $key, $args, $value = '' ) {     global $woocommerce;     $defaults = array(     'type' => 'number',     'label' => '',      'placeholder' => '',     'required' => false,      'class' => array( ),      'label_class' => array( ),     'return' => false,      'options' => array( )     );     $args = wp_parse_args( $args, $defaults );     if ( ( isset( $args[ 'clear' ] ) && $args[ 'clear' ] ) )     $after = '

';     else     $after = '';     $required = ( $args[ 'required' ] ) ? ' *' : '';     switch ( $args[ 'type' ] ) {     case "text":     $options = '';     if ( !empty( $args[ 'options' ] ) )     foreach ( $args[ 'options' ] as $option_key => $option_text )      $options .= '<input data="nochange" type="number" name="' . $key . '" id="' . $key . '" value="40.00" min="40" max="80" step="0.5" " ' . selected( $value, $option_key, false ) . 'class="numeric">' . "\r\n";       $field = '
     ' . $args[ 'label' ] . $required . '     ' . $options . '
' . $after;      break;      } //$args[ 'type' ]      if ( $args[ 'return' ] )      return $field;      else      echo $field;       }           woocommerce_form_field_numeric_2( 'cyl-left', array(      'type' => 'text',         'class' => array('my-field-class form-row-wide'),         'placeholder' => __('Enter something'),           'options' => array(        'cyl-left' => 'cyl-left
',           )          ), $checkout->get_value( 'cyl-left' ));              echo '
';       During the process I change the data with jquery:                       $(".numeric").on("change", function() {       $(this).attr("data","changed");       });      And now I would like to validate the custom filed, to being displayed only when `data` is set to changed. How can I achive this ? I've tried like that:                 if (get_post_meta( $order->id,'cyl right', $data != "nochange")){              echo '
'.__('CYL Oko prawe').':   ' . get_post_meta( $order->id,'cyl right', true). '
';       }      and like that                   if (get_post_meta( $order->id,'cyl right',true)){                 foreach($_POST as $key => $value) {         if($data != 'nochange'){        echo '
'.__('SPH Oko prawe').': ' . get_post_meta( $order->id,'cyl right', true). '
';         }}}      but with no expected resault, Is it possible to get `$_POST` > data value ?


Add Piwik Tracking code to page

I use piwik analytics to track the visitors to my website. I recently created a blog on WordPress and wanted to added the same tracking code that I use on the plain HTML webpage. How can I added the tracking script in the php in order to track my blog visitors? thanks!


Can I have the same wordpress site under different url?

Can I run the save a wordpress site under different domain names? Like mydomain.com and mydomain.net ? Where the domain name will NOT change in the address bar of web browser.


How to remove slug from more than one custom post type

I followed this tutorial from WordPress (http://vip.wordpress.com/documentation/remove-the-slug-from-your-custom-post- type-permalinks/) to remove slug from custom post type. Now my question is how to remove from more than one custom post type. Any help would be appreciated!


WordPress edit_user_profile_update update secondary role

I am trying to save secondary role field in user-edit.php which is independent of WP's main roles. I had no problem with saving other custom fields that are unique but for roles (wp_capabilities), it looks like it first saves my roles (I set sleep(10) to check in database in the process) and at the end of request, WP saves main role field which overwrites my previously saved role. Is there any way to order events somehow so my function executes at the very end of request? Here's what I've got so far: Hooks:               <?php     add_action( 'edit_user_profile',        array( $this, 'test_profile_form'));     add_action( 'edit_user_profile_update', array( $this, 'test_save_profile_form' ));      Callbacks:               function hook_save_profile_form($user_id) {             if(!current_user_can("edit_user",$user_id)) {                 return false;             }             $user = new WP_User($user_id);             $user->add_role($_POST['secondary-role']);             //debug             sleep(10);     }


PHP in CSS file?

so I have this in my CSS ...                 #mainnav li:after {     content: url('images/nav-divider.png');     }      obviously I need to have it link to 'bloginfo('template_directory'); /images/nav-divider.png' instead but how do I link that correctly seeing as there is PHP in it? Thanks, Josh


How to add multiple rewrite rules to WordPress .htaccess and delete them separately?

After an intense research without finding the proper answer I decided to ask my question here. I need to add some rewrite rules when activating a plugin in WordPress without existing custom rules being deleted. Example: if I add rules for plugin A, they are written into `.htaccess` (inside the WordPress block). But if I activate another plugin B which also has custom rewrite rules, then the rules of plugin A are overwritten by the rules of plugin B. How I add the rules:               register_activation_hook(__FILE__, 'activatemyplugin');          function activatemyplugin() {        add_rewrite_rule('pdf/([^/]*)$', plugins_url('pdfexport') . '/out/$1', 'top');        flush_rewrite_rules();     }      On deactivation of A or B, all custom rules (of A and B) are removed (replaced by default rules).               function deactivatemyplugin() {         flush_rewrite_rules();     }      How can I add and delete specific rewrite rules, so that previously added rules remain? Every help is appreciated. Thanks in advance.


How to get 1 or 2 specific posts on top of my wordpress blog?

Does anyone know how to get 1 or 2 specific posts on top of my wordpress blog all the time? I mean just like in a forum where you can sticky a post so they are always on top of the other posts. Is this maybe a simple line of code (i am not realy a coder) or does anyone knows a good plugin for this? Any help would be realy appreciated.


echo get_post_meta of all post in a category to fill up a select field

I want to retrieve a specific post_meta of all posts contained in a specific category. I want to build a search form at the top of each category with a select field which would be filled up by the required post_meta of all the post contained in the category the user is currently in. Is this doable? Maybe it's possible with a loop which would look like: `For each post_meta called "City" in all posts contained in category 'X', you must put it in <option value="City's name">City's name</option>` So far, here is what I have been able to do.               <select>     <option value="" selected="selected">Please pick a city below...</option>     <option value="<?php echo get_post_meta($post->ID, 'City', true) ?>">     <?php echo get_post_meta($post->ID, 'City', true) ?>     </option>     </select>      Not much, I know. Any help, please ? Thank you in advance.


Where's the redirect happening?

I've inherited a Wordpress site. Have a ton of PHP experience but only moderate Wordpress experience. Currently the URL: http://iridescentlearning.org/technovation Redirects to another page. My client wants that redirection changed. But I can't figure out where that redirection is happening. The .htaccess file has this...               # BEGIN WordPress     <IfModule mod_rewrite.c>     RewriteEngine On     RewriteBase /     RewriteRule ^index\.php$ - [L]     RewriteCond %{REQUEST_FILENAME} !-f     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule . /index.php [L]     </IfModule>          # END WordPress     RewriteEngine on     <IfModule mod_suphp.c>         suPHP_ConfigPath /home/ab6700/public_html/php.ini         <Files php.ini>             order allow,deny             deny from all         </Files>     </IfModule>      ...which doesn't look to me like it does anything. I've looked through all the Settings and can't see anything that has to do with redirection. And the page it's redirecting to, I can't find anything there that suggests that the page should go to it. I do see one plugin called "Better Anchor Links" but it's been deactivated. So where is this redirection happening from?


Add user managable titles to custom menus?

I am looking for a way to include a user managable title in a menu. Ideally, it will take the place of the first `<li>` object in the output. Any ideas? * * * **Edit** _Clarification_ I am looking for a way to add a header to a menu list, defined by the given name of the menu in the admin panel. So, the code should look a little like this:

 Menu Name

Link

Link

Link

Link

      * * * **Edit** _Further Development_ I have a code block for extracting the name of a menu, based on it's location in a theme, but I can't quite get the HTML layout I want (i.e. add the title to the first `<li>`).               function mf_get_menu_name($location){         if(!has_nav_menu($location)) return false;         $menus = get_nav_menu_locations();         $menu_title = wp_get_nav_menu_object($menus[$location])->name;         return $menu_title;     }


Hyperlinking images on posts to permalink

i have this site with only one image in each post.. how do you turn the posted image to hyperlink to the permalink? Most images are from an external source and is just automatically embedded on each post using a plugin that I use. There are a lot of posts on my site already and it's next to impossible to manually edit each post to link the each image to the post's permalink.. I checked the index.php of my site.. I saw a line for "the content" and when I added an "a href" to it linking to the permalink, it just doesn't work, im not sure why.. please help. thanks!


I want to create a drag and drop image collection in wordpress custom post

In my wordpress add new property (custom post type) page I want a small area where i can add multiple images with standard uploader and then drag and drop to reorder them and then show them on front end. I have seen this kind of functionality working in visual composer for wordpress (check live demo on their website) See this image in which visual compose creates gallery http://snag.gy/QuPjb.jpg In that popup we can add/delete images and drop down to reorder them and its using the standard image uploader of wordpress. I want that funcitnality in my website's custom post type, please guide me how can I create it. I have all of its code but I don't know where to start.


Working on fixing wp-front-end-editor, encountering undefined index

Scribu's Frond-End Editor plugin is brilliant, but throws some Strict errors in debug mode. Since I'm using the plugin on a project, I figured I'd fix the errors. (You can see my changes from the original on my Github). I managed to fix the strict errors (they were all about methods not matching their parents), but my changes resulted in the following error: `Notice: Undefined index: after_widget in \wp-content\front-end- editor\php\fields\widget.php on line 25` and I can't for the life of me figure out why. You're welcome to peruse the code on Github, but I'll reproduce the offending method below:               function wrap( $content, $data = null, $params = null ) {         if ( !$this->check() )             return $params;              $p =& $params[0];              // Text widgets are handled differently         if ( 0 === strpos( $p['widget_id'], 'text-' ) )             return $params;              $wrap = parent::wrap( '', '', array( 'widget_id' => $p['widget_id'], 'sidebar_id' => $p['id'] ) );              list( $before, $after ) = scbUtil::split_at( '</', $wrap );              $p['before_widget'] = $p['before_widget'] . $before;         $p['after_widget'] = $after . $p['after_widget'];              return $params;     }      The thing that confuses me about this is that doing a `var_dump` on `$p` shows that the `'after_widget'` index _is_ defined. Also, commenting out _either_ of the `$p[]` declarations results in the error disappearing. Hopefully we can get this resolved and submit the pull request. (Feel free to download and test my changes from Github, too; I haven't done too much testing yet.)


Widget for Sitewide Editable Content?

> **Possible Duplicate:**   >  Add New Footer Widget Area with Limited Options? I have a banner and a footer that I need to be editable, but I'm not sure if a widget is the best way to accomplish this. It's going to be basic text or an unordered list. As an example I included some code below:

line one

line two

line three

      How would I be able to edit the text "line one" "line two" and "line three" so that it's editable and it will change across the whole website?


Embed 'New Post' Form Inside 'New Post' Form

Is it possible to embed a 'New Post' form for one Custom Post Type inside of a 'New Post' form for another Custom Post Type? When a user adds a new post for the custom type 'Event', they should also be able to add a new post for the custom type 'Session' without leaving the 'New Event' page. The user should also be able to add tags for the 'Session' post only. This is almost the same as adding a custom metabox for the 'Event' post type, with the only exception being that the Event's 'Session' data should be saved as a post rather than as a term.


Merging Wordpress posts from different databases

I have development and production versions of my website (on the same hosting). I want to easily synchronize the content between these versions. On the production website, content is updated daily. I cannot use the XML export function because duplicate posts would be created on the development website. Currently both websites uses different databases, but if there is a solution that allows for usage of only one database I gladly will go through it.


Changing old email to new email, lost the password

Help! I have been accepted to write a blog for our local newspaper, The Rolla Daily News, in Rolla, MO. I cannot access my wordpress.com blog. We moved from a rental house in the country to a new house inside the city limits of Rolla, and that meant having to get a new email address. I also cannot remember my password, and as the old email address has been shut down, wordpress can't send me my password via email. Should I cancel my blog and restart up a new one? Thanks for your help.


Add X meta box inputs based on form at top of meta box, how to do it right?

I am setting up a meta box that controls the number of ingredients for a recipe. As each recipe will have a different number of ingredients I decided to use a simple text input and button to set the number of ingredients and have jQuery dynamically add the inputs for that "X" number. I know I need to use jQuery form but am unsure of how to return the html into the meta box correctly. I have a response div set up but not sure how to handle the html. Can i pass the value from the text input into a php function that uses a for loop to print out all the inputs for the ingredients? Or do I need to print all of the html with jQuery? Hope that makes sense. Thanks! my jQuery that works:                   jQuery('#add-ingredients').click(function(event){             event.preventDefault();                                                     var num = jQuery('input:text[name=_num_ingredients]').val();                  var sections = '';             for(var i=1;i<=num;i++){                      section = '
\n';                 section += '
\n';                     section += 'Amount: \n';                     section += '<input type="text" name="_ingredient_amount_' + i + '" /> \n';                 section += '
\n';                 section += '
\n';                     section += 'Measurement: \n';                     section += '<input type="text" name="_ingredient_measurement_' + i + '" /> \n';                 section += '
\n';                 section += '
\n';                     section += 'Ingredient: \n';                     section += '<input type="text" name="_ingredient_name_' + i + '" /> \n';                 section += '
\n';                 section += '

\n';                 section += '
\n';                      sections += section;             }//end for                  //add the new input sections             jQuery('#ingredients').html(sections);             //show the ingredients inputs             jQuery('#ingredients').show('slow');                  return false;                });      But now I can't figure out how to save the meta data correctly. Here's my for loop:                   //loop through all ingredients and update them accordingly         for($i=1; $i<=$num; $i++):                  $amt = '_ingredient_amount_'.$i;             $meas = '_ingredient_measurement_'.$i;             $name = '_ingredient_name_'.$i;                  //set ingredients array for each iteration             $post_meta['_ingredient_amount_'.$i] = $_POST['_ingredient_amount_'.$i];             $post_meta["{$meas}"] = $_POST["{$meas}"];             $post_meta[$name] = $_POST[$name];                  //update meta data             foreach( $post_meta as $key => $value ):                 if( $value ):                     if( get_post_meta( $post_id, $key, FALSE) ): // If the custom field already has a value                         update_post_meta( $post_id, $key, $value );                             else: // If the custom field doesn't have a value                         add_post_meta( $post_id, $key, $value );                     endif;                 else:                     //delete_post_meta( $post_id, $key ); // Delete if blank                 endif;               endforeach;               endfor;      I know I am missing something in the syntax to get the $_POST values. Any ideas? EDIT------------------------------- I was failing to pass the $post variable into my function - silly me. Now it all works correctly. Thanks for all your help!


JQuery prepend a function

I am trying to see where I went wrong with this code. I was trying to prepend the avatar and user meta above the admin menu. I get header already sent messages as well since the code is just right under the body tag.               function profile_script() {     echo '<script type="text/javascript">     /* <![CDATA[ */     (function($) {         $("#adminmenu").prepend($menuprofile);     })(jQuery);     /* ]]> */     </script>';     }     add_action( "admin_footer", 'profile_script' );


How to build a fool proof AdSense revenue sharing model?

I have 5 author levels in my WordPress site. Levels are calculated using points                - level 1      - level 2      - level 3      - level 4      - level 5      Authors getting impressions based on author levels like this.                - Level l => 50%      - Level 2 => 55%      - Level 3 => 60%      - Level 4 => 65%      - Level 5 => 70%      As of now I'm using code like this..               $random_number = mt_rand(1,100);     if ($author == 'level1' && $random_number < 50) {         $adsenseid = 'author adsense id';     } elseif ($author == 'level2' && $random_number < 55) {         $adsenseid = 'author adsense id';     } elseif ($author == 'level3' && $random_number < 60) {         $adsenseid = 'author adsense id';     } elseif ($author == 'level4' && $random_number < 65) {         $adsenseid = 'author adsense id';     } elseif ($author == 'level5' && $random_number < 70) {         $adsenseid = 'author adsense id';     } else {         $adsenseid = 'admin adsense id';     }      The above code depends on random number. So I think it's not fool proof way. Can someone help me to do it in a perfect way? Maybe using `usermeta` table.


Combining RSS Feeds and Sorting with fetch_feed

I'm trying to create a feed of the most recent 10 posts from 5 different feeds all combined into one list. I found a way to combine the feeds but have not been able to easily limit them to 10 and sort them by date. Can someone point me in the right direction? Thanks!!!               <ul>     <?php $rsslist = array(     'http://www.nrel.gov/news/press/rss/rss.xml',     'http://www.pewenvironment.org/rss/campaigns-8589935316',     'http://www.ashrae.org/RssFeeds/ashrae.xml',     'http://www.districtenergy.org/blog/category/idea-activity/feed/',     'http://www.districtenergy.org/blog/category/industry-news/feed/'      );          $feedlist = array();     foreach ( $rsslist as $rssurl ) $feedlist []= fetch_feed( $rssurl ); /* store in feed array for later access */          $current_item_cycle = 0;     while ( sizeof($feedlist) ) { /* while feedlist is not empty */               foreach ( $feedlist as $index => $feed ) { /* cycle through each feed */                  if (!$item = $feed->get_item($current_item_cycle++)) unset($feedlist[$index]); /* if feed has not more items unset */                  else /* echo it out */ { ?>                 <li>                 <?php echo $item->get_date('j F Y | g:i a') . $item->get_permalink(); ?>                 </li>             <?php }         }     } ?>     </ul>


What is the proper way to add a required field to a post type?

So I created a CPT that has a few required fields in a metabox. My metadata is being saved through the save_post hook but from I can find via my googlefu there is no way to stop the saving of the post from this hook. Currently I'm stopping the submission of the form using javascript but I would also like to have a server side solution for this. I guess I have a few questions:   1. Why was Wordpress developed so you can't stop the post submission?   2. What is the accepted way to do this?


Wordpress not displaying themes in the wp-content/themes folder

I'll do my best to explain this but its weird to say the least. So the two default themes (twenty ten and twenty eleven) appear under the Appearance>Themes tab in the wp admin. However, if I add one new theme to wp-content/themes (even if its just an empty folder) all of the themes fail to show up on the Appearance>themes tab, except for the theme currently in use. Anyone have any ideas? \--This is on a LAMP server (Ubuntu 12.04).


Check IF single OR multiple custom data has been entered

I'm building a single template right now for a custom post type. I'm wondering if there is a way to check if either at least one or multiple of the custom values has been entered so I can display the div accordingly. Basically, I want to display the div it has anything filled out, if it is left blank then don't show it. Is this possible? Here is a sample snippet I have:               <?php IF STAEMENT HERE ?>

             <?php if(get_post_meta($post->ID, 'sermon_video', true)) { ?>
<a href=" <?php echo $post_meta_data['sermon_video'][0]; ?>">Video
             <?php } ?>             <?php if(get_post_meta($post->ID, 'sermon_audio', true)) { ?>
<a href=" <?php echo $post_meta_data['sermon_audio'][0]; ?>">Audio
             <?php } ?>             <?php if(get_post_meta($post->ID, 'sermon_document', true)) { ?>
<a href=" <?php echo $post_meta_data['sermon_document'][0]; ?>">PDF
             <?php } ?>

     <?php ENDIF ?>


display posts with same taxonomy term

I'm trying to display 5 related posts in the loop, those related posts being posts that share the same taxonomy value. e.g. I have a custom taxonomy set up called `venues` thus each post has a `venue` taxonomy value assigned to it, so in each post I want to display 5 others posts that share the same taxonomy value (i.e. are at the same venue).   The code I have so far doesn't work quite right:               <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>     <?php     $custom_terms = get_terms('venues');          foreach($custom_terms as $custom_term) {         wp_reset_query();         $args = array('post_type' => 'listings',         'posts_per_page' => 5,             'tax_query' => array(                 array(                     'taxonomy' => 'venues',                     'field' => 'slug',                     'terms' => $custom_term->slug,                 ),             ),          );               $loop = new WP_Query($args);          if($loop->have_posts()) {                  while($loop->have_posts()) : $loop->the_post(); ?>
<?php the_title(); ?>
                  <?php endwhile;          }     }     ?>     <?php wp_reset_query(); ?>     <?php endwhile; endif; ?>      It is successfully showing 5 posts, but they are just five posts from the same post type and not 5 posts that share the same taxonomy value in the loop. Any suggestions would be greatly appreciated!


Link posts to pages for breadcrumbs

Is there a way of linking custom post types to pages. I am looking to create breadcrumbs for the posts. The posts are summarised on individual pages e.g. golf, tennis, football etc.. So the Breadcrumb Structure inside the post will be: Home / Tennis / "Post Title" When clicking on Tennis - it should lead to the Tennis page I have created which summarises all tennis events.


List users by sum of all their posts' custom field values

So I can do this by user, individually, but I can't figure out how to put it in a foreach loop. What I want to do is output something like this: Author, Miles Where miles is the sum of every single post that contains the custom field miles, associated with that author. And then list them from greatest to least. My code to do this when the user is viewing their own mileage looks like this:                   <?php             //get current user             global $current_user;             get_currentuserinfo();             // build query of ids by user             $userPosts = get_posts(array('author' => $current_user->ID, 'post_type'=> 'miles')); //change this             // loop to create array of ids by user             foreach ($userPosts as $post) {                 setup_postdata($post);                 $ids[] = get_the_ID();             }             $idList = implode(",", $ids); //tun this crap into a list                  $meta_key = 'miles';//set this to your custom field meta key             $allmiles = $wpdb->get_col($wpdb->prepare("                                               SELECT meta_value                                                FROM $wpdb->postmeta                                                WHERE meta_key = %s                                                AND post_id in (" . $idList . ")", $meta_key));             echo '
You\'ve completed ' . array_sum( $allmiles) . '
';  ?>      I'm not sure how to replicate this, so it happens for each author, in a list format... thoughts??


Retrieving Meta from Image Attachment

I currently have added a meta box to the media library popup using the following:               // ADD CUSTOM INFO INSIDE THE MEDIA LIBRARY     function AddLibraryFields( $form_fields, $post ) {              $Added_META=get_post_meta($post->ID);               // SPEED INPUT         $Speed=$Added_META['Speed'][0];              $NEW_form_fields['Speed']=array(            'value' => $Speed ? $Speed : '',             'input' => 'html',             'label' => __('Speed'),         'html' => "<input name='attachments[{$post->ID}][Speed]' value='" . $Added_META['Speed'][0] . "' />");             return array_merge( $form_fields, $NEW_form_fields );     };           add_filter( 'attachment_fields_to_edit', 'AddLibraryFields', 10, 2 );      I then save the information in the new fields using:               // SAVE CUSTOM MEDIA LIBRARY FIELDS     function MediaLibrarySave($attachment_id){         // SAVE SPEED         $Speed=$_REQUEST['attachments'][$attachment_id]['Speed'];         if(isset($Speed))update_post_meta($attachment_id, 'Speed', $Speed);     };           add_action( 'edit_attachment', 'MediaLibrarySave' );      All of this seems pretty straightforward, but I'm still really new to this. The above seems to work great, save the info when changed and is specific to each image. Now, I need to be able to access the information inside the SPEED meta field I added, when the user inserts it into the post (I'm assuming this would be the best place to piece it up and convert it into a data-attribute to feed to a jquery plugin?) Here's the function I currently have, but I can't seem to echo the speed meta?               function InsertToPost( $html, $attachment_id, $attachment){         $attachment = get_post_meta($attachment_id, 'Speed');              // WOULD USE THE SPEED SETTING HERE TO CONSTRUCT A NEW <IMG STRING WITH DATA-SPEED         // OR SOMETHING SIMILAR....                  return $html;     };           add_filter('media_send_to_editor', 'InsertToPost', 10, 3);      Basically, I'm wanting to add multiple meta fields to the media library editor so that I'm able to tag each image (like you would with jQuery.data()) and then later retrieve that information and alter it into a single data-attribute for use inside my plugin. data-plugin='{ "speed" : 500 }' Hopefully I'm going about this the right way with the media_send_to_editor hook, but I just can't manage to retrieve the attachment meta from there....


Widget options get

How to get widget options? I've tried like this, like seen in the other question "Using widget options outside of the widget":               $w=get_option('widget_wp_mywidget');         $one=$w[2]["myval"];         $two=$w[2]["myotherval"];      But I am not quite sure why this [2] is dynamic and i can't rely on it, so how to get exact values of the array the right way?


Update wp-config.php and lost pages

I recently made a small change to my `wp-config.php` by adding a memory limit line on a local version that didn't have the correct db settings. When I uploaded it, the db connection obviously broke. After I corrected the db settings and re-uploaded the `wp-config.php`, I was greeted with the installation page. Now all my links are broken, even after refreshing the permalinks. However, all the data is still in my db. How do I reconnect all my pages to the db so that I don't loose any settings?


Nice URLs for a Custom Post Type List with a Shared Custom Taxonomy?

_( **Moderator's note:** Title was "Convert into nice URL a shared custom taxonomy URL with a query string value")_ I have a custom taxonomy template: `taxonomy-country.php` used by two (2) Custom Post Types: `'event'` and `'contact'`. I would like to set up pages to display, for example:   * _"All Costa Rica Contacts"_ , and    * _"All United States Events"_ These URLs current give me those lists:   * http://mytestsite.com/country/costa-rica?post_type=contact   * http://mytestsite.com/country/united-states?post_type=event But I would like to implement those URLs as nice URLs like this:   * http://mytestsite.com/country/costa-rica/contacts/   * http://mytestsite.com/country/united-states/events/ Or even better, something like:   * http://mytestsite.com/contacts/country/costa-rica/   * http://mytestsite.com/events/country/united-states/


Absolutely print script in footer

I am looking for a solution to printing a Javascript include in the footer of WordPress front-end, and I know there are options for this. However, what would allow me to do so with these in mind:   * Will print in footer no matter what theme is used.   * Cannot be overwritten   * Cannot be removed/filtered    * Will work on versions 3.0-3.8+ This will be done by a plugin. Looking forward to your suggestions. Thank you * * * I understand how this need would come off as unfriendly, but this is something that will be placed on limited hosted wordpress installs and is a condition that is agreed to. So this is a legitimate need to prevent removal.


How to move featured image to the top of the list?

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.


Bootsrtap carousel for content slider

Below is the code for content slider using Bootstrap carousel. The problem is that it is only displaying one post from the featured category. I realize that is because of the way I have it offset. I have it offset like that because otherwise it overlaps the 1st post overtop of the 2nd post (on every other slide). How can I make this display correctly?

         <?php             $featured_query = new WP_Query(array('category_name' => 'featured', 'post_per_page' => 2, 'offset' => 0));             if ($featured_query->have_posts()) :         ?>
             <?php                  while ($featured_query->have_posts()) : $featured_query->the_post();             ?>

<?php the_title(); ?>

<?php the_excerpt(); ?>

Sign up today

             <?php wp_reset_postdata(); ?>
                  <?php endwhile; ?>
          <?php endif; ?>          <?php             $featured_query2 = new WP_Query(array('category_name' => 'featured', 'post_per_page' => 1, 'offset' => 1));             if ($featured_query2->have_posts()) :         ?>
             <?php                  while ($featured_query2->have_posts()) : $featured_query2->the_post();             ?>           <img data-src="<?php  ?>" alt="Second slide">

<?php the_title(); ?>

<?php the_excerpt(); ?>

Learn more

              <?php wp_reset_postdata(); ?>
                 <?php endwhile; ?>
         <?php endif; ?>


Remove title attribute from images

I'm looking for a way to remove the _title_ attribute from images, preferably through using a hook or a filter. Most clients don't bother giving images a proper title, thus eliminating the purpose of this attribute. I prefer no tooltips to random, non-descriptive ones.


Homepage not loading, all other pages loading

I've made a small website using WordPress. I've been facing a problem since quite long - my homepage is either extremely slow to load, or doesn't load at all. But all other pages of my website load at a decent speed. I tried contacting my hosting services provider (GoDaddy), but they replied that the home page resolves correctly without any errors on their side. I tried disabling plugins too, but no help. I don't know where else to look, I'm not much of a pro. My website: DoubleRoot


Fatal error: Call to a member function query() on a non-object 3.6.1

I am using function query() and get_results in my plugin code but, it gives me this error: "Fatal error: Call to a member function query() on a non-object". I have this lines of code:               class Dynamic_form {              function product_category(){             global $wpdb;             $TablePressData = $wpdb->query(                     "                         SELECT post_title                         FROM $wpdb->posts                         WHERE post_type = 'tablepress_table'                     "                 );             return print_r($TablePressData);         }     }      I am using version 3.6.1 (My client already using the version so I'm afraid of updating it).


Profile picture in registration form WordPress

I have custom built registration form and i want an option were in a user can upload and display his/her image as a profile picture. Now once a user is registered and have uploaded the profile image then in that case if the user comment on a blog post on the same website then the same profile picture will be displayed. Can you give a script for the same.


Wordpress blog fails to open

When I try to view/access my blog I get the following message.... Just wondering if anyone has any ideas as to the cause and the solution? > Warning: require(/home/photogian/room2850.com/wp-includes/post-template.php) > [function.require]: failed to open stream: Permission denied in > /home/photogian/room2850.com/wp-settings.php on line 119 > > Fatal error: require() [function.require]: Failed opening required > '/home/photogian/room2850.com/wp-includes/post-template.php' > (include_path='.:/usr/local/lib/php:/usr/local/php5/lib/pear') in > /home/photogian/room2850.com/wp-settings.php on line 119


Controller functionality - User not logged in/ redirect to registration page (not wp_login)

I have a site **here**... If a user clicks on **Submit an Event** or **Send an Article** , they are re- directed to a 404 page because I have it set up to make the page private. What I want to do is if the user is logged in, it goes to the correct page. But if the user isn't logged in, then they get directed to **this registration page**. I don't see any way to do this withing the settings of Wordpress. Thoughts?


Is it right way to create shortcode?

I want to create a shortcode, but it creates empty `<p>` tags in the output. I'm using the following code to avoid that problem, however I'm not sure if this is correct way. I have read that if shortcodes are added incorrectly, they create problems with WordPress core functionality, so please advice if the following method is correct.               function run_my_shortcode( $content ) {         global $shortcode_tags;         $original_shortcode_tags = $shortcode_tags;         remove_all_shortcodes();          add_shortcode( 'box', 'my_shortcode' );          $content = do_shortcode( $content );         $shortcode_tags = $original_shortcode_tags;          return $content;     }      add_filter( 'the_content', 'run_my_shortcode', 7 );          //output the shortcode content     function my_shortcode( $atts, $content = null ) {            extract(shortcode_atts(array(             'title' => ''            ), $atts));              $output = '';         $output .= "
";              if (!empty($title)){             $output .= '
'.$title.'
';         }              $output .= '
'. do_shortcode( $content ).'
';         $output .= '
';              return $output;      }     add_shortcode( 'box', 'my_shortcode' );


conditional logic for front-end custom field edits

I'm just starting to learn php/js and would like some recommendations on the best way to setup my logic: Goal- Display the value in a custom metafield in the custom post type. If the user is the author of the page, display an edit button that will reveal an input field. This input should let the user(author) to update the custom field(metabox) from frontend. The following code i wrote works, but seems sloppy, especially when since i plan to repeat it several times in the template for many custom fields. still just beginning to learn this.               <?php      /* check if POST 'leadcandidate' has no value and set var $nersi by custom field in database, or by POST if it has a positive value */     if(empty($_POST['leadcandidate'])){         $nersi = ($meta_values[_dtm_lead_candidate][0]);     }     else {         $nersi = $_POST['leadcandidate'];     }          /* check if user is author of custom post type */     global $current_user;     get_currentuserinfo();          if (is_user_logged_in() && $current_user->ID == $post->post_author)  {         echo '<button id=btn3>Edit me</button>';         /* input field will be hidden and revealed on button click with JS */         /* add $nersi as vlue of input so user starts from seeing what current value of field is */         echo '<form method="post" action=""><input type="text" name="leadcandidate" value="' . $nersi . '"><input type="submit"></form>';     }     /* this updates the database that stores the metafield */     update_post_meta(get_the_ID(), '_dtm_lead_candidate', $_POST['leadcandidate']);     ?>     /* display the value of metafield (to everyone) */
<?php echo 'Lead Candidate:' . $nersi; ?>


is there a way to pass a parameter to a add_menu_page function?

I am trying to create a dynamic way of adding admin pages and submenus with different capabilities. So the first way i thought of which works BTW but is ugly is having all the pages in 1 folder and name them something like 0.manage_options.pagename.php Then get all the pages and simply run through the array and use `explode()` on the name like so:               $classLib = glob(SERVICES.'/*.php');     $pagesArray = array();     $mainMenu = '';     foreach($classLib as $className) {         $tempPages = explode('.',str_replace('.php', '', basename($className)));         /* a function to get nice clean name */         $menu_title = $this->get_admin_menu_clear_name($tempPages['2']);              $pagesArrayTemp[$tempPages[0]] = array(             'page_title' => $tempPages['2'],             'menu_title' => $menu_title,             'capability' => $tempPages['1'],             'menu_slug' => $tempPages['2'],             'url' => 'pluginame/services/'.basename($className),         );     }             $pagesArray = array();     foreach($pagesArrayTemp as $tempPage){         $pagesArray[] = $tempPage;     }     add_menu_page('pluginame', 'Main', $pagesArray[0]['capability'], $pagesArray[0]['url']);          foreach($pagesArray as $page){         add_submenu_page('pluginame', $page['page_title'], $page['menu_title'], $page['capability'], $page['url']);     }      this works however the URI of the page are ridiculously ugly. So i am trying to find an alternative way. without creating a function for each page .... is there a way to pass a parameter to `add_menu_page` or `add_submenu_page` function ? like:               add_submenu_page('something', 'something', 'something' , 'manage_options', 'something', array($this, 'option'));          function option($premission, $pageURL){         if ( !current_user_can( $premission ) )  {         wp_die( __( 'You do not have sufficient permissions to access this page.' ) );     }         require_once($pageURL);     }      maybe a filter or something alike ? Thanks in advanced.


Why do Wordpress rewriites seem to work differently for posts vs pages?

I am creating some simple rewrites in my functions.php file in my WordPress installation:               add_rewrite_rule('product1/faqs/?', 'index.php?name=product1-faqs', 'top');       I've noticed that if you hit "product1/faqs" in the browser, it successfully displays the content of "product1-faqs" but keeps the url as product1/faqs (which is desired) but only if it is a POST. If I try this same technique but on a PAGE, the browser URL flicks to "product1-faqs" (undesired!) Why is that? I don't want have to limit ourselves just to posts for the sake of rewrites working as desired...


Staging/production deployment on WordPress MultiSite

Looking to create a staging process for changes to our WordPress MultiSite. We are running several different templates between the sites in our network, but we'd love to use a stage site to test changes to those sites in the network. We're running 3.7.1. Our themes were built in-house. We run a number of plugins, some network-wide, some on certain sites in the network. We've set up a directory on the webhosting server to run it called /staging. We're not sure where to begin, though.


301 redirect instead of 404 when URL is a prefix of a post or page name?

hey all! i have an odd problem with URL routing. when i request a URL that doesn't exist, e.g. http://localhost/foo, wordpress correctly returns a 404. however, if that URL is a prefix of a post or page name, it instead returns a 301 redirect to the post or page. for example, if i have a post on 10/1/2010 named Food Post, it will return a 301 with Location: http://localhost/2010-10-01_food_post (my permalink structure). likewise, if i have a page named Food Page, it will return a 301 with Location: http://localhost/food_page. you can see this in action on my live site, http://snarfed.org/ . e.g. http://snarfed.org/foo redirects to http://snarfed.org/2009-10-30_food_highlights . turning off permalinks (ie switching to "default") fixes it, for both posts and pages, but naturally i don't really want to do that. i see this on three different installations, all wordpress 3.0.1 and apache 2.2, two ubuntu lucid/mysql 5.1 and one freebsd 7.3/mysql 5.0. i've deactivated all plugins and removed everything from my .htaccess except the lines for wordpress below, verbatim, but no luck.               RewriteEngine On     RewriteBase /     RewriteRule ^wordpress/index\.php$ - [L]     RewriteCond %{REQUEST_FILENAME} !-f     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule . /wordpress/index.php [L]      thanks in advance...


woocommerce stored variable

In wordpress, all information can be retrieved via `$post` or `wp_query`, in woocommerce, is there something similar? I want to display information of each product, on a page next to the picture. I have two questions.   1. How can i get to know, which variable does woocommerce uses to store the data.   2. In General, if we want to know the meta of any post,page, how can we pull it aganist each id, where id is generic (we don't know, its dynamic like `$post->ID`)


Query posts with numeric meta values within a given range

I'm building a rental agency's website with WordPress. I'm having difficulties finding a good way to store an apartment's availability in meta fields. Specifically, enabling visitors to find apartments available within a given date range. I figured I would have the agency select which dates an apartment is unavailable in the post editor. My first guess was to store the dates in a single string. For an example listing that is unavailable from 5 January through 7 January I would keep a single meta record like so:               update_post_meta($post_id, "listing_unavailable", "/20140105/20140106/20140107/");      Now when I would look for a listing available from 6 January through 11 January...               $arrival_date   = 20140106;     $departure_date = 20140111;      ...I would run the following meta query:               $meta = [];          for($i = $arrival_date; $i <= $departure_date; $i++)         $meta[] = array(             "key"     => "listing_unavailable",             "value"   => "/".$i."/",             "compare" => "NOT LIKE"         );          $query->set("meta_query", $meta);      The meta query will return any post which has no unavailable dates within the given range. Perfect! However, WordPress adds one `JOIN` for each meta query, so now we're very limited in date range. I think SQL supports up to 61 `JOIN`s and I have a lot of other fields visitors can filter on. So I would only be able to select a range of 2 or 3 weeks before I'd get a `JOIN` limit error. So then I figured, maybe I should add the unavailable dates each as a separate value. For example, again from the 5th up to the 7th:               delete_post_meta($post_id, "listing_unavailable");     add_post_meta($post_id, "listing_unavailable", 20140105);     add_post_meta($post_id, "listing_unavailable", 20140106);     add_post_meta($post_id, "listing_unavailable", 20140107);      Now I imagine a meta query for 6 January through 11 January would look something like this:               $meta = array(         "key"     => "listing_unavailable",         "value"   => array($arrival_date, $departure_date),         "compare" => "NOT BETWEEN",         "type"    => "NUMERIC"     );      This doesn't work though. The visitor will now still find the example listing because 5 January is outside of the `"NOT BETWEEN"` range, deeming the example listing a valid result. I can't seem to think of the right setup to tackle this issue using standard WordPress functions, without making the SQL query too heavy. Any ideas or suggestions?


Why do all Gallery functions return null for me?

This is how I'm creating new galleries:   * I start with making a new post.   * then I click on `Add Media > Create Gallery`   * after that I select a few images from Media Library (let's say 3 of them).   * and last click on `Create a new gallery` After that the contents of my new post look like:               [gallery ids="1,2,3"]      Now I can see a neat beautiful gallery on my post page: ![enter image description here](http://i.stack.imgur.com/0b5oI.png) The point is:   * I don't want this gallery to be shown.   * I want to get URLs of these images to do something else with them (let's say, a custom slider). # 1\. Hiding the Gallery. **Additional question, not so important, I need help with 2. mainly** I guess it's quite easy to hide the gallery with CSS (any other ideas, because I don't like this one that much? of course I want the shortcode to still be visible in text editor). In reality I'll be using this on a CPT only so maybe there is some way of disabling galleries for CPT? I want the shortcode to still be in text editor though. # 2\. Getting the data from Gallery. Now, there is something really wrong. I've checked it on Twenty Thirtheen and it works, but somehow doesn't with my theme.               $galleries = get_post_galleries_images( $post );     var_dump($galleries);      This code displays all the data about above images on Twenty Thirteen but in my theme I'm getting:               array(0) { }      And there's what it's supposed to display (and it does in other themes):               array(1) { [0]=> array(3) { [0]=> string(27) "http://url/to/the/image.jpg" [1]=> string(27) "http://url/to/the/image.jpg" [2]=> string(27) "http://url/to/the/image.jpg" } }      This is how my index.php looks like:               <?php get_header();?>          <?php get_template_part( 'loop' ); ?>     <?php get_footer(); ?>      single.php:               <?php get_header(); ?>         <?php get_template_part( 'content-single' );  ?>     <?php get_footer(); ?>      content-single.php:               <?php         // I've also tried with while (have_posts()) : the_post();        $galleries = get_post_galleries_images( $post );        var_dump($galleries);     ?>      I've been trying every possible way and I'm never getting the right results. Any ideas what's wrong?


How can I get a comment ID on Submit?

I've added an attachment field to my comment form. It stores the files on Amazon AWS and writes the URL, user ID, post ID, and a few other things to a custom table. I'm having some difficulty getting the comment ID in order to properly associate the attachment with the comment. Is there a good way to get the comment ID as it is being written? I've looked over the documentation and cant seem to find anything that would get my comment ID on submit.


Add class to before_widget for all widgets with a dropdown and a counter

Some predefined widgets offer the option to use a `select` element (dropdown) and/or a counter after each entry. How can I add the CSS classes `widget-with- dropdown` or `widget-with-counters` to these widgets? There are already solutions for custom widgets, known sidebar ids or positions, but I have to inspect the parameters for the current instance, and I want to catch all possible positions or widgets (if they follow the WordPress naming scheme).


exclude parents from the_terms

I'm using this function to get the categories linked to the post:               the_terms($post->ID, 'portfolio-type', '
'.__('Categories:','om_theme').' ', ', ', '
');      the result is this: > Categories: 16 Max, Capacity The category **Capacity** is parent of **16 Max** category. I'm looking to exclude parents so the result would be: > Categories: 16 Max I appreciate any help!


Permissions on upload directory

I've been working with a clean WP download on my local host. I was uploading images and other files with the Media Admin Panel without changing any permissions. Suddenly, I see that I can't upload files anymore, and it seems to be a permissions problem, because I've tried with `777` permissions and it's working. So I've read about it at Changing_File_Permissions. And I've found out that all files (and folders) must have FTP user as owner, but I have not any FTP access in my local host. And don't understand why it should work. Is not the user the server user `www-data` also when accessing with Admin Panel? I know that the user has some rules for the DB management, but not for files! Anyway, I've tried creating a new user in my local host named like the WP user, but neither works. And I can't understand how could it work before. Any suggestion? The only way I see is to change permissions on `upload` folder every time that I want to upload a file, but It would be a time wasting.


Stress testing WordPress

We are going to launch a community site with 100K posts, 100K comments, 10K terms, 5 users ( all admin/editorial), and approx 500K recs in the wp_postmeta. Site may grow with a larger author base and we hope it will grow to become a much bigger site... At this time, I would like to know how would WordPress behave when the above numbers reach the 10 times the current fold, that is 1M posts, 1M comments, 100K terms, 500 users, and approx 5M recs in the wp_postmeta. What tools can I use to put this many records into a WordPress install? My migration routine takes about 10 hours to complete to put 100K posts into WP. I must find more efficient ways to 1M records! I know WP can handle fairly large database content and WordPress.com is the greatest example for that. However, those guys have of a ton of servers... In my case, I have what I have. I'm curious to see/experience how the admin dashboard would load and how the front page ( with multiple loops ) behave... Any ideas/tools towards this goal is greatly appreciated... Of course, once I have that many recs, I will be needing a stress testing tool but I think I can find utilities for that. We are using IIS 7 and we cannot switch to LINUX for legacy code reasons anytime soon.


What action/filter/function determines "current" class in WP Admin Menu

I have created a submenu page for the Media List Table. The link actually points to a custom view I have created called Resources. I am looking for the correct location where the Admin menu determines what page(s) are highlighted as "current", and cannot seem to find where I could access this.               add_media_page( __( 'Resources', ZG_TEXTDOMAIN ), __( 'Resources', ZG_TEXTDOMAIN ), 'read', 'upload.php?resources=1' );      Here is an image of the Resources menu item being clicked, the URL reading as `/wp-admin/upload.php?resource=1`, but the menu is obviously not being highlighted properly. ![enter image description here](http://i.stack.imgur.com/aq3Rv.png) Quite an odd request, as it's not it's on page, but the current path does match the menu slug, so I'm not seeing where the issue lies.


URL rewrite of independent plugin?

I'm currently developing a more complex plugin for WP which can't be hooked up to the WP-API itself (Custom Post Types doesn't fit my requirements). Of course I use the API alot, because the data is administered through WP backend (rendering own forms and lists). I'm stuck with the rewrite options, taxonomities and need just a little hint, how to get the thing working. What I do have for now is               www.example.org/page/?aid=281&kid=104      What I'd like to achieve is               www.example.org/page/some-name/      The vars are already stored in query_vars so far. Should I try to register a rewrite rule (because 'page' is rendered through WP) and get the things going or should I simply modify the .htaccess? Any help is much apreciated!


Can't see custom field after the Loop

I have created a loop to show some products on my wordpress site and they seem to be working fine they reel out the products however if I place one of custom fields after the loop it doesn't show. I know its not an issue with the custom field itself as it works fine if I put it above the loop. Does anyone know where I could be going wrong? Here is my code: http://pastebin.com/SVxYK0XP Thanks