How to count post meta key values for all posts in database

In my post meta data I have the following 'key' for every post: "image_details" a typical value of which is an array such as:               a:3:{s:23:"info_window_bg_image_id";s:3:"128";s:12:"colour_start";s:7:"#000000";s:10:"colour_end";s:7:"#b7b7b7";}      In the above example - `info_window_bg_image_id` is equal to 128 Ideally I would like to find out how many posts have the `image_details['info_window_bg_image_id']` set to 128 but I would settle to find out if any of the posts have that value set. The only way that I can think to do it (with my limited knowledge) is something along the lines of:   1. Retrieve an array of every post in the database   2. Foreach through the array using the ID's   3. Use get_post_meta(ID, Key) to get the "image_details" key   4. Check the value of the 'info_window_bg_image_id' element of the result to see if it matches the value.  This seems like it would be a heavy load because I would have to do this multiple times to check for other values. Is there an easier way of doing this? Perhaps with a direct SQL query via the WP_Query class? Just to reiterate my ideal would be to get a result that lets me know there are:   * 6 posts have post_meta image_details 'info_window_bg_image_id' set to 128   * 10 posts have post_meta image_details 'info_window_bg_image_id' set to 127   * 0 posts have post_meta image_details 'info_window_bg_image_id' set to 126 etc etc But I would also be happy with a result that just says: 128 is used, 127 is used, 126 isn't used etc


Wordpress and magic quotes

I've been writing some Wordpress plugins, and I've been having some problem with Wordpress putting magic quotes on POST and GET data. Specifically, the "wp_magic_quotes" function in \wp-includes\load.php, which is called (presumably on every response) in wp-settings.php. This function adds magic quotes to the data even if I turn off magic quotes in PHP settings.               /**      * Add magic quotes to $_GET, $_POST, $_COOKIE, and $_SERVER.      *      * Also forces $_REQUEST to be $_GET + $_POST. If $_SERVER, $_COOKIE,      * or $_ENV are needed, use those superglobals directly.      *      * @access private      * @since 3.0.0      */     function wp_magic_quotes() {         // If already slashed, strip.         if ( get_magic_quotes_gpc() ) {             $_GET    = stripslashes_deep( $_GET    );             $_POST   = stripslashes_deep( $_POST   );             $_COOKIE = stripslashes_deep( $_COOKIE );         }              // Escape with wpdb.         $_GET    = add_magic_quotes( $_GET    );         $_POST   = add_magic_quotes( $_POST   );         $_COOKIE = add_magic_quotes( $_COOKIE );         $_SERVER = add_magic_quotes( $_SERVER );              // Force REQUEST to be GET + POST.         $_REQUEST = array_merge( $_GET, $_POST );     }      Is it safe for me to just comment out the wp_magic_quotes() call in wp- settings.php? That is, will it negatively affect the normal Wordpress code and/or open up some exploitation vector? If so, is there some other way to do it besides modifying WP code (so I don't have to deal with this every time there's an update)?


Exclude all subcategories in the_category (post)

I'm looking for a way to hide all the subcategories based in my post: It always displays in my posts like : Categorie, sub categories. So I'd like to exclude all of the sub_categories. I've been trying to trick this portion of code:               <?php the_category(', ') ?>      but I can not manage to make it work . If anybody has a solution, I ll be really thankful!! :)


Make Custom Post Behave Like Normal Post?

Is there a way to force Custom Post Types to behave as normal wp posts? Hi - I need some help adding a custom post type to my theme's posts section. The posts page is a static page using a template (not the standard wp home/blog page). The template allows me to select post categories to feature on the page, but my custom post types never show up in the choices. If I select "show all posts" the custom posts still don't show up on the published page unless I add the following code to the end of my functions.php My custom posts then show up in among the regular posts (as I wanted) BUT, it messes up the layout of the site (the main nav menu disappears!)               add_filter( 'pre_get_posts', 'my_get_posts' );     function my_get_posts( $query ) {         $query->set( 'post_type', array( 'post', 'page', 'projects' ) );     return $query;     }


Issue with "Search Everything" plugin

Trying to use this plugin to allow the admin to search uploaded media by tag ... it works fine on the media upload page but finds nothing when searching for the same tag in the `Add Media` popup. I'm not sure why this is happening, but I really need to fix it ... or find a different solution ASAP. The only code I have messing with the search functionality is as follows:               function SearchFilter($query) {         if ( !is_admin() ) {             if ($query->is_search) {                 $query->set('post_type', 'event');             }             return $query;         }     }          add_filter('pre_get_posts','SearchFilter');      Thanks for any help!


how to echo script in head from plugin options page via textarea?

I know how to echo in the head but when i paste a script in the textbox in my options page it comes out like this:               <script>       (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;    i[r]=i[r]||function(){       (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),       m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)       })(window,document,'script','//www.google-analytics.com/analytics.js','ga');            ga('create', 'UA-48019065-1', 'elegantdevelopment.eu');       ga('send', 'pageview');          </script>      instead of this:               <script>       (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){       (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),       m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)       })(window,document,'script','//www.google-analytics.com/analytics.js','ga');            ga('create', 'UA-48019065-1', 'elegantdevelopment.eu');       ga('send', 'pageview');          </script>      I checked my database and the option is stored as the second example display when i check in phpmyadmin Here is the code i have for to insert the snippet:               function PrintAnalytics( $post ){         global $post;         $analytics = esc_attr(get_option('basic_seo_analytics'));         echo "\r\n" . $analytics . "\r\n\n";     }


Sortable WYSIWYG editor

I have a bunch of wysiwyg editors in a metabox that are sortable. Unfortunately whenever I drag a row around I get this error, and I have no idea what is causing it. **Uncaught TypeError: Object [object Object] has no method 'destroy'** This is my sortable code:               $( "#repeatable-fieldset-one tbody" ).sortable({                 handle: '.jQuerySortableIcon',                 cursor: 'move',                 placeholder: "topTenSortablePlaceholder",                 start: function() {                     $('textarea').each(function() {                         var id = $(this).attr('id');                             $('#'+id).next().remove();                         tinyMCE.execCommand('mceRemoveControl', false, id);                     });                     // remove control from our descripiton, and title fields to preserve content                     // tinymce.EditorManager.execCommand('mceRemoveControl',true, 'movie_description-1');                        },                 update: function() {                                     // update the ranking numbers after sorted                     $('.single-movie-row').each(function() {                         var thisIndex = ($(this).index() + 1);                         $(this).find('.movie_rank_number').val('# '+thisIndex);                          });                     $(this).parents("#repeatable-fieldset-one tbody").sortable('refresh');                   }             });      As you can see, on start I am removing control from my textareas (which visually works). The WYSIWYG editors are still below the textareas, after removing control for whatever reason. If I take out this line: `tinyMCE.execCommand('mceRemoveControl', false, id);` I no longer get the error, but my wysiwyg editors don't convert back to textareas. I am converting them to textareas to preserve the content within them. First , what is this error? Is it because its unable to remove the wysiwyg editor when I run mceRemoveControl? Thought I had this working earlier, went with a different method that didn't work out, and have since came back to this route and am now hitting this error. Any ideas? **EDIT** It now looks like the reason its throwing the error is because its unable to remove the placeholder. But I don't know why. It also looks like after I drop my new item into place, all of these styles get added to it throwing everything off: `width: 1375px; height: 263px; position: absolute; z-index: 1000;`


Choosing the right server for a big WordPress site with buddypress

I started working in a WordPress site with buddypress and I need to choose a server. They have 1.9 million users in the database and they are estimating to have like 250,000 views every month. The site is not live yet. I'm sure you might need more information that this, but can you guide me in the right direction. What hardware should I use? what specification do you recommend? I went to hivelocity.net and I was thinking maybe something like this... Is this too little, too much? Please let me know what you think.   * 4 x Quad-Core 2.0GHz E5-4603 40MB cache with HT   * 256GB DDR3   * 600GB Intel Solid State Drive S3500 series   * 300GB Intel Solid State Drive S3500 series   * SSD RAID 10   * 1Gbps Unmetered Port (estimated 330,000GB)   * CentOS 6.x   * 64 Bit   * cPanel   * On-Board IPMI included   * Juniper SSG-5-SB   * 200 GB Storage with 1 CAL   * cPanel to cPanel- FREE if you have Fully Managed cPanel Services. Otherwise this falls --under Custom Migrations below.   * Total: $2723.00   * Setup: $148.00


Getting tagid from tagname

Currently I am working on a rating plugin. You can see the code I got so far below:               <?php if (function_exists('get_highest_rated')): ?>     <ul>     <?php get_highest_rated_tag(12, 'both', 0, 10); ?>     </ul>     <?php endif; ?>      But now it comes to a bit of php that I simply can't find on the web so far, so I will ask you. At this code, you see the number 12, that is the tag id. But I can't put in the tag name. So I was thinking of echo'ing the tagid for a certain tagname. Is this possible? This way I can get like $tagid of that certain tagname and insert it into the code above.


Shortcode into the same shortcode

I'm working on a theme for a framework, and using shortcode to divide the layout, I've found the following problem: Into a content, I can divide the container into 12 different parts, it also applies for content inside the content (and this is when problem comes), meaning, for sample, if I decide to set 8 and 4 columns, and then the 8 columns I want to divide it into 2 parts, I would need a structure like this:               [content]       [8 columns]           [content]   <-- PROBLEM IS HERE               [6 columns]                  half of eight part 1.               [/6 columns]               [6 columns]                  half of eight part 2.               [/6 columns]           [/content]        [/8 columns]            [4 columns]          some content here       [/4 columns]     [/content]      When I try to executed this logic, the second content is not being taken, and is displayed as text.. so... I thought the shortcode into a shortcode logic would work, however... it doesn't work if the SC is the same, in short works this (my code) is not working for me.                function content_sc($atts, $content = null){        return '
'.do_shortcode($content).'
';      }      add_shortcode('content', 'content_sc');       Any guessing??? Thanks in advanced!!!


wordpress loop for specific category

i have this snippet for specific category it works perfect but i want little modification to show posts by Ascending order.               <?php           // The Query      query_posts( array ( 'category_name' => 'A', 'posts_per_page' => -1 ) );           // The Loop     while ( have_posts() ) : the_post(); ?>
          <a href="<?php the_permalink() ?>" title="<?php the_title(); ?>"><?php the_title(); ?>
           <?php endwhile;           // Reset Query      wp_reset_query();           ?>


Wordpress loop: Display <div> if posts exist

In a single post template I am trying to output some header text in a `<div>` and display links to related posts in a `<ul>` if related posts exist (based on tags). If there are no posts, nothing should be displayed. `$idspost[] = $post->ID` gets the posts which should be displayed. The loop is one of a series of loops and the retrived post ID's are also passed on to the next loop in order to avoid duplicate posts showing up. All works well so far. I have echoed out the ID's to test, but with my basic skills I don't realize how I will display the `<div>,<ul>` and retrieve the post ID's in the standard way:               <?php if (have_posts()) : ?>       <div>         <?php while (have_posts()) : the_post(); ?>           … //get the permalink, title etc...         <?php endwhile; ?>        </div>     <?php endif; ?>      The post ID's are retrieved:               <?php         $tags = wp_get_post_tags($post->ID);         if ($tags) {           $second_tag = $tags[1]->term_id;           $args=array(             'tag__in' => array($second_tag),             'post__not_in' => array($post->ID),             'showposts'=>5, //Display this number of related posts             'ignore_sticky_posts'=>1            );           $my_query = new WP_Query($args);           if( $my_query->have_posts() ) {               while ($my_query->have_posts()) : $my_query->the_post();                if (!in_array($post->ID, $ids))                {; $idspost[] = $post->ID; ?>              <?php }             $ids[]= $post->ID;              $idspost[] = $post->ID;             endwhile;           }         }         ?>      Would be very grateful for help!


Translations not returning translated strings

I have the following function to display my comment form in my child theme                   function pietergoosen_comment_form_fields( $args = array(), $post_id = null ) {         if ( null === $post_id )             $post_id = get_the_ID();         else             $id = $post_id;              $commenter = wp_get_current_commenter();         $user = wp_get_current_user();         $user_identity = $user->exists() ? $user->display_name : '';              $args = wp_parse_args( $args );         if ( ! isset( $args['format'] ) )             $args['format'] = current_theme_supports( 'html5', 'comment-form' ) ? 'html5' : 'xhtml';              $req      = get_option( 'require_name_email' );         $aria_req = ( $req ? " aria-required='true'" : '' );         $html5    = 'html5' === $args['format'];         $fields   =  array(             'author' => '
' . '' . __( 'Name', 'pietergoosen' ) . ( $req ? ' *' : '' ) . ' ' .                         '<input id="author" name="author" placeholder="'.__( '*Required* Enter a valid name and last name', 'pietergoosen' ).'" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' />
',                  'email'  => '
' . __( 'Email', 'pietergoosen' ) . ( $req ? ' *' : '' ) . ' ' .                         '<input id="email" name="email" placeholder="'.__( '*Required* Enter a valid email', 'pietergoosen' ).'" ' . ( $html5 ? 'type="email"' : 'type="text"' ) . ' value="' . esc_attr(  $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' />
',                  'referer' =>'
' . __( 'Where did you here about this website?', 'pietergoosen' ) . '' .                         '<input id="referer" name="referer" placeholder="'.__( 'Facebook, Twitter, Friends, Google, etc …', 'pietergoosen' ).'" type="text"  size="30" />
',     );              $required_text = sprintf( ' ' . __( 'Required fiels are marked %s'), '*' );              $arg = array(             'fields'               => apply_filters( 'comment_form_default_fields', $fields ),             'comment_field'        => '
' . _x( 'Comment', 'Comments field name', 'pietergoosen' ) . ' <textarea id="comment" name="comment" placeholder="'.__( '*Required* Enter your comment here. Minimum 20 characters, please', 'pietergoosen' ).'" cols="45" rows="8" aria-required="true"></textarea>
',             'must_log_in'          => '
' . sprintf( __( 'You must be logged in to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '
',             'logged_in_as'         => '
' . sprintf( __( 'Logged in as %2$s. Log out?' ), get_edit_user_link(), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '
',             'comment_notes_before' => '
' . __( 'Your email address will not be published.' ) . ( $req ? $required_text : '' ) . '
',             'comment_notes_after'  => '
' . sprintf( __( 'You may use these HTML tags and attributes: %s' ), ' ' . allowed_tags() . '' ) . '
',             'id_form'              => 'commentform',             'id_submit'            => 'submit',             'title_reply'          => __( 'Leave a Reply', 'pietergoosen' ),             'title_reply_to'       => __( 'Leave a Reply to %s', 'pietergoosen' ),             'cancel_reply_link'    => __( 'Cancel reply', 'pietergoosen' ),             'label_submit'         => __( 'Post Comment', 'pietergoosen' ),             'format'               => 'xhtml',             );         return $arg;     }          add_filter('comment_form_defaults', 'pietergoosen_comment_form_fields');      All the translatable strings are scraped up and are displayed in my af_AF.po file. The problem is that some strings don't return the translated texts and some do. Here are some of the strings that return the translated text                'author' => '
' . '' . __( 'Name', 'pietergoosen' ) . ( $req ? ' *' : '' ) . ' ' .                         '<input id="author" name="author" placeholder="'.__( '*Required* Enter a valid name and last name', 'pietergoosen' ).'" type="text" value="' . esc_attr( $commenter['comment_author'] ) . '" size="30"' . $aria_req . ' />
',                  'email'  => '
' . __( 'Email', 'pietergoosen' ) . ( $req ? ' *' : '' ) . ' ' .                         '<input id="email" name="email" placeholder="'.__( '*Required* Enter a valid email', 'pietergoosen' ).'" ' . ( $html5 ? 'type="email"' : 'type="text"' ) . ' value="' . esc_attr(  $commenter['comment_author_email'] ) . '" size="30"' . $aria_req . ' />
',                  'referer' =>'
' . __( 'Where did you here about this website?', 'pietergoosen' ) . '' .                         '<input id="referer" name="referer" placeholder="'.__( 'Facebook, Twitter, Friends, Google, etc …', 'pietergoosen' ).'" type="text"  size="30" />
',      and here are those strings that don't want to show the translated text                'comment_field'        => '
' . _x( 'Comment', 'Comments field name', 'pietergoosen' ) . ' <textarea id="comment" name="comment" placeholder="'.__( '*Required* Enter your comment here. Minimum 20 characters, please', 'pietergoosen' ).'" cols="45" rows="8" aria-required="true"></textarea>
',             'must_log_in'          => '
' . sprintf( __( 'You must be logged in to post a comment.' ), wp_login_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '
',             'logged_in_as'         => '
' . sprintf( __( 'Logged in as %2$s. Log out?' ), get_edit_user_link(), $user_identity, wp_logout_url( apply_filters( 'the_permalink', get_permalink( $post_id ) ) ) ) . '
',             'comment_notes_before' => '
' . __( 'Your email address will not be published.' ) . ( $req ? $required_text : '' ) . '
',             'comment_notes_after'  => '
' . sprintf( __( 'You may use these HTML tags and attributes: %s' ), ' ' . allowed_tags() . '' ) . '
',      This is code I copied from wordpress core files. Am I missing something? Any suggestions


Theme Option select values

I'm building a theme options panel and so far been successful, except with the "Select" type option. This is my code:               array( "name" => "Transition",         "desc" => "Choose the type of transition.",         "id" => $shortname."_transition",         "type" => "select",         "std"   => '1',         "options" => array("0" => "None", "1" => "Fade", "2" => "Slide Top", "3" => "Slide Right"),      Now, my select code is this:               <select name="<?php echo $value['id']; ?>" id="<?php echo $value['id']; ?>">     <?php foreach ($value['options'] as $option) { ?><option <?php if ( get_settings( $value['id'] ) == $option) { echo ' selected="selected"'; } elseif ($option == $value['std']) { echo ' selected="selected"'; } ?>><?php echo $option; ?></option><?php } ?>      Now, when I pull the option into the theme, it outputs the option name (fade, Slide Top...etc) instead of the value (0, 1, 2, 3). I'm guessing here that perhaps I'm missing the `value=""` from the `/option>` code? any help would be appreciated, thank you. **Edit: figured it out, edited the second code to this:**               <?php foreach ($value['options'] as $key=>$option) { ?><option value="<?php echo $key; ?>" <?php if ( get_settings( $value['id'] ) == $option) { echo ' selected="selected"'; } elseif ($option == $value['std']) { echo ' selected="selected"'; } ?>><?php echo $option; ?></option><?php } ?></select>


Execute js files doesn't seem to work

I have developed a website that uses the "Royal Slider". The post loads custom fields from the database without a problem and loops through the images and create a lovely slideshow as can be seen at http://www.ccmediaservices.co.uk/property/2-bedroom-apartment-to-rent/ The problem is I want to pass some custom settings to customise the slider. Normally this is achieved with this block of js at the bottom of the html just before tag. This is the settings js initialise code               <script>     jQuery(document).ready(function($) {     $('.royalSlider').royalSlider({     fullscreen: {       enabled: true,       nativeFS: true     },     controlNavigation: 'thumbnails',     autoScaleSlider: true,      autoScaleSliderWidth: 960,          autoScaleSliderHeight: 850,     loop: false,     imageScaleMode: 'fit-if-smaller',     navigateByClick: true,     numImagesToPreload:3,     arrowsNavAutoHide: true,     arrowsNavHideOnTouch: true,     keyboardNavEnabled: true,     fadeinLoadedSlide: true,     globalCaption: true,     globalCaptionInside: false,     thumbs: {       appendSpan: true,       firstMargin: true,       paddingBottom: 4          }     });     });     </script>      In wordpress this is not possible as I am well aware so I did the standard procedure of placing two action hooks in the function file. One to register the script and one to print it from the footer. This is my code               /* Royal Slider Hooks */          add_action ('init', 'register_my_royal_slider_script');          add_action ('wp-footer', 'print_my_royal_slider_script');          /* Royal Slider Functions */          function register_my_royal_slider_script() {     wp_register_script('my-script', get_template_directory_uri() . '/royalslider/custom-slider-settings.js', array('jquery'), '1.0', true);     }               function print_my_royal_slider_script() {     global $add_my_script;          if ( ! $add_my_script )         return;          wp_print_scripts('my-script');     }      Unfortunatly it is failing to have any effect. Is there something wrong with any of the above code you can see? I'm a bit confused I'm getting no errors with this


Notify comment author upon reply

To improve communication between guest commenters and authors, I am fiddling with a script that sends an email to the author of a comment when it receives a reply. Here is how the code looks so far:               <?php     /*      Plugin Name: Comment Reply Notifier     Plugin URI: http://wordpress.stackexchange.com/users/24875/christine-cooper     Version: 0.1     Author: Christine Cooper     Description: When someone replies to a comment, an email is sent to the writer of the replied comment.     Author URI: http://wordpress.stackexchange.com/users/24875/christine-cooper     */          add_action('comment_post', 'comment');     function comment($comment_reply_id)      {         $comment = get_comment($comment_reply_id);         if($comment->comment_parent != 0)          {             $old_comment = get_comment($comment->comment_parent);             if($old_comment->user_id == 0)             {                 $email = $old_comment->comment_author_email;                 $name = $comment->comment_author;                 $content = $comment->comment_content;                 $post = get_post($comment->comment_post_ID);                 $title = $post->post_title;                 $link = get_permalink($comment->comment_post_ID);                 $blogname = wp_specialchars_decode(get_option('blogname'), ENT_QUOTES);                 $subject = sprintf('Comment reply: "%2$s" at %1$s', $blogname, $title );                 $notify_message  = sprintf('Someone replied to a comment you left on: %s', $title ) . "\r\n";                 $notify_message .= sprintf( 'Reply by: %1$s ', $name ) . "\r\n";                 $notify_message .= 'Comment: ' . "\r\n" . $content . "\r\n\r\n";                 $notify_message .= 'You can reply to the comment here: ' . "\r\n";                 $notify_message .= $link . "#comments\r\n\r\n";                 $message_headers = "Content-Type: text/plain; charset=\"" . get_option('blog_charset') . "\"\n";                 wp_mail( $email, $subject, $notify_message, $message_headers );             }         }      }          ?>      It works fine, feel free to try it. There are two things I want to add to it. I want to adjust the name and the email of the message. So I want to set the Blog name as the name of the sender and a custom email as the sender's mail (for instance no-reply@domain.com). How do I do it?


Echo title attribute php

I have the following in functions.php:               function twentyten_continue_reading_link() {     global $id;     return '  0, 'before' => 'Permalink to: ', 'after' => '')) . the_title() . '">' . __( 'Read More »', 'twentyten' ) . '';     }      which creates a "Read More" link after an excerpt with a title attribute. I want to do the same thing in another part of the site, but the code for this 'Read More' link is different (see below). Since it's a php echo statement the same syntax won't work and I don't know how to translate what I have above to work in the situation below. I want to keep the href= $permalist[$j], but add a title attribute after it.               echo "
Read More »
";


Setup Featured image on all posts from thesis thesis_post_image custom field?

I moved from thesis to other wp theme and i want to change the thesis post images (these are saved under thesis_post_image in database )as featured images. Site have over 1000+ posts. Is there a way to run a code to change the thesis_post_image urls in the database to the featured image field in the database?


Use options to control jQuery plugin

This may be a dumb question, but I've been teaching myself Wordpress and I've been struggling with this for a while. What I want to do is use a Wordpress control panel page to control a countdown clock on my site. I found a jQuery countdown that seems like it will work well and I've learned how to create a plugin with an options page and how to get that options page talking with the options database. I've got the options page creating an array with the month, day, and time that the countdown should end and saving it to a table in my options database. I understand that the wp_localize_script function is what I want to use in order to output that data to my jQuery plugin. However, I can't seem to connect the final dots. The code for the jQuery countdown looks like this:               <script> $('.live-countdown').countdown({ date: 'January 1, 2015 13:30:00' }); </script>      I have all of that information stored in my options DB (as an array with month, day, year, and time in the correct format), but I can't seem to figure out how to get it to output in such a way that I can use it here. Can someone explain to me how to use wp_localize_scripts to output my information? I'm still very much learning (both Wordpress and PHP in general) and I've been struggling with this for a few days. Sorry if it's a repeat question but I've been searching and Googling for a while with no luck. All the tutorials I can find are either unclear or for something slightly different. It seems really simple but I think I just need it explained a little better for my particular situation. Thanks for the help!


Can't redirect to previous page after using GET

I have a function that is displaying a shopping cart and products, and so after a product is added (which happens via `GET`) I want it to return to regular domain. This is the code that updates the cart:               $page = $_SERVER['PHP_SELF'];          // if the product is added to the cart     if (isset($_GET['add'])) {         $_SESSION['cart_'.$_GET['add']]++;         header('Location: '.$page);         // echo 'added';     }      Right now the cart is displayed on my homepage, which is `http://localhost/tester/` , and after a product is added the url becomes `http://localhost/tester/?add=1`, but then I want it to revert back to `http://localhost/tester/` but I cannot get it to do that. Any ideas?


Exclude categories by ID

I've searched this site and tried all kinds of ways to exclude categories 1 and 7 from this list, but nothing is working. No errors but doesn't hide the cats either. Categories 1 and 7 are not empty, but I'd also like to exclude empty categories, so !empty must stay.                    <?php     $terms = apply_filters( 'taxonomy-images-get-terms', '', array('taxonomy' => 'category') );          if ( ! empty( $terms ) ) {            foreach( (array) $terms as $term ) {           echo '

taxonomy ) ) . '">' . $term->name . '
';           echo '
taxonomy ) ) . '">
';           echo '
'. $term->description . '

';       }          }     ?>


Run query once inside a loop

I am trying to prevent to much queries inside a plugin one of my plugins. I have a query inside a function which will output a complete block with some layout elements and an input element which will contain a value(from the query). I have like 50 blocks, so this means 50 queries, not the best way to do this. Are there a way to run the query once that will keep the results in tact. I need the query inside this function:               function inputblock($table, $id){         global $wpdb;         $results = $wpdb->get_row($wpdb->prepare("SELECT * FROM $table WHERE the_id = %d", $id));              // one column is called the_name         echo '<input value="'.$results->the_name.'"/>';              unset($results);// something like this          }      inputblock('table_1', 1);      inputblock('table_1', 44);      inputblock('table_1', 1234);      ...      ...      // example above is already 3 queries, it must just be 1


What is the point of get_comment_count() if you cannot limit by a comment type?

We are finding that large WooCommerce sites run very slow. Amongst many issues, this one has me scratching my head. WooComemrce stores order notes in the comments table, giving them a comment_type of 'order_note' and approving them immediately. They are linked to the orders so can only be seen by the shop administrators. Now, something on one site (not traced it yet) is doing this query:               SELECT comment_approved, COUNT(*) AS total     FROM wp_comments     GROUP BY comment_approved      With 120k comments on the system, mostly of type "order_note", this is taking a substantial time on every page load (up to 500mS query time) and thrashing the server. What would be the point of this query? It gets the counts of ALL rows in the comments table, grouped by the approval status. It counts comments, trackbacks, pings, and order_notes. What would be the point of that? I cannot think of a use for doing such a query on every page. The get_comment_count() function in wp-includes/comment.php will run this query. If you pass in the post ID, then it summarizes for that post. That's fast. If you do not pass in a post ID, then it counts all rows in the entire table, and that is slow and IMO useless. This function does NOT accept a comment_type, so you cannot limit the query to a specific type of comment. While I trace the source of this query, I am wondering why WP would support querying the whole table like this. It is kind of assuming that custom comment types will NEVER be created, i.e. the comments table will never be used for anything other than the three comment types listed in the codex. Is this the case? Is WooCommerce totally abusing this table? I'm not sure what kind of answer I am looking for here, but I suspect a ticket needs to be raised for it somewhere (perhaps adding the comment_type to the query WHERE clause in the function), so looking for any thoughts or any similar experiences with this problematic query. Updates: The exact query:               SELECT comment_approved, COUNT( * ) AS num_comments     FROM wp_comments     GROUP BY comment_approved      This takes 300mS consistently to run, and returns this: | comment_approved | num_comments | | ---------------- | ------------ | | 0 | 1 | | 1 | 191370 | | post-trashed | 1 | | spam | 29 | No difference after optimising the table. Now I noticed the count aliases as "num_comments" and not "total", which means it is wp_count_comments() that is running and not get_comment_count(). This means the count results _should be_ cached under key comments-0, but it's not - the query is run every page. Maybe the cache is being cleared somwhere else on the page? But still, doing this count is useless. Most of the "approved" comments are order_notes added by WooCommerce. They are not "comments" in the usual sense. The comment_approved column is indexed (the first column in a compound index) and WP says it has a cardinality of 7, even though only four groups are returned from the query. This takes about 1mS:               SELECT DISTINCT comment_approved     FROM wp_comments      So the index is working there, but it just slows down when the counts are needed, and that should really only need the indexes to be inspected. The explain plan is: select_type = SIMPLE table = wp_comments type = index possible_keys = NULL key = comment_approved_date_gmt (???) key_len = 70 ref = NULL rows = 195885 Extra = Using index Maybe it is just one of those things that MySQL is really bad at optimising, like sub-selects, which it have been atrocious since day one.


Why use dynamic_sidebar() conditionally?

In the codex example of displaying sidebars, what is the significance of the conditional wrapping around the call to dynamic_sidebar? Why do this:               <?php if ( dynamic_sidebar('example_widget_area_name') ) : else : endif; ?>      this seems to work ok:               <?php dynamic_sidebar('example_widget_area_name'); ?>      Thanks, Toby


Wordpress getting css and script files from client machine rather than the server machine

I'm a noob Wordpress user and I'm having an odd problem. I managed to install Wordpress edit the wp-config file and everything. However when I browse my site from a remote machine no css or script files are loaded, although I can see the html page without any styling. When I checked the source, I found out that Wordpress is trying to get the scirpt files from the client machine ex: _http://127.0.0.1/wp-admin/css/wp- admin.css?ver=20111208_ Any Ideas on what the problem might be ?


"Unable to create new image" error in wordpress dashboard image editor

My server is nginx and wordpress version is 3.8.1. I can upload images but when I try to edit the image (scale, crop) it gives below error and doesn't show picture. I have tried with 400kb to 1mb picture both has same problem. I found on internet that it can happen because of GD library is not available. I have installed GD library but still getting same error. Also tried this solution but no luck. Can anyone help me? ![enter image description here](http://i.stack.imgur.com/c3AXW.jpg)


Let plugin check if taxonomy is already registered by another plugin

My site is using a custom taxonomy that can be associated with two different custom post types. Each post type is registered by a different plugin. It may be that only one of the plugins is active or that both are activated. My idea was to let each plugin check if the taxonomy has already been registered and —if not— register it. I put the following code into each plugin, but this —of course— gives me an error (Cannot redeclare register_taxonomy_my_taxonomy).               if ( !taxonomy_exists( 'my_taxonomy' ) ) {         add_action( 'init', 'register_taxonomy_my_taxonomy' );         function register_taxonomy_my_taxonomy() {             ...     }


Delete posts based on post meta data

I'm looking for a simple SQL script that will delete posts where the post meta of that post id has some value ['x']. DELETE FROM wp_posts WHERE post_id == wp_post_meta->post_id WHERE meta_value = ['x']


automatically save custom post type title as a category

I wonder if there is a way to automatically create category from my custom post type titles. For example - if I create post named 'sport', the function will create a category - 'sport' automatically.


Change content language for one page

I have one page witch has a different language then the rest of the site. I looked in to many plugins but I can't find a way to chance the content language `<html lang="nl-NL" prefix="og: http://ogp.me/ns#">` for just one page. I use Yoast SEO and he uses `<meta property='og:locale' content='nl_NL'/>` and that also needs to be en_us


Multisite, sharing content by URL

I have a network of two sites, `A.example.com` and `B.example.com`. I'd like it so that if I create a page on `A` with a permalink of `/Widgets` I can access it on `B` using the same relative permalink but without having to actually create the content on `B`. (One site has user profiles that we'd like to continue to manage on a single site but expose on the other site, too.) Site `B` would still "look" like `B` but the content would come from `A`. I was thinking of hooking into `init` but didn't really know what to do and the documentation isn't really helpful. Or would it make more sense to hook into `pre_get_posts` and just change the table prefix that I'm querying? (I know MS isn't intended for this model and that I'll have to handle repercussions like links within the content but that's not a big deal.) Thanks **[EDIT]** Sorry, `/Widget` was a bad name probably, these aren't Wordpress Widgets, just regular posts.


How to serve assets files (js, css, images) on a subdomain

Currently I'm setting up a blog on site.com/wordpress and I would like to serve all of my assets for the blog on my asset server, assets.site.com/blog/. I got the desired results on the front end by changing the siteurl option in the database (wp_options) however the admin routes to that address (the asset server) instead of site.com (which is the value of the home option). What do I need to change to server assets files from a subdomain (js, css & images)?


Why can I not use setup_postdata($post) in the sidebar?

I have created a function that takes one parameter - post type, and will output each posts with some html and title, content etc within that. However, I want to be able to use functions associated with `$post`, especially `the_excerpt`. However, when I try to use my function in my sidebar php widget, it simply outputs the main page's title and content, not the custom queries post info. If I run the function in the page, it works fine though, and echos out the custom queries' post details. You may ask why I don't just put this in the sidebar, well it's too messy and I'll be reusing it with different custom posts, so I thought I'd write a function. MY function:               function myRecentPosts($postType){          wp_reset_postdata();            $args = array( 'post_type' => $postType,'posts_per_page' => 3);            $recentPosts = get_posts( $args );                 foreach($recentPosts as $post){               setup_postdata($post);  ?>

<?php the_title();?>
               <?php the_excerpt();?>
               <?php            }        wp_reset_postdata();          }


How to add subcategories to the blogroll?

I'm looking for a way to create subcategories in my blogroll... For example:               Downloads     -> Windows     -> Mac     -> Linux      I want to create a real **page** (not a widget) where the main categories and beneath the sub categories are listed... Is there any way?


dynamic sidebar in front page

I am developing TwentyTen child theme and wish to display dynamic sidebar on front page, but something is not quite right. I modified `loop-page.php`:
         <?php dynamic_sidebar('promotion-sidebar'); ?> //ADDED LINE         <?php the_content(); ?>         <?php wp_link_pages( array( 'before' => '
' . __( 'Pages:', 'twentyten' ), 'after' => '
' ) ); ?>         <?php edit_post_link( __( 'Edit', 'twentyten' ), '', '' ); ?>
      At first I was invoking it inside `is_front_page` conditional statement but then to double check issue I decided to call it on every page. And guess what it appears on every single one except on the one I want: **THE FRONT PAGE** _**Edit: I am using Sidebar Template for my static front page._** I just don't get it. Any help appreciated.


Remove category from url

I want to remove /category/ base from the permalinks. I tried the solution **http://wordpress.stackexchange.com/questions/6106/remove-parent-category- from-permalink-basically-only-have-the-child-category/** but if i try pasting this in functions.php, i get the 404 error. I also tried `RewriteRule ^category/(.+)$ /$1 [R=301,L]` by pasting in **.htaccess** , but still, i get 404 error.


Large database causes slow load

I have a 2GB WordPress database (using InnoDB Storage Engine) and I noticed my site loads slow when I press the publish button right after I selected a featured image in the media library. I had a look at my tables and noticed `wp_postmeta` is the biggest table and `wp_posts` the 2nd biggest out of all the tables. Is there a way to speed up my load? The database is InnoDB


Accessing site's root from themes folder

Having some troubles with a PHP script I am trying to build. I need to access the a file which is located in the root folder of my Wordpress install: **wordpress-root/live-config.php** Problem is, my script file is located inside the theme's root folder, and I'm trying to access the root folder when defining a constant. My script file is located in: **root-directory/wp-content/themes/theme-root/** If I use `require ABSPATH . 'live-config.php';` it's no good because it looks in the directory where your current file is (ie. **theme-root** directory instead of my **wordpress-root** ). I just want to know what the best way would be to grab the root folder of my Wordpress install when defining a constant which is in the theme directory? In my script, I'm currently trying:               /** Absolute path to the WordPress directory. */     if ( !defined('ABSPATH') )     define('ABSPATH', dirname(__FILE__) . '/');          /**     * Define type of server     *     * Depending on the type other stuff can be configured     * Note: Define them all, don't skip one if other is already defined     */          define( 'WP_DEV_SERVER', file_exists( ABSPATH . 'dev-config.php' ) );          /**     * Load DB credentials     */          if ( WP_DEV_SERVER )         require ABSPATH . 'dev-config.php';     else         require ABSPATH . 'live-config.php';      But obviously defining ABSPATH in my **theme-root** does not actually point to the **wordpress-root** directory.


Programmatically changing role information; editing role name and deleting

I am making system where I am delegating a lot of functionality to the front end of a system using Wordpress. I have listed all the roles (most of the custom) and need to ability for a logged in user to edit the name of the role or delete it. I cant find any normal WP functions to do this, or plugins that allow the simple solution I need, so I was thinking I may need to run a MYSQL query to change the info but.. have you seen the wp_options table with the user role information?? Its a massive mess and I dont really want to destroy the system. Any suggestions? Thanks in advance.


How to display the title for each menu item in a span attribute

I'm trying to add a CSS hover effect to my theme's main menu and the effect is based on an attribute passed in a `<span>` element. The problem is that I am unable to produce this dynamically with the title of each menu item. Here is the HTML that I would like to produce:                        Home         About         Contact           Now in WP I tried adding the `link_before` and `link_after` attribute in order to add the `<span>` element but I'm not sure how to produce the title for each menu item for the "data-hover" attribute. Any help would be highly appreciated.


image background is cut

http://dev.freelanceu.net/mjl/miamischool/ that's my webpage that has a problem in the background, I don't even declared it as no-repeat but still the background was cut at the bottom. I'm confused because in the other page, it's not cut, like this one http://dev.freelanceu.net/mjl/miamischool/forms/


Disable Redirect to Product Page on Search Results Page in WooCommerce

In WooCommerce if you search for a product and there is only one search result then WooCommerce will redirect you directly to the product page. If I want to add some fancy styling to the search results page is there a way I can disable this default functionality?


WP 3.8 theme customizer error

I'm trying to make some customizer for my theme, but i've got JS error "Uncaught ReferenceError: wp is not defined " LOL. I wrote all code based on Codex, maybe it is just WP 3.8 bug? Or what i'm doing wrong? my code - PHP:               add_action( 'customize_preview_init', 'customizer_preview' );          function customizer_preview() {             wp_register_script( 'wproto-customizer-preview', get_template_directory_uri() . '/js/admin/screen-customizer.js', '', true );             wp_enqueue_script( 'wproto-customizer-preview', array( 'jquery', 'customize-preview' ) );     }      JS:               ( function( $ ) {              // here i've got an error "wp is not defined"         wp.customize( 'blogname', function( value ) {             value.bind( function( newval ) {                 $( '#text-logo .site-title' ).html( newval );             } );         } );     } )( jQuery );      please help :)


WP_editor doesnt apply wpautop on single line content

For a current project I am trying to echo a line of text saved in the theme's options page. I use the wp_editor function for the user input instead of a textarea. The code I am using is quite simple:                   <?php         break;         case "wysiwyg" :          ?>
            <?php echo $value['name']; ?>:	                           <?php               if( get_settings($value['id']) != "") {                     $settings = stripslashes(get_settings($value['id']));               }else{                   $settings = $value['std'];               }               ?>               <?php wp_editor($settings,$value['id'],array('wpautop' => true,'media_buttons'=>false)); ?>
<?php echo $value['desc']; ?>
         <?php break;         ?>      I tried to make sure paragraphs are used by adding `wpautop => true`.. The problem occurs when I try to add a single line of text in the WYSIWYG-mode. When saving the field, paragraph's arent added. After reloading the page the html view is changed back to WYSIWYG and all my HTML tags have disappeared. I tried to use the `wpautop` function manually, but this would append a blank paragraph after the insert variable. My code looks like this:               <?php echo wpautop(stripslashes($lo_homepage_highlight_1_text)) ;?>      And will return:
Lorem ipsum (.....) dolor sit amet. Great rich text

      I don't understand what I am missing here.


How to show content of custom fields in search results?

I was able to include the pages where there are custom fields in search results but I managed not to display the content when there is nothing in the content. Is there a way to include the content of custom fields in the loop?


posts_per_page no limit

I want to return ALL posts with `query_posts`. I tried setting `posts_per_page` to a really high number, but `query_posts` freaks out and doesn't return any posts. What is the correct way to query posts without a limit?               $args = array(         'post_type'      => 'post',         'cat'            => '22,47,67',         'orderby'        => 'name',         'order'          => 'ASC',         'hide_empty'     => 1,         'depth'          => 1,         'posts_per_page' => ?         );


tax_query in get_posts() not working?

I'm trying to print out all the posts within every taxonomy for a custom post type called `product` (jigoshop products). So i get all of the taxonomies using `$cats = get_terms('product_cat');`, then i loop through them all, and get all the posts that is within the taxonomy. The problem is, it doesn't work. It just returns blank!               $uposts = get_posts(array(         'post_type' => 'product',         'numberposts' => -1,         'tax_query' => array(             'taxonomy' => $cat->taxonomy,             'field' => 'slug',             'terms' => array($cat->slug),             'operator' => 'IN'         )     ));      If i change the `'terms' => array($cat->slug)` to `'terms' => $cat->slug` it returns _all_ posts, as if it ignores the tax_query completely. Any ideas what's causing this to fail? I've tried playing around with `operator`, changing `field` to ID (and also sending `$cat->ID` as a term)... nothing works! $cat has the following values:               stdClass Object     (         [term_id] => 114         [name] => Ny testkategori         [slug] => ny-testkategori         [term_group] => 0         [term_taxonomy_id] => 115         [taxonomy] => product_cat         [description] =>          [parent] => 0         [count] => 2         [meta_id] => 3         [jigoshop_term_id] => 114         [meta_key] => order         [meta_value] => 1     )      So $cat->slug and $cat->taxonomy are valid values.


Really high memory usage with almost no plugins -- could Arabic / Hebrew text be a factor?

I've got a fairly small site with literally almost zero plugins (Importer, W3 Total Cache) and not that many pages or media assets but it's running a huge amount of memory (regularly 33MB plus). The only thing I can think of is that this is because about 12 of the 20 pages use RTL languages. My workflow for handling those is Word document / Google Drive doc to Sublime Text 2 to Wordpress editor. Anyone have any experience with this that might be able to help out? Thanks!


the blog owner multisite

In a multisite, how can I get the ID of the owner of the current blog? I know how to get the current blogs Id using get_current_blog_id(), so given that ID, how would I fetch the ID of the owner of that blog? (there's just one owner per blog.)


Most efficient way to list all categories and display a post for each of them?

I'm working on a blog that has around 8.000 posts and 50 categories. The task I'm working on is to list all categories and for each category to show the latest post with a certain custom field value. My current approach is to get all the categories, loop through them and for each one do a wp_query to find the latest post. Is there a more efficient way to do this, one that doesn't involve running 50 queries on the page?


Mask and Track Outbound Links

I'm creating a wordpress website for a client. **MY AIM** : Website will have links to products from various websites. Those links are actually affiliate links for website and services. Those link are needed to be converted into http://www.example.com/go/123 or something like that and when clicked they redirect to the actual link. The next requirement would be to tracking the number of outgoing links. Can you guys, wordpress expert let me about any plugin that would do the job, or even one of the thing that I want. I have also searched this website as well as plugins directory on wordpress.org, but have not found any suitable plugin.


Settings API - getting hidden input / submit button's name

I'm generating this form using Settings API:               <form action="options.php" method="post">           <?php settings_fields('XX_theme_settings'); do_settings_sections('my_settings'); ?>        <input type="hidden" name="foo" value="bar" />        <input name="SubmitButton" type="submit" class="button-primary" value="<?php _e('Save Changes'); ?>" />        </form>      Validation callbacks $input array returns only 'my_settings' input fields. How do I access `foo` (`bar`) input's value and submit button's name `SubmitButton`? This doesn't work for the hidden input:               my_validation($input) {        $foo = $input['foo'];     }      And when it comes to the submit button I don't even know where to start.


Get the current taxonomy product category title in woocommerce

I am wanting to show the current taxonomy product category title in the single product page. The code below works, but returns all product categories. I need some help singling out the current category.               <?php          global $post;         $args = array( 'taxonomy' => 'product_cat',);         $terms = wp_get_post_terms($post->ID,'product_cat', $args);              $count = count($terms);          if ($count > 0) {              foreach ($terms as $term) {             echo '
';             echo 'Category: ' . $term->name;             echo '
';         }     }     ?>      After a few hours of experimenting and searching, you guys are my last hope for a solution. Thanks.


How to strip/remove all blank spaces at the beginning/end of a search string

I use hack of Chris_O for highlighting the search terms. When a user enters the search keywords without any blank space in the beginning or at end of the search string it retrieves and highlights the search terms in the corresponding records nicely. But if the user enters the search string with blank_space in the beginning or at the end, it retrieves and highlights the the search terms but all non- english portions of the post content appears weird (like ���� or ????). Although the english content appears fine but with tags (e..g, `<p style="text-align: center;">test site</p>` etc.) Is it possible in the hack to strip/remove all blank spaces at the beginning/end of a search string? thanks a lot. I use version 3.1.4 with the default twentyten theme. Here is the Hack: Step 1: Add these 2 functions to your functions.php               function search_content_highlight()     {         $content = get_the_content();         $keys = implode('|', explode(' ', get_search_query()));         $content = preg_replace('/(' . $keys .')/iu', ''placeholder4'', $content);         echo '
' . $content . '
';     }          function search_title_highlight()     {         $title = get_the_title();         $keys = implode('|', explode(' ', get_search_query()));         $title = preg_replace('/(' . $keys .')/iu', ''placeholder4'', $title);         echo $title;     }      Step 2: In my theme's loop.php file I call `<?php search_title_highlight(); ?>` instead of `<?php the_title(); ?>` and use `<?php search_content_highlight(); ?>` instead of `<?php the_content(); ?>` Step 3: In my css add the search-highlight class


How to get a list of all the possible thumbnail sizes set within a theme

What function can I use in a plugin to get the dimensions of every image size (in an array preferably) that is defined in a child theme? Just for clarification I am not asking how to _create_ a new image size.


what happens to existing media files when I switch to year/month directory structure format?

A site has thousands of images in the uploads folder. ISP has threatened to shut it down because it is about to exceed server limits for the max number of files in one directory. I looked at the Settings > Media panel and there is the unchecked option "Organize my uploads into month- and year-based folders" If I check this, what will happen to the existing images in the uploads directory (will they be re-organized?) If not, can someone recommend a way/plugin to refile them in the new structure? I'd like to tidy up. thank you


embed video and display in pop up

I have installed lightbox plus plugin. I want to display my video in a popup. Or you can suggest me any alternate plugin that can display my video in a pop up. video source is from my own local server.


Display upcoming Events for next 7 Days

I saw a request for a simple 7 day event calendar that always starts with today. I have a custom meta box called opening-time that gets a YYYY-MM-DD input. For now this is what I have, and its not working. It only outputs 2011-11-17 today is 11-11-2011 so that is wrong. It also must have a php error because none of the blog outputs either. Thank you in advance.               <ul id="days_header">     <?php         $today = date("o-m-d");      $future = strtotime ( '+6 days' , strtotime ( $today ) ) ;      $future = date ( 'o-m-d' , $future );      $event_query = new WP_Query(     array(        'post_type'   => 'event',       'meta_key'    => 'opening_time',       'orderby'     => 'meta_value',       'order'       => 'asc',       'meta_query'  => array(          array(           'key'     => 'opening_time',           'value'   => array($today,$future),           'compare' => 'BETWEEN',           'type'    => 'DATE'         )        )       )      );     ?>     <?php for ($i=0; $i<7; $i++):     $thedate = strtotime ( '+'.$i.' day' , strtotime ( $today ) ) ;     $thedate = date ( 'o-m-d' , $thedate ); ?>          <li>     <?php echo $thedate; ?>     <?php if ($event_query->have_posts()) : while ($event_query->have_posts()) :  $event_query->the_post();?>       <?php if(meta('opening_time') == $thedate) :?>         <?php the_title(); ?>         <?php else: ?>           No Events Today            <?php endif; ?>       </li>     <?php endwhile; endif; rewind_posts(); ?>


Link all Wordpress images size

How i can link all different images size upload in wordpress? I've definited different size image with the plugin simple image size so i'ld like show in single post, links to all new images example here: http://topwalls.net/brink-6/ hi this is my image.php               <?php get_header(); ?>

                  <?php while ( have_posts() ) : the_post(); ?>                      <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                             <?php                                 $metadata = wp_get_attachment_metadata();                                 printf( __( 'Published %2$s at %4$s × %5$s in %7$s', 'noteworthy' ),                                     esc_attr( get_the_time() ),                                     get_the_date(),                                     wp_get_attachment_url(),                                     $metadata['width'],                                     $metadata['height'],                                     get_permalink( $post->post_parent ),                                     get_the_title( $post->post_parent )                                 );                             ?>                                                                                <?php edit_post_link( __( 'Edit', 'noteworthy' ), '| ', '' ); ?>

<?php the_title(); ?>

                                 <?php                                     /**                                      * Grab the IDs of all the image attachments in a gallery so we can get the URL of the next adjacent image in a gallery,                                      * or the first image (if we're looking at the last image in a gallery), or, in a gallery of one, just the link to that image file                                      */                                     $attachments = array_values( get_children( array( 'post_parent' => $post->post_parent, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID' ) ) );                                     foreach ( $attachments as $k => $attachment ) {                                         if ( $attachment->ID == $post->ID )                                             break;                                     }                                     $k++;                                     // If there is more than 1 attachment in a gallery                                     if ( count( $attachments ) > 1 ) {                                         if ( isset( $attachments[ $k ] ) )                                             // get the URL of the next image attachment                                             $next_attachment_url = get_attachment_link( $attachments[ $k ]->ID );                                         else                                             // or get the URL of the first image attachment                                             $next_attachment_url = get_attachment_link( $attachments[ 0 ]->ID );                                     } else {                                         // or, if there's only 1 image, get the URL of the image                                         $next_attachment_url = wp_get_attachment_url();                                     }                                 ?>                                      <a href="<?php echo $next_attachment_url; ?>" title="<?php echo esc_attr( get_the_title() ); ?>" rel="attachment"><?php                                 $attachment_size = apply_filters( 'noteworthy_attachment_size', 1200 );                                 echo wp_get_attachment_image( $post->ID, array( $attachment_size, $attachment_size ) ); // filterable image width with, essentially, no limit for image height.                                 ?>
                                  <?php if ( ! empty( $post->post_excerpt ) ) : ?>
                                 <?php the_excerpt(); ?>
                             <?php endif; ?>
                              <?php the_content(); ?>                         <?php wp_link_pages( array( 'before' => '
' . __( 'Pages:', 'noteworthy' ), 'after' => '
' ) ); ?>
                                                   <?php if ( comments_open() && pings_open() ) : // Comments and trackbacks open ?>                             <?php printf( __( 'Post a comment or leave a trackback: Trackback URL.', 'noteworthy' ), get_trackback_url() ); ?>                         <?php elseif ( ! comments_open() && pings_open() ) : // Only trackbacks open ?>                             <?php printf( __( 'Comments are closed, but you can leave a trackback: Trackback URL.', 'noteworthy' ), get_trackback_url() ); ?>                         <?php elseif ( comments_open() && ! pings_open() ) : // Only comments open ?>                             <?php _e( 'Trackbacks are closed, but you can post a comment.', 'noteworthy' ); ?>                         <?php elseif ( ! comments_open() && ! pings_open() ) : // Comments and trackbacks closed ?>                             <?php _e( 'Both comments and trackbacks are currently closed.', 'noteworthy' ); ?>                         <?php endif; ?>                         <?php edit_post_link( __( 'Edit', 'noteworthy' ), ' ', '' ); ?>
                                              <?php previous_image_link( false, __( 'Previous' , 'noteworthy' ) ); ?>                             <?php next_image_link( false, __( 'Next' , 'noteworthy' ) ); ?>                                               <?php comments_template(); ?>                  <?php endwhile; // end of the loop. ?>

      thanks Stew


How to use the empty space left and right of a post?

(WordPress 3.5.1, theme 20-11) I would like to use the red colored areas left and right to a post and can't find information on what plugin might deal with that. How can I add content there - widgets f.x. Or would I have to change the theme? I would prefer to not alter the code for this purpose. ![enter image description here](http://i.stack.imgur.com/sG3zx.png)


wp_enqueue_ scripts

I've searched high and low for the answer - the codex on `wp_enqueue_script` seems pretty simple. The problem is when I add my custom excerpt script to my functions file, register and then enqueue it (set to place in header), the source is displayed in the header as:               <script src="http://www.olliedaw.co.uk/wp-content/themes/DawRefrigerationMilkTanks/js/excerpt.js" type="text/javascript">      Which looks correct in firebug, but it still comes up with a 404 error when I look at the script in firebug as if it can't find the file! File name is right, and is in the right place but still cant get it to load???               themes/Daw Refrigeration Milk Tanks/js/excerpt.js


Why the JavaScript code is ignored from wp editor?

In WordPress when i publish a page with JS code is ignored and don't returns anything.   How can I make sure that when I write a HTML+JS code will be converted to output?!   Like: `<a class="print" href="#" onClick="window.print();">PRINT</a>` Thank you! and sorry for my weak english!


Most effective use of DB querys

I've got a custom database table with lots of data that I'd like to query several times from a custom template file I've built. Say the db table looks like this:               id     name     city          zip     23     Mike     New York      123     54     Peter    Los Angeles   456     78     Steven   Chicago       789     79     Tom      Los Angeles   450      And I want to run at least four queries, looking kinda like this:               SELECT * FROM table LIMIT $paginated,10 (this is presenting all of the names)     SELECT id,city FROM table GROUP BY city (this will be a dropdown list of all the citys)     SELECT zip FROM table WHERE city = "New York" GROUP BY zip      That's only three queries but anyway - is it more effective to just run one big query with all of the data into an array, and then just loop that array whenever needed, or is it better to perform actual db queries? I'm using $wpdb->get_results for every query of course, is this harder for the server to work with? I mean, using WP code to perform DB queries should result in more PHP code for the compiler to translate, am I wrong?


content gets scrambled

Every time someone edits our blog the content is displaying all wrong. It looks perfect in the wysiwyg editor but when you publish the page the content is completely wrong (pictures displayed next to each other etc. How to prevent this? example link


Can't use get_results() in ajax query

I'm using a jquery ajax call to get certain data from wpdb and I'm getting the following message:               Fatal error:  Call to a member function get_results() on a non-object in C:\wamp\www\maps_en2\markers.php on line 15
      This is the call:               $.ajax({         type: "POST",         url: "markers.php",         data: ({'southWestLat' : southWestLat , 'southWestLng' : southWestLng , 'northEastLat' : northEastLat , 'northEastLng' : northEastLng}),         success: function(msg){         alert( msg );         }     });      And this is the called code - markers.php:               <?php         global $wpdb;         $sql = "SELECT user_id, lat, lng FROM coordinates WHERE lat>".$_POST["southWestLat"]." and lat<".$_POST["northEastLat"]." and lng>".$_POST["southWestLng"]." and lng<".$_POST["northEastLng"];         $rows = $wpdb->get_results($sql, OBJECT_K);         ...     ?>      What's strange is that when the php code was on the same file as the javascript (and instead of the parameters 'southWestLat' etc, I used numbers, then it worked.   I should state that the jquery is in a php file under twentyten theme folder but markers.php is under the root directory (couldn't use it when it was in the theme for some reason).


post_content with Contact Form 7

Is it possible to add name="post_content" to more than one input field? I am using Contact Form 7 plugin, and now only the last input field with name="post_content" is gathered in the post. If I put the whole form in a div I only get raw data (not the filled one). Can someone help please.


Exclude post format from get_posts

The title basically says it all. I know I can use the following to get posts from the `aside` post format:               $args = array(         'post_type'=> 'post',         'post_status' => 'publish',         'order' => 'DESC',         'tax_query' => array(             array(                 'taxonomy' => 'post_format',                 'field' => 'slug',                 'terms' => array( 'post-format-aside' )             )         )     );          $asides = get_posts( $args );     foreach ( $asides as $aside ) {         setup_postdata( $aside );         // HTML...     }      What I would like to know is **how do I get posts that are _not_ in the `aside` post format**?


Clash of the rewrites

I have a category called 'neighborhoods'. I also have child categories within 'neighborhoods' E.G. Lakewood, Highland Park... When I click 'highland park' the url is /pages/category/neighborhoods/highland-park How can I change the htacces rules so that when viewing highland park the url would be neighborhoods/highland park/ I also have a post titled 'highland park' in order to have the neighborhoods page generate the 'highland park' category. But when you click it takes you to the single post page. I have a rewrite rule that works when you go to /neighborhoods/ it rewrites pages/category/neighbhorhoods/ but going to the child category brings you the post. **EDIT:** here is the contents of the .htaccess file               RewriteRule ^sellers/? pages/sellers/     RewriteRule ^buyers/? pages/buyers/     RewriteRule ^neighborhoods/? pages/category/neighborhoods/


Making an IE only site (Like a Mobile only site)

For those who are curious, I'm changing the theme but this theme relies on CSS3 and HTML5 and displays very ugly in IE 8 or below. - Especially the navigation. What I want to do is keep my old theme and use it for IE users only, I assume if this can be done for a mobile site, it can for IE. Would it be easier to just get another WP installation and duplicate the content (What's the easiest way to do this?). Or is there a method, such as the mobile method to redirect users to that theme. My plan was, create a second installation with the existing theme then somehow grab the content from the main site and add and IF code redirecting IE users. Is this possible, or is there an easier/ or simpler way?


How can I upload a file with no extension

I am trying to upload a configuration file so I can include a link to it in my post. And I get a Security error, because the file type is not allowed. My config file has no extension. I found this question: Adding file types in wordpress Is there a way that I can add the mime type of '' for a "No Extension" type?


Analytics causes website to crash

Okay so the website I webmaster for http://www.detroitdungeon.com has been having some analytic issues as of lately. I have the google analytics plugin installed and it was working fine for quite sometime. All of a sudden the plugin caused IE users to crash after the page had loaded. So instead of using the plug in I decided to use the code given to me by google and I placed it in the footer of the website. Doing this caused the webpage to crash with all browsers. after the code has been placed in the footer the source code reads               Parse error: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in /home/content/36/5385336/html/detroitdungeon/wp-content/themes/delighted_black2/footer.php on line 5      Here is footer.php               <?php           include('footer_content.php');$delight_mainfont = get_option('delight_mainfont');echo '
Delighted Black designed by Christian Myspace & Designed By: Digital Designz Media GroupIn conjunction with Ping Services   |   French Teacher Jobs   |   Maths Teacher Jobs

                              ';          ?>      I tried going with godaddy analytics and the same issue is happening. Any help would be GREATLY appreciated.


Query reset problem or flawed code to enable custom post type query

After reading through here and trying various options, I am finally able to get my custom post types 'testimonial' (created with product 'Toolset') to show along with my standard cat/tag queries WITHOUT the menu disappearing!! Here is the code I came up with, and placed in my theme's custom-functions.php file:               add_filter('pre_get_posts', 'query_post_type');     function query_post_type($query) {     if(is_category() || is_tag() || is_home() && empty($query->query_vars['suppress_filters'] ) ) {     $post_type = get_query_var('post_type');     if($post_type)         $post_type = $post_type;     else         $post_type = array('post','testimonial','nav_menu_item');     $query->set('post_type',$post_type);     return $query;      }     }      Being new to this I am not quite certain of how this is relating to the loop, and so of course now the problem is, when pulling my custom post types, on that same page a footer widget pulling from the same custom post type is delivering odd results, so it seems clear that I need to apply wp_reset_query(); or wp_reset_postdata(); - but my efforts to apply it are not working. I have tried it within the last container of the query itself, and in various theme locations. It has me wondering if I am really not doing it right, or there is instead a fatal flaw lurking in my code??? I am hoping someone can save me on this it has been so frustrating... * * * ADDENDUM - Updating this based on comments received... If it helps others, I tried a few changes from suggestions below, but didn't follow them correctly at first... so for example was mixing '$query->is_category() || $query->is_tag()', etc with just 'is_main_query()' (duh) and seeing it fail assumed the latter addition was not helping... but then I read again and followed the complete suggestion applying the following:               add_filter('pre_get_posts', 'query_post_type');     function query_post_type($query) {     if($query->is_category() || $query->is_tag() || $query->is_home() && $query->is_main_query()) {     $post_type = get_query_var('post_type');     if($post_type)         $post_type = $post_type;      else         $post_type = array('post','testimonial');     $query->set('post_type',$post_type);     return $query;         }     }      ... and it now appears to be working correctly! So just as stated below, not including $query-> into every one of the statement elements brought on the bad mojo! It also seems that I am now able to eliminate the && empty($query->query_vars['suppress_filter'] as well as the addition of 'nav_menu_item' since the filter is now being applied to the proper location. Thanks much for the help with this.


Why I obtain a white page when I import a backup of an old WP blog on my local web server?

I am pretty new with WP (I came from Joomla) and I am finding some problem loading an old WP backup on my local Apache. I have take the directory containint an old blog (named blog) and I have put it inside my local **www** directory of my Ubuntu local system. Then I have import the database backup on my local MySql server and finally I have change the **wp-config.php** file changing the information about my local database. The problem is that when I try to open the address:               http://localhost/blog/      in my browser it appear a withe page and I can't see no output Why? What could be the problem? How can I try to solve it? Tnx Andrea


After migration of an old WP blog on my local web server I obtain white screen, why? is it a wp_options DB table problem?

I am pretty new in WP (I came from Joomla) and I am finding some difficulties in the migration of an old WP website (made inWP 3.5) on my local web server. I have performed the following operation:   1. I have put the website backup into a directory named **blog** into my Apache **www** directory on my Ubuntu local system.   2. Then I have put the database backup on my MySql local server   3. Finally I have change the values in the **wp-config.php** file to use my local DB The problem is that when I try to open the URL:               http://localhost/blog/      to see the website I see noting (a white screen) Inside the **wp-config.php** I have activated the debug mode by the line:               define('WP_DEBUG', true);      and I have no errors, so I think that this is not a DB problem. Inside the Apache error log file ( **/var/log/apache2/error.log** ) I found that the following errors occurs:               [Fri Jan 10 22:04:50 2014] [notice] Apache/2.2.22 (Ubuntu) PHP/5.3.10-1ubuntu3.9 with Suhosin-Patch configured -- resuming normal operations     [Fri Jan 10 22:05:08 2014] [error] [client 127.0.0.1] PHP Warning:  require_once(/var/www/blog/wp-load.php): failed to open stream: No such file or directory in /var/www/blog/wp-blog-header.php on line 12     [Fri Jan 10 22:05:08 2014] [error] [client 127.0.0.1] PHP Fatal error:  require_once(): Failed opening required '/var/www/blog/wp-load.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/blog/wp-blog-header.php on line 12     [Fri Jan 10 22:38:37 2014] [error] [client 127.0.0.1] PHP Warning:  require_once(/var/www/blog/wp-load.php): failed to open stream: No such file or directory in /var/www/blog/wp-blog-header.php on line 12     [Fri Jan 10 22:38:37 2014] [error] [client 127.0.0.1] PHP Fatal error:  require_once(): Failed opening required '/var/www/blog/wp-load.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/blog/wp-blog-header.php on line 12     [Fri Jan 10 22:38:38 2014] [error] [client 127.0.0.1] PHP Warning:  require_once(/var/www/blog/wp-load.php): failed to open stream: No such file or directory in /var/www/blog/wp-blog-header.php on line 12     [Fri Jan 10 22:38:38 2014] [error] [client 127.0.0.1] PHP Fatal error:  require_once(): Failed opening required '/var/www/blog/wp-load.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/blog/wp-blog-header.php on line 12     [Fri Jan 10 22:38:39 2014] [error] [client 127.0.0.1] PHP Warning:  require_once(/var/www/blog/wp-load.php): failed to open stream: No such file or directory in /var/www/blog/wp-blog-header.php on line 12     [Fri Jan 10 22:38:39 2014] [error] [client 127.0.0.1] PHP Fatal error:  require_once(): Failed opening required '/var/www/blog/wp-load.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/blog/wp-blog-header.php on line 12     [Fri Jan 10 22:38:40 2014] [error] [client 127.0.0.1] PHP Warning:  require_once(/var/www/blog/wp-load.php): failed to open stream: No such file or directory in /var/www/blog/wp-blog-header.php on line 12     [Fri Jan 10 22:38:40 2014] [error] [client 127.0.0.1] PHP Fatal error:  require_once(): Failed opening required '/var/www/blog/wp-load.php' (include_path='.:/usr/share/php:/usr/share/pear') in /var/www/blog/wp-blog-header.php on line 12      Reading online it seems to me that I also have to change the values of the **home** and **siteurl** fields into the **wp_options** database table (they contained references to the site on the old server), so I have change it with these values:   * **home** : `http://localhost/blog`   * **siteurl** : `http://localhost/blog` But the problem persist (I always see a white screen). I think that maybe the problem could be that these value are wrong, or maybe I have change some other values? Or maybe I also create a specific **.htacces** file into my **blog** directory? (now I have no **.htaccess** file) Do you have some idea about how to solve this problem? Tnx Andrea


Better Method for Multiple Meta Boxes

I'm learning about meta boxes and have gotten them to appear on my local dev, but I can't figure out how to avoid creating new functions for saving multiple meta boxes. I assume that I could call an array and reuse the same functions for generating the meta box content and saving it, but I keep getting errors when trying so. Here is the code I have now in my functions file:                   /**          * Home Page Custom Meta Content          *         **/              // Add the Meta Box           function add_home_meta_box() {               add_meta_box(                   'home_meta_box', // $id                   'Home Page Content', // $title                    'show_home_meta_box', // $callback                   'page', // $page                   'normal', // $context                   'high'); // $priority             add_meta_box(                   'home_meta_box_lower_1', // $id                   'Home Lower Left', // $title                    'show_home_meta_box_lower_left', // $callback                   'page', // $page                   'normal', // $context                   'high'); // $priority             }         add_action('add_meta_boxes', 'add_home_meta_box');                     // Creating Array for Fields         $prefix = 'home_';         $home_meta_fields = array(             array(                 'label' => 'Caption Title',                 'desc' => 'Upper section H2 caption title.',                 'id' => $prefix.'title',                 'type' => 'text'             ),             array(                 'label' => 'Caption Sub Title',                 'desc' => 'Upper section H3 caption title.',                 'id' => $prefix.'sub_title',                 'type' => 'text'             ),           array(                 'label'=> 'Caption',                 'desc'  => 'Caption text block.',                 'id'    => $prefix.'caption',                 'type'  => 'textarea'             ),             array(                   'name'  => 'Caption Image',                   'desc'  => 'Upload a pre-cropped 1140px wide x 530px tall web-optimized image.',                   'id'    => $prefix.'image',                   'type'  => 'image'               )         );// end caption array              $prefix2 = 'home_lower_left';         $home_meta_fields_lower_left = array(             array(                 'label' => 'Column Title',                 'desc' => 'H2 title for column.',                 'id' => $prefix2.'title',                 'type' => 'text'             ),             array(                   'name'  => 'Column Image',                   'desc'  => 'Upload a pre-cropped 360px wide x 300px tall web-optimized image.',                   'id'    => $prefix2.'image',                   'type'  => 'image'               ),             array(                 'label' => 'Column Sub-Title',                 'desc' => 'H3 sub-title above text block.',                 'id' => $prefix2.'sub_title',                 'type' => 'text'             ),           array(                 'label'=> 'Text block',                 'desc'  => 'Caption text block.',                 'id'    => $prefix2.'caption',                 'type'  => 'textarea'             ),             array(                 'label' => 'Button Label',                 'desc' => 'Button link label (what user reads on button).',                 'id' => $prefix2.'btn_label',                 'type' => 'text'             ),             array(                 'label' => 'Button URL',                 'desc' => 'URL where button links to. Enter http:// to work.',                 'id' => $prefix2.'btn_url',                 'type' => 'text'             )         );// end lower left array                   //The Callback         function show_home_meta_box() {         global $home_meta_fields, $post;         // Using nonce for verification         echo '<input type="hidden" name="home_meta_box_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';                  //Begin field table and loop             echo '
';             foreach ($home_meta_fields as $field) {                 // get value of this field if it exists for this page                 $meta = get_post_meta($post->ID, $field['id'], true);                 // begin a table row with                 echo '
                                 '.$field['label'].'	                                 ';                                 switch($field['type']) {                                     // case items will go here                                     // text                                       case 'text':                                           echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$meta.'" size="30" />
'.$field['desc'].'';                                       break;                                     // textarea                                       case 'textarea':                                           echo '<textarea name="'.$field['id'].'" id="'.$field['id'].'" cols="60" rows="4">'.$meta.'</textarea>
'.$field['desc'].'';                                       break;                                     case 'image':                                           $image = get_template_directory_uri().'library/images/img-preview-blank.png';                                             echo ''.$image.'';                                           if ($meta) { $image = wp_get_attachment_image_src($meta, 'medium'); $image = $image[0]; }                                                          echo    '<input name="'.$field['id'].'" type="hidden" class="custom_upload_image" value="'.$meta.'" />
                                                          <input class="custom_upload_image_button button" type="button" value="Choose Image" />                                                           Remove Image
'.$field['desc'].'';                                       break;                                   } // end switch                 echo '
';             } // end foreach             echo '
'; // end table         }              // Save the Data         function save_home_meta($post_id) {               global $home_meta_fields;                    // verify nonce               if (!wp_verify_nonce($_POST['home_meta_box_nonce'], basename(__FILE__)))                    return $post_id;               // check autosave               if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)                   return $post_id;               // check permissions               if ('page' == $_POST['post_type']) {                   if (!current_user_can('edit_page', $post_id))                       return $post_id;                   } elseif (!current_user_can('edit_post', $post_id)) {                       return $post_id;               }                    // loop through fields and save the data               foreach ($home_meta_fields as $field) {                   $old = get_post_meta($post_id, $field['id'], true);                   $new = $_POST[$field['id']];                   if ($new && $new != $old) {                       update_post_meta($post_id, $field['id'], $new);                   } elseif ('' == $new && $old) {                       delete_post_meta($post_id, $field['id'], $old);                   }               } // end foreach           }           add_action('save_post', 'save_home_meta');         // Lower Left         //The Callback         function show_home_meta_box_lower_left() {         global $home_meta_fields_lower_left, $post;         // Using nonce for verification         echo '<input type="hidden" name="home_meta_box_left_nonce" value="'.wp_create_nonce(basename(__FILE__)).'" />';                  //Begin field table and loop             echo '
';             foreach ($home_meta_fields_lower_left as $field) {                 // get value of this field if it exists for this page                 $meta = get_post_meta($post->ID, $field['id'], true);                 // begin a table row with                 echo '
                                 '.$field['label'].'	                                 ';                                 switch($field['type']) {                                     // case items will go here                                     // text                                       case 'text':                                           echo '<input type="text" name="'.$field['id'].'" id="'.$field['id'].'" value="'.$meta.'" size="30" />
'.$field['desc'].'';                                       break;                                     // textarea                                       case 'textarea':                                           echo '<textarea name="'.$field['id'].'" id="'.$field['id'].'" cols="60" rows="4">'.$meta.'</textarea>
'.$field['desc'].'';                                       break;                                     case 'image':                                           $image = get_template_directory_uri().'library/images/img-preview-blank.png';                                             echo ''.$image.'';                                           if ($meta) { $image = wp_get_attachment_image_src($meta, 'medium'); $image = $image[0]; }                                                          echo    '<input name="'.$field['id'].'" type="hidden" class="custom_upload_image" value="'.$meta.'" />
                                                          <input class="custom_upload_image_button button" type="button" value="Choose Image" />                                                           Remove Image
'.$field['desc'].'';                                       break;                                   } // end switch                 echo '
';             } // end foreach             echo '
'; // end table         }              // Save the Data         function save_home_meta_lower_left($post_id) {               global $home_meta_fields_lower_left;                    // verify nonce               if (!wp_verify_nonce($_POST['home_meta_box_left_nonce'], basename(__FILE__)))                    return $post_id;               // check autosave               if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE)                   return $post_id;               // check permissions               if ('page' == $_POST['post_type']) {                   if (!current_user_can('edit_page', $post_id))                       return $post_id;                   } elseif (!current_user_can('edit_post', $post_id)) {                       return $post_id;               }                    // loop through fields and save the data               foreach ($home_meta_fields_lower_left as $field) {                   $old = get_post_meta($post_id, $field['id'], true);                   $new = $_POST[$field['id']];                   if ($new && $new != $old) {                       update_post_meta($post_id, $field['id'], $new);                   } elseif ('' == $new && $old) {                       delete_post_meta($post_id, $field['id'], $old);                   }               } // end foreach           }           add_action('save_post', 'save_home_meta_lower_left');      Thanks for helping me out! Much appreciated.


List all custom post type posts from a given category?

I have a custom post type `myposttype` and it's taxonomy is called `myposttype_categories`. `myposttype_categories` have multiple terms inside, such as `foo` and `bar`. The tricky question is - how do I list all myposttype posts that belong to `foo` (or `bar`)? I thought this should work, but it does not:               $args = array(             'post_type' => 'myposttype',             'myposttype_categories'=> 'foo');     $loop = new WP_Query( $args );      And the loop is always empty. I've tried possibly every Taxonomy paramter for WP_Query() also checked Category parameters. There are very old posts addressing the issue issue, but it seems it still doesn't work after 3 years...? Or am I missing something? http://wordpress.org/support/topic/wp_query-and-custom-taxonomies http://core.trac.wordpress.org/ticket/13582 [edit] That's how I register my post type:               add_action('init', 'myposttype_register');            function myposttype_register() {              $labels = array(             'name' => _x('Myposttype', 'post type general name'),             'singular_name' => _x('Myposttype item', 'myposttype item'),             'add_new' => _x('Add Myposttype', 'myposttype item'),             'add_new_item' => __('Add New Item'),             'edit_item' => __('Edit Item'),             'new_item' => __('New Item'),             'view_item' => __('View Item'),             'search_items' => __('Search Items'),             'not_found' =>  __('Nothing found'),             'not_found_in_trash' => __('Nothing found in Trash'),             'parent_item_colon' => ''         );              $args = array(             'labels' => $labels,             'public' => true,             'publicly_queryable' => true,             'show_ui' => true,             'query_var' => true,             'menu_icon' => get_stylesheet_directory_uri() . '/article16.png',             'rewrite' => true,             'capability_type' => 'post',             'hierarchical' => false,             'menu_position' => null,             'supports' => array('title','editor','thumbnail','page-attributes','comments','trackbacks'),             'show_in_nav_menus' => true,           );               register_post_type( 'myposttype' , $args );          }        And taxonomy:               register_taxonomy("myposttype_categories", array("myposttype"), array("hierarchical" => true, "label" => "Categories", "singular_label" => "Type", "rewrite" => true));


$form_fields from attachment_fields_to_edit returning empty array

I'm trying to remove the caption field from non-images attachments' edit page, which should be a simple matter of `unset($post['post_excerpt'])`, but I can't unset a non-existent value... Looking at the core, this Array being empty should mean that no fields exist on the attachment page, but all the expected fields are there (plus custom ones I've added). I'm completely and utterly baffled. I've tried extremely high & extremely low priority values in applying the filter, neither of which makes a difference. Below is a test case showing the empty Array before and the Array with just my custom field after.               function attachment_fields_edit( $form_fields, $post ) {         print_r( $form_fields ); // Array ( )              $form_fields['author'] = array(         'label' => __('Author'),         'input' => 'text',         'value' => get_post_meta( $post->ID, "author", true ) );              print_r( $form_fields );         /* OUTPUT:         Array         (             [author] => Array                 (                     [label] => Author                     [input] => text                     [value] => Author Name                 )         )         */     }     add_filter( 'attachment_fields_to_edit', 'attachment_fields_edit', null, 2 );`      I don't know what to do about this. It makes no sense based on the code I'm looking at. Any help would be appreciated! PS: Given recent changes to the Media Manager, my working theory is that this may be related in some way to this change...


Creating fields in the database

I am newbie to wordpress plugin and this is my first plugin which I am doing now. I want that when the plugin will be activate it will make some predefined fields in the database and also the same fields in the form page. So how to do that. Any help will be highly appriciable.


How Do I Figure Out What File(s) to Edit from Looking at the Source Code

I just started working at a company and they have a website that was partially completed by another designer and have hired me to complete and make changes to it. It seems that most of the website was created in WordPress, but some of it seems to be done by hand-coding in HTML & CSS. The website is at http://www.executivetravellink.com/ I do have access to their FTP, so I can transfer the files locally and are able to see them, but my issue is that I can't tell in what files changes were made. For example, if you see the navigator bar at the top with the "Flights," "Cruises," etc, you can see that the previous designer added small icons next to the links. I know that if you go into Appearance--->Menus that you can add/edit the links on the menu and the images can be inserted from using the style.css file in Wordpress. However, I am not sure in what file he was storing those actual images, so I can add new ones. Also, I'm having this issue on many pages, but for example on http://www.executivetravellink.com/brands/hotel-brands/, when you go to the hotel-brands page in Wordpress, I can see the first paragraph about Club Med, but I'm assuming the remaining paragraphs are not there and must be in a separate file linked to it. I tried to insert a banner above the first paragraph and it would not show up. From looking at the source code, would someone be able to know the answer to that? I’m still very new to Wordpress and can’t say I’m an expert at HTML & CSS either at this point. Any information that someone could give me would be certainly much appreciated. Thank You!


How to List Thumbnails based on Custom Categories

I need to list(display) all thumbnails from my Custom Post Types in a page template based on product categories. For Example I have a Custom Category called "Art" and some images(Custom Post Type) products enabled by "Feature Image" associated with "Art" Category.Now I would like to list ONLY all thumbnails of Art category product on my Custom Page Template. Can you please let me know how to do this? I find this method which works only for one page without ability to select from pages!               <?php the_post_thumbnail(); ?>


How to prevent empty category to list content of sub categories?

I have a category structure like following:               A     ->B       ->C     D      (B is sub category of A and C is sub category of B) I have content only for category "C" and if I open Category "B" the content of category "C" is displayed. How can I prevent this? I want to display "No Posts" if I open Category "B".