title: Display HTML only if Custom Field has a Value

text:
I am working with a plugin called Advanced Custom Fields. I am looking for help with code for my custom post type template, which is displaying some repeater field data. I have HTML wrapping each sub-field. Sometimes there will be no value for one or more of the sub-fields. _How to NOT display the HTML that is wrapping the sub-fields, if no value exists for the sub-field?_ In the below code, the SPAN tag for the sub fields of "measurement" and "amount" should HIDE if no value exists for the sub-field. My code is as follows:               <?php          if(get_field('ingredients-list'))         {         echo '
';                  while(has_sub_field('ingredients-list'))         {         echo '
 ' . get_sub_field('quantity') . '  ' . get_sub_field('measurement') . ' ' . ' '. get_sub_field('ingredient_name') .' ' . get_sub_field('notes')  . '
';          }                   echo '
';     }         ?>


title: Repeatable Meta Fields Not Saving

text:
Need some help from the community as i am new to the plugin development of WordPress. I like to create a plugin for WordPress where i need a repeatable fields. But whenever i am saving the post the fields are not saving. I am uploading the file to dropbox so that anyone can checkout the code. Here is the link - https://dl.dropboxusercontent.com/u/34202357/latest-news.zip And here is the code if anyone don't want to download the zip **latest-news.php**               define('WP_DEBUG', true);     define('WP_DEBUG_LOG', true);     define('WP_DEBUG_DISPLAY', false);     if ( WP_DEBUG ) {         define ( 'CLRDR_LN_VERSION', '1.3.5-'.time() );     } else {         define ( 'CLRDR_LN_VERSION', '1.3.5' );     }     define ( 'CLRDR_LN_DIR', plugin_dir_path(__FILE__) );     //define ( 'CLRDR_LN_URL', plugins_url().'/latest-news' );               /**      * Include files      *      * @since 1.0.0      */          if( is_admin() ) {              // Load admin code         require_once( CLRDR_LN_DIR.'includes/custom-post-type-helper-class.php' );              require_once( CLRDR_LN_DIR.'includes/post-types.php' );          }          require_once( CLRDR_LN_DIR.'includes/scripts.php' );      **post-types.php**               <?php          $latest_news = new Custom_Post_Type( 'Latest News Ticker',array('supports'=>array('title')) );            $latest_news->add_meta_box(             'Default News Items',             array(                 'custom_meta_fields' => array(                     array(                         'label' =>  'News Text',                         'type'  =>  'text'                     ),                     array(                         'label' =>  'Link',                         'type'  =>  'text'                     )                                )             ),             'default_meta_box'     );          $latest_news->add_meta_box(             'Ticker Display',             array(                 'custom_meta_fields' => array(                     array(                         'label' =>  'News Text',                         'type'  =>  'short-code'                     )                                    )             ),                       'side_display_settings',             'side'     );      **custom-post-type-helper-class.php**               <?php          class Custom_Post_Type         {             public $post_type_name;             public $post_type_args;             public $post_type_labels;                     /* Class constructor */             public function __construct( $name, $args = array(), $labels = array() )             {                 // Set some important variables                 $this->post_type_name       = strtolower( str_replace( ' ', '_', $name ) );                 $this->post_type_args       = $args;                 $this->post_type_labels     = $labels;                                // Add action to register the post type, if the post type doesnt exist                 if( ! post_type_exists( $this->post_type_name ) )                 {                     add_action( 'init', array( &$this, 'register_post_type' ) );                 }                      // Listen for the save post hook                 $this->save();             }                  /* Method which registers the post type */             public function register_post_type()             {                        //Capitilize the words and make it plural                 $name       = self::beautify( $this->post_type_name );                           $plural     = self::pluralize( $name );                      // We set the default labels based on the post type name and plural. We overwrite them with the given labels.                 $labels = array_merge(                          // Default                     array(                         'name'                  => _x( $plural, 'post type general name' ),                         'singular_name'         => _x( $name, 'post type singular name' ),                         'add_new'               => _x( 'Add New', strtolower( $name ) ),                         'add_new_item'          => __( 'Add New ' . $name ),                         'edit_item'             => __( 'Edit ' . $name ),                         'new_item'              => __( 'New ' . $name ),                         'all_items'             => __( 'All ' . $plural ),                         'view_item'             => __( 'View ' . $name ),                         'search_items'          => __( 'Search ' . $plural ),                         'not_found'             => __( 'No ' . strtolower( $plural ) . ' found'),                         'not_found_in_trash'    => __( 'No ' . strtolower( $plural ) . ' found in Trash'),                          'parent_item_colon'     => '',                         'menu_name'             => $plural                     ),                          // Given labels                     $this->post_type_labels                      );                                // Same principle as the labels. We set some default and overwite them with the given arguments.                 $args = array_merge(                          // Default                     array(                         'label'                 => $plural,                         'labels'                => $labels,                         'public'                => true,                         'show_ui'               => true,                         'supports'              => array( 'title', 'editor' ),                         'show_in_nav_menus'     => true,                         '_builtin'              => false,                     ),                          // Given args                     $this->post_type_args                      );                      // Register the post type                 register_post_type( $this->post_type_name, $args );             }                  /* Method to attach the taxonomy to the post type */             public function add_taxonomy( $name, $args = array(), $labels = array() )             {                 if( ! empty( $name ) )                 {                                // We need to know the post type name, so the new taxonomy can be attached to it.                     $post_type_name = $this->post_type_name;                          // Taxonomy properties                     $taxonomy_name      = strtolower( str_replace( ' ', '_', $name ) );                     $taxonomy_labels    = $labels;                     $taxonomy_args      = $args;                          if( ! taxonomy_exists( $taxonomy_name ) )                         {                             //Capitilize the words and make it plural                                 $name       = ucwords( str_replace( '_', ' ', $name ) );                                 $plural     = $name . 's';                                      // Default labels, overwrite them with the given labels.                                 $labels = array_merge(                                          // Default                                     array(                                         'name'                  => _x( $plural, 'taxonomy general name' ),                                         'singular_name'         => _x( $name, 'taxonomy singular name' ),                                         'search_items'          => __( 'Search ' . $plural ),                                         'all_items'             => __( 'All ' . $plural ),                                         'parent_item'           => __( 'Parent ' . $name ),                                         'parent_item_colon'     => __( 'Parent ' . $name . ':' ),                                         'edit_item'             => __( 'Edit ' . $name ),                                          'update_item'           => __( 'Update ' . $name ),                                         'add_new_item'          => __( 'Add New ' . $name ),                                         'new_item_name'         => __( 'New ' . $name . ' Name' ),                                         'menu_name'             => __( $name ),                                     ),                                          // Given labels                                     $taxonomy_labels                                      );                                      // Default arguments, overwitten with the given arguments                                 $args = array_merge(                                          // Default                                     array(                                         'label'                 => $plural,                                         'labels'                => $labels,                                         'public'                => true,                                         'show_ui'               => true,                                         'show_in_nav_menus'     => true,                                         '_builtin'              => false,                                     ),                                          // Given                                     $taxonomy_args                                      );                                      // Add the taxonomy to the post type                                 add_action( 'init',                                     function() use( $taxonomy_name, $post_type_name, $args )                                     {                                                                register_taxonomy( $taxonomy_name, $post_type_name, $args );                                     }                                 );                         }                         else                         {                             add_action( 'init',                                     function() use( $taxonomy_name, $post_type_name )                                     {                                                        register_taxonomy_for_object_type( $taxonomy_name, $post_type_name );                                     }                                 );                         }                 }             }                         private function default_meta_box( $meta, $custom_fields=array(), $data_id )              {                 // Begin the field table and loop                 echo '

	';                                                      /* Loop through $custom_fields */                 foreach( $custom_fields['custom_meta_fields'] as $field )                 {                                                                                $field_id_name  = self::uglify( $data_id )  . '_' . self::uglify( $field['label'] );                                                                      echo '' . $field['label'] . '	';                          //echo '' . $field['label'] . '<input type="text" name="custom_meta[' . $field_id_name . ']" id="' . $field_id_name . '" value="' . $meta[$field_id_name][0] . '" />';                 }                 echo '

|||	';                 foreach( $custom_fields['custom_meta_fields'] as $field )                 {                                                                                $field_id_name  = strtolower( str_replace( ' ', '_', $data_id ) ) . '_' . strtolower( str_replace( ' ', '_', $field['label'] ) );                                                                     echo '';                     echo self::input_fields( $field_id_name, $meta, $field,1 );                                              echo '	';                      }                 echo '-	+	';                 echo '

';             }                  private static function input_fields( $field_id_name, $meta, $field = array(), $repeatable=0 )              {                                 switch($field['type']) {                          // text                     case 'text':                         if($repeatable)                          {                             $i = 0;                             $html= '<input type="text" name="'.$field_id_name.'['. $i . ']" id="'.$field_id_name.'" value="'.$meta[$field_id_name][0].'" size="30" />
'.$field['desc'].'';                         }                         else                         {                             $html= '<input type="text" name="custom_meta['.$field_id_name.']" id="'.$field_id_name.'" value="'.$meta[$field_id_name][0].'" size="30" />
'.$field['desc'].'';                         }                     break;                          // textarea                     case 'textarea':                         $html= '<textarea name="custom_meta['.$field_id_name.']" id="'.$field_id_name.'" rows="4" width="100%">'.$meta[$field_id_name][0].'</textarea>
'.$field['desc'].'';                     break;                          // select                     case 'select':                         if($repeatable)                          {                             $i = 0;                             echo '<select name="custom_meta['.$field_id_name.']['. $i . ']" id="'.$field_id_name.'">';                             foreach ($field['options'] as $option) {                                                         echo '<option', $meta[$field_id_name][0] == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';                             }                             echo '</select>
'.$field['desc'].'';                              }                         else                         {                             echo '<select name="custom_meta['.$field_id_name.']" id="'.$field_id_name.'">';                             foreach ($field['options'] as $option) {                                                         echo '<option', $meta[$field_id_name][0] == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';                             }                             echo '</select>
'.$field['desc'].'';                              }                                                                    break;                                                }                      return $html;                  }                       /* Attaches meta boxes to the post type */             public function add_meta_box( $title, $fields = array(), $boxtype = NULL, $context = 'normal', $priority = 'default' )             {                 if( ! empty( $title ) )                 {                                        // We need to know the Post Type name again                     $post_type_name = $this->post_type_name;                                          // Meta variables                        $box_id         = strtolower( str_replace( ' ', '_', $title ) );                     $box_title      = ucwords( str_replace( '_', ' ', $title ) );                     $box_context    = $context;                     $box_priority   = $priority;                                      // Make the fields global                     global $custom_fields;                           $custom_fields[$title] = $fields;                                             add_action( 'admin_init',                             function() use( $box_id, $box_title, $post_type_name, $box_context, $box_priority, $fields, $boxtype )                             {                                                add_meta_box(                                     $box_id,                                     $box_title,                                     function( $post, $data )                                     {                                                                            global $post;                                                                                // Nonce field for some validation                                         wp_nonce_field( plugin_basename( __FILE__ ), 'custom_post_type' );                                                                            // Get all inputs from $data                                         $custom_fields = $data['args'][0];                                                                                // Get the saved values                                         $meta = get_post_custom( $post->ID );                                              // Check the array and loop through it                                         if( ! empty( $custom_fields ) )                                         {                                             switch($data['args'][1]) {                                                      case 'default_meta_box':                                                     self::default_meta_box( $meta, $custom_fields, $data['id'] );                                                 break;                                                      case 'side_display_settings':                                                     echo '

[clrdr_latest_news id="'.$post->ID.'"]

';                                                 break;                                                      default:                                                     /* Loop through $custom_fields */                                                     foreach( $custom_fields['custom_meta_fields'] as $field )                                                     {                                                                                $field_id_name  = strtolower( str_replace( ' ', '_', $data['id'] ) ) . '_' . strtolower( str_replace( ' ', '_', $field['label'] ) );                                                                                echo '' . $field['label'] . '<input type="text" name="custom_meta[' . $field_id_name . ']" id="' . $field_id_name . '" value="'. $meta[$field_id_name]. '/>';                                                     }                                                 break;                                             }                                                                                }                                          },                                     $post_type_name,                                     $box_context,                                     $box_priority,                                     array( $fields, $boxtype)                                 );                             }                         );                 }                    echo "
";                          //echo $this->post_type_name;                     //print_r($custom_fields);                     foreach($custom_fields as $title=>$fields )                     {                                                    // Loop through all fields                         foreach( $fields['custom_meta_fields'] as $field )                         {                             $field_id_name  = strtolower( str_replace( ' ', '_', $title ) ) . '_' . strtolower( str_replace( ' ', '_', $field['label'] ) );                                   print_r($fields);                             echo $field_id_name."
";                                  //update_post_meta( $post->ID, $field_id_name, $_POST['custom_meta'][$field_id_name] );                         }                          }                 echo "
";                       }                            /* Listens for when the post type being saved */             public function save()             {                 // Need the post type name again                 $post_type_name = $this->post_type_name;                                  add_action( 'save_post',                     function() use($post_type_name )                     {                         // Deny the wordpress autosave function                         if( defined('DOING_AUTOSAVE') && DOING_AUTOSAVE ) return;                              if ( ! wp_verify_nonce( $_POST['custom_post_type'], plugin_basename(__FILE__) ) ) return;                              global $post;                                                 if( isset( $_POST ) && isset( $post->ID ) && get_post_type( $post->ID ) == $post_type_name )                         {                             global $custom_fields;                                                        // Loop through each meta box                             foreach($custom_fields as $title=>$fields )                             {                                                            // Loop through all fields                                 foreach( $fields['custom_meta_fields'] as $field )                                 {                                     $field_id_name  = strtolower( str_replace( ' ', '_', $title ) ) . '_' . strtolower( str_replace( ' ', '_', $field['label'] ) );                                           update_post_meta( $post->ID, $field_id_name, $_POST['custom_meta'][$field_id_name] );                                 }                                  }                         }                     }                 );             }                  //add_action('save_post', 'save');                  public static function beautify( $string )               {                   return ucwords( str_replace( '_', ' ', $string ) );               }                    public static function uglify( $string )               {                   return strtolower( str_replace( ' ', '_', $string ) );               }                    public static function pluralize( $string )               {                   $last = $string[strlen( $string ) - 1];                        if( $last == 'y' )                   {                       $cut = substr( $string, 0, -1 );                       //convert y to ies                       $plural = $cut . 'ies';                   }                   else                   {                       // just attach an s                       $plural = $string . 's';                   }                        return $plural;               }            }          ?>      **scripts.php**               <?php          function clrdr_lnt_admin_scripts( $hook ) {              if(is_admin()) {                  wp_enqueue_script('jquery-ui-slider');                    wp_enqueue_script('custom-meta-js', plugins_url('js/custom.js', __FILE__));         }                 }          add_action( 'admin_enqueue_scripts', 'clrdr_lnt_admin_scripts' );      **custom.js**               jQuery(function(jQuery) {       jQuery('.repeatable-add').click(function() {           field = jQuery(this).closest('tr').clone(true);             fieldLocation = jQuery(this).parents('tbody tr');           jQuery('input', field).val('').attr('name', function(index, name) {                          return name.replace(/(\d+)/, function(fullMatch, n) {                                return Number(n) + 1;               });           })           field.insertAfter(fieldLocation, jQuery(this).closest('td'))           return false;       });            jQuery('.repeatable-remove').click(function(){               if ((jQuery(this).parents('tbody tr').siblings().andSelf().length)!=2)         {             jQuery(this).parents('tr').remove();               return false;           }     });            jQuery('.sortable-form-table tbody').sortable({           opacity: 0.6,           revert: true,           cursor: 'move',           handle: '.sort'       });       });       Thanks to all in advance.


title: Irregular TTFB and server wait time response

text: im having a hard time figuring this out. I've created a custom wordpress theme from scratch, following the best practices that I could. The site works great most of the time, with a load time that feels okay considering implementation of a lot of frontend stuff (typekit, youtube embed, vimeo, jquery etc). The problem is before the frontend ressources load. Sometimes a get a Waittime in the server response time that goes up to around 8-10 seconds, while being around 700ms most of the time. This makes it Extremely hard to test and troubleshoot. So the problem either lies in the server settings, or in my php code. Since its not happening all the time, I think i can conclude that its not the code, since its the same code running all the time, and therefore should have been slow all the time - but maybe thats a hasted conclusion. ![enter image description here](http://i.stack.imgur.com/b3v2g.png) Im really looking to get some input on how to further test this, or hear about any experience with irregular server wait time and TTFB. The website is currently in testmode at wm.minnie.mico.dk Note: Ive been through disableing plugins, but again that should have made it slow ALL the time right? also - im not caching at the moment, since I need to fix this issue first.


title: WordPress Child Theme - twentyeleven

text: This is my first attempt at creating a child theme based off the WP twentyeleven theme. To begin with, I am using MAMP on my mac and have the following directory structure:                applications/MAMP/htdocs/mysite/wp-content/themes/twentyeleven/style.css                                                       /mytwentyeleven/style.css      My URL in my browser appears as: `http://localhost:8888/mysite/` My problem/query is, when I activate my theme within WP 3.2 and then go and view it, there is no style been applied at all and the header and footer don't appear either. Based on my directory structure above, I am thinking my style.css within my mytwentyeleven directory is not importing original parent twentyeleven style.css file. I think my import path is wrong or perhaps something else. Again, this is my first time at creating a child theme. Here is my child theme style.css file contents:               /*     Theme Name: MyTwentyEleven Theme     Author: Me     Description: My TwentyEleven Child Theme CSS     Template: twentyeleven     */     @import url("../twentyeleven/style.css");      Can people please let me know what I have missed as the import url path is not working as from the looks of it, it's not finding the parent twentyeleven style.css file. Not sure if it's a MAMP thing but I just can't seem to see why it's not working/finding correct path back to parent stylesheet file. Thanks


title: Select query with two and two related taxonomies

text: is this possible for 2 taxonomy and 2 terms                $querystr = "      SELECT *      FROM $wpdb->posts      LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id)      LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)      LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id)      WHERE $wpdb->posts.post_type = 'shows'      AND $wpdb->posts.post_status = 'publish'      AND $wpdb->term_taxonomy.taxonomy = 'location'      AND $wpdb->term_taxonomy.taxonomy = 'genre'      AND $wpdb->terms.slug = 'california'      AND $wpdb->terms.slug = 'comedy'      ORDER BY $wpdb->posts.post_date DESC      LIMIT 10      ";          $pageposts = $wpdb->get_results($querystr, OBJECT);          if ($pposts):          foreach ($pposts as $post):     setup_postdata($post);          the_title();     echo '<br'>;     the_content();          endforeach;     endif;      i tried putting this code above but the doesnt display anything; I want to display posts that has 2 term name and 2 taxonomy like for example: sampleposts [showlocation_tax][genre_tax] showlocation_tax has terms -california -LA while genre_tax - comedy - fashion what i want to do is i want to show all post for example: posts from california with comedy shows something like that i will really appreciate your help a lot


title: WordPress Multisite with multiple domains using Nginx

text: I'm growing grey hair here. I've tried so many things and yet I can't get a grasp on how to set this up. Found tons of guides but no one goes through all aspects, which are:   * A single WP Multisite install that handles several domain based (8 to be exact) sites   * Site running on Nginx Following this guide (https://www.digitalocean.com/community/articles/how-to- configure-single-and-multiple-wordpress-site-settings-with-nginx), I've set up a server (Ubuntu 10.3) with everything installed and being able to run the WP install through the default sites-enabled config. But as I apply the configs in the tutorial I come to a halt. This is my current setup http://pastebin.com/6iSK4H1M In the tutorial under the example.conf, root is set to point to a directory which I assume will be the same for all sites ("example" dir being the WP install). If I run the default IP / localhost I can access and login to the WP install. But as I add a domain under sites-enabled (and remove the default config) I just get a notification that the site can't be displayed. Have made sure to clear dns caching. In WP admin, I've created a new site and set it as a subdomain with a wildcard (*.example.com), and applied this to wp-config.php -               define('WP_ALLOW_MULTISITE', true);     define('MULTISITE', true);     define('SUBDOMAIN_INSTALL', true);     define('DOMAIN_CURRENT_SITE', 'localhost'); // Does it matter if I put localhost or IP here?     define('PATH_CURRENT_SITE', '/');     define('SITE_ID_CURRENT_SITE', 1);     define('BLOG_ID_CURRENT_SITE', 1);      And - is a domain mapping plugin really mandatory to get this to work? Any help would be greatly appreciated!


title: Create a page that automatically redirects to latest post of a specific tag/category?

text: I'm looking to make a URL like for example:               http://localhost/latest-news      Where the page for `latest-news` will automatically redirect to the latest news article (article with `news` category tag). I then will need to use the link /latest-news in a few different places (menu, and a slider on the front page).


title: How to get correct URLs in network wide menu (Multisite)?

text: I'm using this function to switch to my main website's navigation and display it on all sub sites in my multisite network. Ideally the links should have the following format: http://www.mysite.com/navigation-link but on the sub-sites the urls are http://www.mysite.com/subsite/navigation- link Obviously these pages don't exist so it's just showing a blank page. Any idea how I could make sure the urls are like the first example and how I might incorporate that into my function? function wp_multisite_nav_menu() {                   global $blog_id;              $args = array(                 'menu' => 'Main Menu',                 'theme_location' => 'main-nav'                  );              $main_blog = 1;               $main_blog = absint( $main_blog );                   if ( !is_multisite() || $blog_id == $main_blog ) {             echo wp_nav_menu( $args );             return;         }              else {              switch_to_blog( 1 );              echo wp_nav_menu( $args );              restore_current_blog();              }          }


title: Batch users creation

text: I would like to share a document with about 140 users after password authentication and I want to avoid to create manually all the 140 accounts. Is it possible to create them quickly? **UPDATE** : usernames to add are stored into a text file. The question is focused on the batch users creation because I will create a password-protected area where all the users will access to download the document.


title: Finding URI in Child Theme

text: Which is best way to find URI in child Theme.               <?php echo get_template_directory_uri(); ?>     <?php bloginfo('template_directory'); ?>      Below given code works but it has "stylesheet" in it, sounds like its a hake to find URI. Is this the only solution ?               <?php echo get_stylesheet_directory_uri(); ?>     <?php bloginfo('stylesheet_directory'); ?>


title: wp_nav_menu() loses 'current-menu-*' classes on single product page within category

text: I have my menu set up like so:   * **Shop Online** (WPeC 'Products Page' page)      * **Product Category** (WPeC Category)     * **Product Category** (WPeC Category)        * **Product Sub Category** (WPeC Category)       * **Product Sub Category** (WPeC Category)     * ... Single product pages are viewable from any category or sub category page as they both show the product listing view. Now when I select either _Shop Online_ , a product category or sub-category the menu updates it's CSS classes to match the current hierachy with the usual (example) `current-menu-page`, `current-menu-ancestor` and `current-menu- parent` among others. It doesn't matter if I click on the menu or the category listing on the _Shop Online_ page to get there. For some reason as soon as I view a product singularly (`domain.tld/product- cat/sub-cat/product-single` or `domain.tld/product-cat/product-single`), the menu classes are removed and I lose my menu highlighting because the classes are no longer there. Is there a way that I can reflect the single product view in the menu by highlighting the current category/ies that the product is in, as well as the `Shop Online` menu item/link respective of how you got to the product? WP v3.5 WPeC v3.8.9.4


title: Why don't some template tags work when querying information on single.php?

text: I'm trying to fetch content about the current post into the header.php of my theme (to dynamically insert Facebook OpenGraph Metadata). Since I'm on a single post page, shouldn't it be able to run functions like `the_content()` or `wp_get_attachment_thumb_url()`?               <?php if (is_single()) {                <meta property="og:title" content="<?php echo get_the_title()." - Advocate Daily" ?>" />               <meta property="og:description" content="<?php string_limit_words(the_content(), 15);" ?> />               <meta property="og:image" content="<?php echo wp_get_attachment_thumb_url(); ?>" />     <?php } ?>      In the above example, the first tag works, but the content of the other two isn't outputted. Does this mean certain template tags needs to be in the               if ( have_posts() ) : while ( have_posts() ) : the_post();      loop? Do I need to declare this loop again in the header?


title: What's the easiest way to setup SMTP settings programmatically?

text: Assume we have blank WP site and we want to setup SMTP settings programmatically in our plugin or theme. What's the easiest way to do it without changing core files?


title: Click link on plugin/theme page and open the contextual help on a specific tab

text: I've added a help section using the add_help_tab() function. I'd like to be able to click a link somewhere on the theme/plugin page and have the help panel open at whichever tab I need. Can someone help me out with the required JS for this? Each tab panel has a unique hash link associated with it so I'd need to use this somehow I'm guessing               /themes.php?page=theme_options#tab-panel-general


title: Integrating Meet-up feeds into the regular portion of a Wordpress blog

text: Good day, This is the first question I've ever posted on StackExchange. I've set up a WordPress site for our local makers group, www.redmountainmakers.org. My problem is that I've been asked to incorporate the feed from our meet-up group (Red Mountain Makers on Meet-up, Birmingham AL) into the main blog feed so that as much as possible, we are posting in one location and sending content out to our Facebook page, the blog, etc. The goal is to post once, propagate many times. Using Meet-up's OAuth API, I can pull feed in, but I can't pull feed in _and_ add new content at the blog itself without seriously breaking things. I've looked at HootSuite as a publish and schedule once -> send to many destination solution, but from what I've been able to read thus far, it doesn't appear to support Meet-up. Has anyone else run into this problem, worked out a solution or have any pointers regarding a social media management solution that can push posts to Meet-up, WordPress, Facebook and has an API I can use to code up addtional custom solutions? Will be working on this again as soon as my exams are over May 11th. *Have lurked around the edges for a good two years, but have been able to find what I've needed from other peoples earlier questions and answers.


title: Custom query with category exclusion and post-meta "whitelist"

text: I have two widgets, one shows **News** while the other shows everything except News (We'll call the second one **Blog** ). The blog portion is currently working correctly. The News posts are either categorized as `In the News` OR have the custom post meta `in-the-news`, set to 1. It's important to note that not all posts will have the custom post meta defined. The main problem I am facing is that I need to compare post meta based on whether the post is categorized one way or another. **I may need to do a custom database query for this behavior, at least for the News.** Is it possible to do a custom query and convert it to a standard WP_Query object? * * * ## What I have tried Query for **News**. **Problem:** Only shows posts within category 75 that have `in-the-news = 1`. **Desired result:** Show all posts from category 75 regardless of the value of `in-the-news`, and any additional posts from outside the category which have `in-the-news = 1`               query_posts(array(       'ignore_sticky_posts' => true,       'posts_per_page' => 3,       'cat' => "75", // Only posts within category 75 (News)            // Including posts tagged to show "In the News"       'meta_query' => array(         'relation' => 'OR',         array(           'key' => 'in-the-news',           'value' => '1',           'compare' => '=',         ),         array(            'key' => 'in-the-news',           'compare' => 'NOT EXISTS',           'value' => '',         ),       )     ));      Here is the query for the **Blog** : This query appears to be working correctly, showing all posts outside of category 75, and hiding posts with `in-the-news = 1`.               query_posts(array(       'ignore_sticky_posts' => true,       'posts_per_page' => 3,       'cat' => "-75", // All posts EXCLUDING those in category 75 (News)            'meta_query' => array(         'relation' => 'OR',         array(           'key' => 'in-the-news',           'value' => '0',           'compare' => '=',         ),         array(            'key' => 'in-the-news',           'compare' => 'NOT EXISTS',           'value' => '',         ),       )     ));      * * * ## Solution Thanks to `s_ha_dum` for the amazing examples, here is the final query I am using. The logic here is that we do a custom MySQL query for an array of post IDs, then do a standard WP_Query using the returned IDs. **Note:** The logic here was a bit more complicated than the original post. Basically, we originally had "News" and "Blog". But now we also have "Risk". Also, the `in-the-news` post meta was changed to `show-in-blog` as we reverse the functionality. I can't expect anyone else to ever understand the reasoning for this in the first place, as even I think it is ridiculous (But the client wants it, so be it!) Here is my query, for the "Blog" widget. Slight variations are made for the "News" area. I'm not sure if the query could be cleaned up. I'm also not sure if it's a bad idea to perform so many SELECTs within the same query.               global $wpdb;          $query = // Splitting the SQL query to it's own code block for syntax highlighting!      * * *                 SELECT `ID`       FROM {$wpdb->posts} posts       WHERE (              /* Exclude posts in News (94)             Ignore show-in-blog option for News here,             as News is displayed on the same page */         94 NOT IN (            SELECT `term_taxonomy_id`            FROM {$wpdb->term_relationships}           WHERE `object_id` = posts.`ID`         )              AND              /* Exclude posts in Risk (96),             But show Risk posts that have the postmeta "show-in-blog" */         (                96 NOT IN (              SELECT `term_taxonomy_id`              FROM {$wpdb->term_relationships}             WHERE `object_id` = posts.`ID`           )           OR           (             96 IN (                SELECT `term_taxonomy_id`                FROM {$wpdb->term_relationships}               WHERE `object_id` = posts.`ID`             )             AND             1 IN (               SELECT `meta_value`                FROM {$wpdb->postmeta}               WHERE                `meta_key` = 'show-in-blog'               AND `post_id` = posts.`ID`             )           ) /* OR */              ) /* AND */            ) /* WHERE */            ORDER BY `post_date` DESC;      * * *               $args = array(       // Only include IDs returned by the above query       'post__in' => $wpdb->get_col( $query ),       'posts_per_page' => 10,     );          $wp_query = new WP_Query( $args );          get_template_part('loop', 'frontpage');


title: best way to run a php script away from the template?

text: I'm looking for some inspiration on the best way to run a php script away from the template. I know that the wordpress core files won't have loaded, so I am wondering what workgflow you follow when doing this? cheers


title: How to: Simple Nested Shortcode

text:
Im trying to wrap a shortcode inside of a "user loggeed in" shortcode. Here are the two shortcodes and my setup in WYSIWYG               function wpfc_logged_in( $atts, $content = null ) {         if (is_user_logged_in() )           {             return do_shortcode($content);           }     }          add_shortcode('loggedin', 'wpfc_logged_in');               function info_box( $atts, $content = null  ) {             extract( shortcode_atts( array(             'type' => 'tip',             'icon' => ''         ), $atts ) );           $return = '

'.$content.'

';         return $return;      }     add_shortcode('info_box', 'info_box');      WYSIWYG:               [loggedin]     [ info_box type='setting' ]content text[ /info_box]     [/loggedin]


title: open graph image being overwritten by gravatar logo?

text: example page; http://www.c-art.org.uk/2011/07/01/jenny-abbot/ some reason the gravatar image is overwriting the posts featured image thumb (100x100). Nnot sure how its doing it! How can i get rid of it?               <meta property="og:title" content="Jenny Abbot" />     <meta property="og:description" content="C-Art — Cumbria Artist Open Studios, Jenny Abbot Artist Index PaintingC-Art"/>     <meta property="og:url" content="http://c-art.modernactivity.co.uk/?p=1254"/>     <meta property="og:image" content="http://www.c-art.org.uk/wp-content/uploads/Summer-at-Sea-Wood-100mm-100x100.jpg"/>     <meta property="og:type" content="article"/>     <meta property="og:site_name" content="C-Art"/>      best, dc.


title: how to show images without passing it to timthumb.php file for resizing

text: currently I m showing post image and it's exceprt on my index page of website. Beacuse of this site is slow downs as each image is passed to timthumb.php file. I want to change in code so that image is displayed direct without passing to timthumb.php file for resizing. Is there any way to achieve this?? Thanks in advance..


title: Making a parent directory writable by the server

text: Uploading an image to add to a page, I got a message saying: Unable to create directory... Is its parent directory writable by the server? Assuming the issue is that the parent directory needs to be made writable by the server, how do I make the parent directory writable by the server? Thanks, Richard


title: How can I abstract code out of a template by using functions.php

text: I'm creating a template, and one of the files is getting overloaded with pig- ugly mixed html and php. At first I thought that maybe I should cut out chunks of the code, and call them using include(). Then I thought - maybe there is a wordpress way to do things. Perhaps I should abstract out my logic from the templates, by putting the custom loop in functions.php, and then calling it somehow from the template. How do I do this?


title: Can a thumbnail of an animated gif be animated?

text: I have an animated gif I want to show in two places, having two different sizes. I am creating two sizes in my functions.php, using               add_image_size( 'small-feature', 500, 300 );     add_image_size( 'gallery-thumb', 120, 9999 );      If the uploaded file is 500 x 300 px, it will keep the animation, as it no resizing happens. If the image is to be resized, the animation is lost. Is there a way I can resize these images and still keep the animation in the original .gif file?


title: bulk post_content update

text: I need to replace all post_content in a particular tag/category to the desired one i have. is their a plugin to accomplish it or is their a query to finish this. Iam sick of doing this manually, is their a way to accomplish it.


title: Widget editor not displaying in Dashboard

text: I'm not sure if this is because of the new 3.9 update, because I haven't had to mess with any widgets in a while, but my active widgets won't display in the editor anymore. I've uploaded a screen shot of how it looks here: http://i.imgur.com/Ctbzo3S.png This may or may not be related, but my Screen Options drop-down does nothing when I click on it and neither does anything else within that widget window. Here are the errors I'm getting: >   * PHP Fatal error: Call to undefined function select_input() >   * PHP Notice: Trying to get property of non-object PHP Strict Standards: > Only variables should be passed by reference >   * PHP Notice: has_cap was called with an argument that is **deprecated** > since version 2.0! >   * PHP Deprecated: Assigning the return value of new by reference is > deprecated >   * PHP Notice: get_settings is **deprecated** since version 2.1! >


title: Is there a WP Way of getting a filehandle?

text: I'm using an external CSV reading library that takes a filehandle (resource) as an argument. I'm using wp_handle_upload() to actually process and store the file in the Uploads directory, but that returns the file path, not a resource. Is `$filehandle = fopen( $file['file'], 'r' )` acceptable here, or is there a better WP alternative? I don't see anything that fits the bill in `file.php`, or anywhere else I've looked.


title: I am trying to make a page in the admin section similar to the appearance of the Profile page for users

text: I am working on a plugin and would like to know the correct way I go about creating a page that will look like the users page (image attached at the buttom) The fields will be different and will add data(the data is unrelated to user information) to a new table created by the plugin . So it does not seem like the Settings API will help me. I am strictly talking about appearance. Should I just use the css built in wordpress or is there some sort of function that will help me create all the fields?![enter image description here](http://i.stack.imgur.com/t7Fo7.png)


title: Which Membership Plugins Allow Registered Users To Bookmark Posts?

text: I'm having some trouble finding plugins (free & premium ok) that would allow a registered member to essentially bookmark any post of interest to them while searching, and then revisit that bookmark through their user profile whenever their logged back in. The only plugin that I'm aware of that has a related feature is the premium Wishlist Member plugin. Specifically, what are other membership plugins that can achieve this? Thank you in advance!


title: How to insert an array of terms using wp_insert_term?

text: WP provides a function to insert terms:               <?php wp_insert_term( $term, $taxonomy, $args = array() ); ?>       I have 60 $terms, each has its own $args, I want to prepare the 60 terms as an array, then, insert them at once. Is this posible? How?


title: wp_mail function timing out

text: I have the following function. This is part of a membership-based site. When a post of the type "message" is moved to Publish status, it should send an email to all users who belong (custom user meta) to the district(s) that are checked (taxonomy) when the post is drafted. If I send to a small group, it seems to work. If I send to all the districts, it hangs and no messages appear to go out. I tried limiting it into chunks (25) to ease the pain, but does not help. Any thoughts besides telling the client to only send to one group at a time?               add_action('publish_messages', 'messages_notify', 10, 3);     function messages_notify() {         global $post;         // if post already published, abort         if($post->post_status == 'publish') {             return;         }         // get districts ticked, else abort         $districts = get_the_terms($post->ID, 'message_district');         if(empty($districts)) return;              // query members who belong to one of the districts ticked         $the_districts = array();         $district_args = array('relation' => 'OR' );         foreach($districts as $district){             $the_districts[] = $district->name;             if ($district->name == 'Northeast') {                 $district_args[] = array('key' => 'whprms_district_ne', 'value' => 1);             }             if ($district->name == 'North Central') {                 $district_args[] = array('key' => 'whprms_district_nc', 'value' => 1);             }             if ($district->name == 'Southeast') {                 $district_args[] = array('key' => 'whprms_district_se', 'value' => 1);             }             if ($district->name == 'Southwest') {                 $district_args[] = array('key' => 'whprms_district_sw', 'value' => 1);             }             if ($district->name == 'West') {                 $district_args[] = array('key' => 'whprms_district_w', 'value' => 1);             }         }         $district_members = get_users(                  array(                 'meta_query' => $district_args,                 )         );              $attachment_args = array('post_type' => 'attachment', 'orderby' => 'date', 'order' => 'ASC', 'numberposts' => -1, 'post_status' => NULL, 'post_parent' =>$post->ID);         $attachments = get_posts($attachment_args);         if ($attachments) {             $att_array = array();             foreach ($attachments as $attachment) {                 $att_array[] = get_the_title($attachment->ID);             }         }              // message only users with desired role(s)         $bcc = array();         foreach($district_members as $district_member) {             if(user_can($district_member->ID, 'board_members') || user_can($district_member->ID, 'members')) {                 $bcc[] = $district_member->user_email;             }         }              $subject = 'WHPRMS Message: '.$post->post_title;         $message = 'New message posted by ';         if(user_can($post->post_author, 'administrator')) {             $message .= get_the_author_meta('user_nicename', $post->post_author)."\n\r";         }         else {             $message .= get_the_author_meta('first_name', $post->post_author).' '.get_the_author_meta('last_name', $post->post_author)."\n\r";          }              $message .= 'Excerpt: '.stripslashes(substr($post->post_content, 0, 240)).'...'."\n\r";         $message .= 'Link: '.get_permalink($post->ID)."\n\r";              $message .= 'District(s): '.implode(', ', $the_districts)."\n\r";         if (!empty($att_array)) {             $message .= 'Attachment(s): '.implode(', ', $att_array)."\n\r";         }              $message .= 'You are receiving this message because you belong to one of the districts mentioned above.';              $chunked_bcc = array_chunk($bcc, 25);              foreach($chunked_bcc as $bcc_chunk){             $headers = array();             $headers['Bcc'] = 'BCC: '.implode(', ', $bcc_chunk);             wp_mail('no-reply@whprms.org', $subject, $message, $headers);         }          }


title: Use the_content outside the loop

text: I was trying to get first 100 words of the content in the header, and I use the following snippet to get the first 100 words in the loop, but is it possible to get the value outside the loop:               $cstring = get_the_content( '' );     $newcString = substr( $cstring, 0, 100 );     echo'<p>' . $newcString . '</p>';


title: Change the Permalink for wordpress attachment

text: My attachments are currently rewritten from   `http://localhost/?attachment_id=3` to   `http://localhost/images/image-title` using @Bainternet's answer here.                $new_rules['images/(\d*)$'] = 'index.php?attachment_id=$matches[1]';        However, wordpress still refers to the link as the default `http://localhost/?attachment_id=3`. Wordpress functions such as the_permalink, get_attachment_url, get_attachment_image_src, etc. all use the default format of `http://localhost/?attachment_id=3`. I am able to access the image as intended if I manually type in the rewritten format `http://localhost/images/image-title`. How can I get wordpress to use my custom rewrite for the permalink especially on the admin page? **EDIT:** reworded question for specificity and correctness:   How do I override `the_permalink` to use the format `/images/image-title` instead of `/?attachment_id=ID`?   I can get image-title using `$post->post_title`. **EDIT #2:**   For anyone reading this question in the future, I found it best to use `$post->post_name` for the link to insure uniqueness.   `/images/post_title`


title: Define custom Page Template without its own .php file

text: Is there any way of defining a Page Template from some function/filter/hook, without having any .php file containing the comment at the top of the page to declare the Template Name? * * * For example, instead of doing this: ### some-custom-page-template.php               /**     * Template Name: Some Custom Page Template     */      ### another-custom-page-template.php               /**     * Template Name: Another Custom Page Template     */      I wonder if I can do something like: ### functions.php               wp_some_function_to_define_templates( 'Some Custom Page Template' );     wp_some_function_to_define_templates( 'Another Custom Page Template' );      * * * **_EDIT_** : I'm writing a _complex_ and kind of _experimental_ WP theme - It is as Object-Oriented as WP lets it to be, I have Controller classes to decide what to display in each page, DAO classes to retrieve data from DB, Twig templates to generate the views and so on... I've spreaded the code so much, that my Page Templates have become just a line of code where I call some Controller and let it do the job, to finally render a Twig template. So I decided to move that call to the Controller, to inside the `template_include` filter, so that I don't even need to put any code in the Page Templates... I might get rid of Page Templates, but I still need them to _group_ pages somehow, to set some Advanced Custom Fields groups for them, etc... So I ended up with about 15 PHP files that contain only a comment at the top with some Template Name, which is exactly what I'd like to avoid by defining those templates from some function... Am I trying to _reinvent the wheel_? Maybe in some sense, but I think it's becoming a really _cool_ theme, very maintenable and modifiable...


title: Setting posts per page in query_posts

text:
Bear with me here.. The default posts per page in the admin area is 10. During some testing I wanted to change the posts per page for my custom post archive to 2 (in WP 3.1). The problem is that I only have 4 posts, so there should be 2 pages with 2 posts on each, but because the default is at 10, going to /page/2 returns error-404 (assuming because with 10 posts per page there wouldn't be a second page) The only way to get around this was to set the default in the admin area to 1, but it's not really ideal as i now have to do a custom query_post for all post type archives to set the posts per page. Does anyone have a better way to do this, or any ideas? Thanks. archive-project.php:               <?php get_header(); ?>              <?php             global $wp_query;             query_posts(array_merge($wp_query->query, array(                 'paged'          => get_query_var('paged'),                 'posts_per_page' => 2             )));         ?>
<?php _e('Previous work', 'fullycharged'); ?>
              <?php if (have_posts()): while(have_posts()): the_post();?>             <a href="<?php the_permalink(); ?>" id="post-<?php the_ID(); ?>" <?php post_class('launch col col-' . $i); ?>>                 <?php the_title(); ?>                 <?php the_content(); ?>                      <?php endwhile; endif; ?>              <?php if ($wp_query->max_num_pages > 1): ?>

<?php next_posts_link( __( '← Older posts', 'twentyten' ) ); ?>

<?php previous_posts_link( __( 'Newer posts →', 'twentyten' ) ); ?>

         <?php endif; ?>          <?php get_footer(); ?>      register post type:               register_post_type('project', array(         'capability_type' => 'post',         'has_archive' => true,         'hierarchical' => false,         'labels' => array(             'name' => __('Projects', 'fullycharged'),             'singular_name' => __('Project', 'fullycharged'),             'all_items' => __('All Projects', 'fullycharged'),             'add_new_item' => __('Add New Project', 'fullycharged'),             'edit_item' => __('Edit Project', 'fullycharged'),             'update_item' => __('Update Project', 'fullycharged')         ),         'menu_icon' => get_stylesheet_directory_uri() . '/images/monitor-off.png',         'menu_position' => 5,         'public' => true,         'publicly_queryable' => true,         'exclude_from_search' => false,         'rewrite'  => array('slug' => 'work', 'with_front' => false),         'supports' => array('title', 'editor', 'thumbnail', 'custom-fields')     ));


I'm receiving this error: [27-Jun-2012 18:22:39 UTC] PHP Fatal error: Call to undefined function plugin_basename() in /XXXX/public_html/wp- content/plugins/price-update/price-update.php on line 68:                           //We set the plugin basename here, could manually set it, but this is for demonstration purposes                 $this->plugin_basename = plugin_basename(__FILE__);      in this block of code:               class PriceUpdate extends mtekk_admin     {             protected $version = '0.0.1';             protected $full_name = 'Price Update';             protected $short_name = 'Price Update';             protected $access_level = 'manage_options';             protected $identifier = 'pr_upate';             protected $unique_prefix = 'prud';             protected $plugin_basename = 'price-update/price-update.php';             protected $opt = array();             /**              * __construct()              *              * Class default constructor              */             function __construct()             {                     //We set the plugin basename here, could manually set it, but this is for demonstration purposes                     $this->plugin_basename = plugin_basename(__FILE__);                     register_deactivation_hook(__FILE__, array($this, 'deactivate'));                     add_action($this->unique_prefix . '_cron_hook', array($this,'cron_handle'));                     //Register some of our custom taxonomies                     add_action('init', array($this, 'wp_init'), 0);                     add_action('wp_footer', array($this, 'footer'));                     //We're going to make sure we load the parent's constructor                     parent::__construct();             }      However, its defined above:                       protected $plugin_basename = 'price-update/price-update.php';      any ideas?


title: Saving custom fields to a custom taxonomy

text: I am trying to create a custom field for a custom taxonomy. update_post_meta works great with posts. Taxonomies are not posts so this won't work.               <?php update_post_meta($post_id, $meta_key, $meta_value, $prev_value); ?>       How would I save a custom field within a custom taxonomy? Other solutions include the options_table (bad!) or creating a custom table (cumbersome). Is there another, canned solution or function to help with this?


title: How to filter get_avatar?

text: I want to use local avatar system for my wp website , I want to filter the `get_avatar()` function so it will return the avatar from my server instead of the default gavatar . I have the following code :               class local_avatar{                  function __construct(){                 add_filter('get_avatar',array($this,'get_avatar'));             }                  public function get_avatar($avatar , $id_or_email , $size = '96'  , $default , $alt = false){                      global $wpdb;                 $upload = wp_upload_dir();                      if(is_numeric($id_or_email)){                     // the user id                     $image = get_user_meta($id_or_email,'_ahaali_avatar',true);                     if($image){                         $image_path = $upload['baseurl'].'/avatar/'.$image;                         $ahaali_avatar = '';                     }else{                         $image_path = 'http://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s='.$size;                         $ahaali_avatar = '';                     }                 }elseif(is_string($id_or_email)){                     // the user email                     $user_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM wp_users WHERE user_email = %s",                     $id_or_email));                     $image = get_user_meta($user_id,'_ahaali_avatar',true);                     if($image){                         $image_path = $upload['baseurl'].'/avatar/'.$image;                         $ahaali_avatar = '';                     }else{                         $image_path = 'http://0.gravatar.com/avatar/ad516503a11cd5ca435acc9bb6523536?s='.$size;                         $ahaali_avatar = '';                     }                 }                 return $ahaali_avatar;             }              }      And it returns the following errors : > Warning: Missing argument 2 for local_avatar::get_avatar() in > /home/subhi/public_html/work/example.com/wp- > content/plugins/ahaali_avatar/core.php on line 40 > > Warning: Missing argument 4 for local_avatar::get_avatar() in > /home/subhi/public_html/work/example.com/wp- > content/plugins/ahaali_avatar/core.php on line 40 How can I solve this?


title: Display a random customposttype2 excerpt in single-custompostype1.php that shares same taxonomy

text:
OK - Looked everywhere for this one. **Details:** Custom Post Type #1 = 'product' > registered taxonomy 'productranges' Custom Post Type #2 = 'testimonial' > registered taxonomy 'testimonials' Both CPTs share categories 'Complete Food' , 'Treats', etc.. for example **Question:** How can I display a random post excerpt of the same shared-category from a 'Testimonial' post into 'Product' post? In a sense linking the Testimoinals to the Products. I've used the following but it only shows a random post from all the categories, I need it to output from the current-shared category being viewed:               <?php     $posts = get_posts('post_type=testimonial&issue=$issueid&post_status=publish&numberposts=1&orderby=rand');          foreach ($posts as $post) : setup_postdata($post); ?>
<?php the_title(); ?>
     <?php the_excerpt('
'); ?>read more...           <?php endforeach; ?>     <?php          //Reset Query     wp_reset_query();?>      Cheers if you can help!


title: next_posts_link returns same content of 1st page

text: Pagination seems to work fine... I have 21 posts... and it will go to 3 pages... however... every page shows 10 posts and the same content as the first page....               <?php     $temp = $wp_query;     $wp_query= null;          $args = array(         'post_type' => 'a-reports',         'post_status' => 'publish'     );     $wp_query = new WP_Query( $args );     if ( $wp_query-> have_posts() )     {     while ($wp_query->have_posts()) : $wp_query->the_post();      ?>     <a target="blank" href="<?php the_permalink(); ?>">Report     <?php     endwhile;          <?php next_posts_link('Older Entries »');           //clear again     $wp_query = null;     //reset     $wp_query = $temp;     ?>


title: User Registration Allow Same Email

text: Have researched this problem and can't find a solution for Wordpress 3.7.1 running as a single site. Problem: Allow a user to register on the site and ignore the error WP throws back if email is already registered - "This email is already registered, please choose another one." Have tried writing my own plugin, something in the way of               if($errors['field'.$field->id] == 'This email is already registered, please choose another one.')     unset($errors['field'.$field->id]);      Any help on this would be greatly appreciated. PS. i) I know its not ideal to allow same email for registration but can't see another solution to allow same family members to register under different usernames but same family email. ii) The answer on a previous question did not work on single site, using the code               add_filter('pre_user_email', 'skip_email_exist');      this is why I had to ask this question for single site solution.


title: Search filter triggered & sort by custom post type

text: I am using a plugin (Relevanssi) and a custom function to sort the search results by custom post types (see below). _This is working great_.               add_filter('relevanssi_hits_filter', 'separate_result_types');     function separate_result_types($hits) {         $types = array();              // Split the post types in array $types         if (!empty($hits)) {             foreach ($hits[0] as $hit) {                 if (!is_array($types[$hit->post_type])) $types[$hit->post_type] = array();                                         array_push($types[$hit->post_type], $hit);             }         }              // Merge back to $hits in the desired order         $hits[0] = array_merge((array)$types['cats'], (array)$types['dogs'], (array)$types['horses']);        return $hits;          }      The problem arises when I want to display search results on a per-type basis. For example, when on the "Search Pets" page (which is a page template, search- pets.php) I want to display only search results for the above CPTs. When on the "Blog" page (standard WP posts), I want to display only blog posts, and if on a non custom CPT page, display page results. I thought that by adding an if/else statement (see below) that would work.               add_filter('relevanssi_hits_filter', 'separate_result_types');     function separate_result_types($hits) {         $types = array();              // Split the post types in array $types         if (!empty($hits)) {             foreach ($hits[0] as $hit) {                 if (!is_array($types[$hit->post_type])) $types[$hit->post_type] = array();                                         array_push($types[$hit->post_type], $hit);             }         }              // If post type = dogs, cats, horses         if (in_array( get_post_type(), array('dogs','cats','horses'))){         // Merge back to $hits in the desired order         $hits[0] = array_merge((array)$types['dogs'], (array)$types['cats'], (array)$types['horses']);        // return $hits;              } else {               // If post type = posts, page         if (in_array( get_post_type(), array('post','page'))){         // Merge back to $hits in the desired order         $hits[0] = array_merge((array)$types['post'], (array)$types['page']);         //return $hits;              }}         return $hits;     }      But it only seems to return the top filter results. Any idea where I'm going wrong, or if my logic will even work? Very much a PHP noob. Thanks! Ramsey


title: How do I setup htaccess for 301 redirects, post Joomla to Wordpress migration?

text: I've almost completed the tedious task of migrating a relatively complex Joomla site over to Wordpress. The (more or less) final stage I am wishing to figure out is the 301 redirections. I've spent the past few hours researching this topic, but I've not found any tips specific to my situation (particular the sub-directory structure). I'd greatly appreciate some hand-holding. I don't wish to mess this up because I realise it could impact the hundreds of incoming links from search engines. **Here's the background information:**   * Joomla was installed in `www.domain.com/site/`   * Wordpress has been installed in `domain.com/wordpress/`   * All Joomla articles were migrated to Wordpress installation, and post IDs were maintained.   * Joomla URI permalink structure for articles is: `www.domain.com/site/YYYYMMDD###/...` **e.g.** `www.domain.com/site/20110623398/articles/category-slug/article- slug.html` The ### is the unique ID of the article on Joomla (aka post ID).   * The posts in Wordpress have the same unique ID. Thus `www.domain.com/site/20110623398/articles/category-slug/article-slug.html` can be redirected to `domain.com/?p=398`   * There are a few other URI structures I'll need to handle. But I will address that once I have the redirection of the articles figured out. **MY QUESTION (IN PARTS)**   1. How do I set up the .htaccess file so that all incoming links to joomla articles have the unique ID extracted and then redirect to `/?p=UID` (as a 301 redirect)?   2. How do I do this in such a way that the site will always use or display `domain.com/` as the home directory (with and without the www), whilst keeping the site located in `/wordpress` (or in `/site`, if that works better for the redirects - which I suspect it will). I don't, however, want the site to ever load up and show a `/wordpress/post- name-etc/` type URI (or `/site/post-name-etc/` URI). Meaning I want the `/wordpress/` or `/site/` part to always be removed from the end user point of view (including search engines). I believe the .htaccess file is also used for this.   3. Along with many other sites and posts, I have read the info related to Giving Wordpress It's Own Directory on the WordPress Codex. Point #4 on that article says, "Copy (NOT MOVE!) the index.php and .htaccess files from the WordPress directory into the root directory of your site (Blog address).", but I have a .htaccess file in the root already, and it has lots of code in it. Is it okay to just copy the index.php and not the WP htaccess file? * * * Points **(2)** , combined with **(1)** , is where I came a bit unstuck. Getting all the articles on `domain.com/site/` to redirect to `domain.com/`, and for the correct page to come in from `domain.com/wordpress` without displaying the `/wordpress/` part. As mentioned above, I suspect it may be best if I move the wordpress site to `domain.com/site` (and change it's configuration file home directory settings accordingly).


title: WP_Query not retrieving by random order under parent

text:
I currently have TWO subpages under parent page ID 43. Client testimonials.. Anyway. I have the random order thing in the query $args but the order never changes. What could I be missing?               wp_reset_query();     $args=array(       'post_parent' => 43,       'post_type' => 'page',       'post_status' => 'publish',       'posts_per_page' => 2,        'orderby'=>'rand'     );     $my_query = new WP_Query($args);     if( $my_query->have_posts() ) {         while ($my_query->have_posts()) : $my_query->the_post();         ?>
<? echo get_post_meta($post->ID,'subtitle', true);?>

<? echo get_the_excerpt(); ?>
         <?         endwhile;     }     wp_reset_query();  // Restore global post data stomped by the_post().


title: allow photo/video in comments

text: I have a request to allow subscribers to upload/embed photos or video in comments. Is anyone aware of an existing plugin to handle this, I couldn't find anything suitable. I found examples of code to change the tags that are stripped from comments which would allow embedding, but I'm not sure that really fits the bill and would require change to a core file.


title: When to use the Filesystem API? Should I use it at all?

text: I'm wondering when it is recommended to use the Filesystem API, and whether it's useful at all? WordPress seems a little inconsistent when it comes to Filesystem API usage, it uses the API only in a few places when uploading and unpacking files, and that doesn't make much sense to me, I mean, where's to point in using it at all when there are a lot of other situations where the PHP filesystem functions are used for direct access? Uploading packages would work even when there are ownership "problems", however I'm pretty sure that these "problems" won't go away 5 minutes later when I'm utilizing any of the functions that are using for example fwrite directly. So why should I as a plugin/theme developer care about it anyways when half of the WordPress functions I'm using does not rely on the Filesystem API, my plugin/theme wouldn't work correctly anyways, wouldn't it?


title: How to parse a custom url (within WP site) and obtain params passed to that URL

text: In my WP site-- eg. http://www.mydomain.com-- a request has to be passed to a custom URL-- http://www.mydomain.com/custompage?param1=abc&param2=def Now, I wish to obtain the parameters passed to that URL from a function in functions.php of that theme. This function is executed when the above (example) URL is loaded... How do I do this? For above eg. I wish to obtain first parameter=abc and second parameter=def-- I already know that the parameters are named param1 and param2.


title: Save custom post type not working

text: I'm having a strange problem with same code not working on localhost vs production server. The code is simple and I am trying to save a custom post type, but none of the data in my metaboxes are saved. I have some `echo` statements in my `save_custom_type` for debugging to see how the data looks like. Not even those print statements are echoed when I press "Publish" on production environment. The custom post type is created in my theme, I hook into the action 'init'. Code for creation and first lines up to the first echo statement in the save method.               function create_omgang_post_type() {         $labels = array(                 'name' => 'Omgång',                 'add_new' => 'Lägg till ny omgång',                 'add_new_item' => 'Lägg till ny omgång',                 'not_found' => 'Inga omgångar inlagda'                 );         $args = array(                 'description' => 'En omgång för denna säsong',                 'public' => true,                 'hierarchical' => true,                 'show_in_menu' => false,                 'show_in_admin_bar' => true,                 'label'=>'Omgångar',                 'labels' => $labels,                 'supports' => array(                         'title', 'page-attributes')                  );         register_post_type('omgang', $args);      }     add_action('init', 'create_omgang_post_type');           /*-------------------------------------*/          function save_custom_post_omgang($post_id) {         $slug = 'omgang';         $post = get_post($post_id);               if($post->post_type == "omgang" ) {             if(! $_POST)                 return;                  if(!wp_post_revision_title($post_id)) {                  $lag = get_all_lag();                       $data = array();                 foreach($_POST as $key => $value) {                     //key#type                     $explodedID = explode('#', $key);                          if($explodedID[0] != $key) {                         $key = $explodedID[0];                         $type = $explodedID[1];                              $data[$key][$type] = $value;                     }                 }                 print_r($data); //this line is not even printed in PRD             }         }     }


title: Remove "posts" from admin but show a custom post

text: After checking out: http://codex.wordpress.org/Function_Reference/remove_menu_page,   I successfully use the following code to hide some stuff from the menu:               add_action( 'admin_menu', 'my_remove_menu_pages' );          function my_remove_menu_pages() {         remove_menu_page('link-manager.php');         remove_menu_page('tools.php');         remove_menu_page('users.php');         remove_menu_page('edit-comments.php');       }      However both the "posts page" and a custom post types page seems to run on `/wp-admin/edit.php`. So I'm looking for a way to _hide_ the posts menubar but still show the menu for a custom post type I've added.


title: woocommerce add variable after price

text: I am kind of new to woocommerce but finding this plugin amazing so far.. I am trying to figure out how to add a variable right after the price which will give the buyer additional information about how many credits he purchased (using stars) There is an option of adding attributes and showing them as variables but it all shows underneath in the "Additional information" tab and I want that to appear right after the price the following screenshot better describe what I am looking for: ![enter image description here](http://i.stack.imgur.com/nsb9Q.png) * **This "stars" additional information must be added to the checkout page as well as sent to the customer as additional important information** Thanks in advance   Gil


title: Get all children titles of a page as a link to them

text: I want to pull all the children titles of certain page and put them as a link. This is what i got so far:               $my_wp_query = new WP_Query();                         $all_wp_pages = $my_wp_query->query(array('post_type' => 'page'));                              // Get the page as an Object                         $oferta =  get_page_by_title('Oferta');                              // Filter through all pages and find Portfolio's children                         $all_children = get_page_children( $oferta->ID, $all_wp_pages );                              echo '<pre>' . print_r( $_children, true ) . '</pre>';      Now, how can I get page titles from $all_children ?


title: How to get new post URL?

text: I'm wondering... how can I get the new post URL in my theme? Is there a built- in function for this? So, it should return something like http://example.com/wp-admin/post- new.php?post_type=post. Connor.


title: Logging into multiple Non-Wordpress sites through one Wordpress login

text: I'm trying to connect my partner sites with my main site. Is it possible for me to be able to log into my partner sites (they aren't running on WordPress) AND my WordPress site simultaneously with one login on my WordPress site, and if so, how can this be done? I've searched for plugins but to no avail. I'd like to save my clients time, so they don't have to login to each site separately. The issue is that my partners aren't running on WordPress. I really have no idea where to even start, so I figured an open-ended question would be best. Thanks in advance for any suggestions or ideas.


title: wordpress str_replace the content with tag

text: it is possible to find tag in the content and replace with link?               function replace_content($content){       foreach(get_the_tags() as $tag) {         $out .= $tag->name .',';         $csv_tags .= '"slug . '">' . $tag->name . '"';       }       $find  = array($out);       $replace = array($csv_tags);       $content = str_replace($find, $replace, $content);       return $content;     }     add_filter('the_content', 'replace_content');


title: is_home() and is_front_page() not working in sidebar

text: I'm trying to display a custom widget in the sidebar of my homepage (which is a static front page defined in `Settings > Reading`). Here is the relevant part of my `sidebar.php`:               if ( is_front_page() || is_home() ) {         if ( is_active_sidebar( 'sidebar_lecture' ) ) : ?>             <div id="secondary" class="widget-area" role="complementary">                 <?php dynamic_sidebar( 'sidebar_lecture' ); ?>             </div>         <?php      endif;      The sidebar does not display because the conditional tag does not recognize my homepage as being a homepage. When I `print_r($wp_query)` in the sidebar, it reveals that `[is_page] => 1` and that the post's `[ID] => 32`, which is correct. However, `[is_home]` is null. For the record, I did use a custom query (`query_posts()`) in my `page.php` template, but I did reset it afterwards using `wp_reset_query()`. Any pointers?


title: Adding unit ammount after WooCommerce price. Example $ 24 /m2 and $24 / m

text: So hey guys, I'm trying to get my WooCommerce price per unit done. Some of the items I'm selling are floortiles, and as of such they're sold per square metre. I have added the following code to display /m2 behind every price               .amount:after{         content: "/m2";         text-size: 13px;     }      This adds the /m2 after each price. However, some of the items I am currently selling are not floortiles. For example decorating strips are sold per metre. And I'm selling column blocks, which are sold per piece. How can I add the price units correctly? Does the WooCommerce CSS recognize SKU? and if so, how to implement it?


title: Is it possible to change the log file location for WP_DEBUG_LOG?

text: I use WP_DEBUG_LOG in my development environment and have no issues with debug.log being in the wp-content directory. Sometimes I turn on WP_DEBUG in production when I need to debug something, and I still want to use the log but would like to redirect it to something outside my web root. Is this possible using WP_DEBUG_LOG?


title: Check if email address exists front end with AJAX in a plugin

text:
I am pulling my hair out trying to figure this out. I have followed the wordpress codex here for AJAX: http://codex.wordpress.org/AJAX_in_Plugins All I keep returning is 0, I never get a 1. Any idea why? My code is as follows. PHP:               add_action('wp_enqueue_scripts', 'live_validation' );     add_action('wp_ajax_validate_email', 'validate_email_input');     add_action('wp_ajax_nopriv_validate_email', 'validate_email_input');          function live_validation() {         wp_enqueue_script( "validate_email", STRIPE_BASE_URL . 'inc/js/check-email.js', array( 'jquery' ) );         wp_localize_script( "validate_email", "validateEmail", array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );     }          function validate_email_input() {         $email = $_POST['email'];         if ( email_exists($email) ) {             echo 1;          } else {             echo 0;         }         exit;     }      JS:               jQuery(document).ready(function($) {         $('input[name=email]').keyup(function() {                  var input_value = $(this).val();                  $.post( validateEmail.ajaxurl, { action:'validate_email', email:input_value }, function(data) {                 $('.message').html(data);             });         });     });      HTML:
         <?php _e('Email', 'oe'); ?>         <input type="text" size="20" id="email" name="email" />


title: Select Menu for Custom post Type does not save

text:
I posted a discussion on CSS-Tricks the other day. Explaining that my Videos were not displaying on my Video page from my custom post type that I created using this tutorial. I thought I fixed the issue but it turns out the issue wasn't resolved. Anyway, so I thought maybe the way I setup my CPT/Fields were messing things up. So I found another tutorial and redid the CPT and Fields, here is the new code. I was able to get my Video ID field to save, but when I select "Youtube" or "Vimeo", then save, it just goes back to it's default option "Select". So when I view my page the container where the video should be placed is blank. I am new to all of this Wordpress PHP so I have no idea if the select menu code is correct...or whatever the issue is. I'd appreciate any help to find the cause of this. **EDIT//** After editing this line:               $ret .= '
';      to this:               $ret .= '
';      The Selected Video Type can now be saved, but my issue with a blank container remains... I pasted the PHP section which should display the video in this pastebin.


title: adding new posts into wordpress DB automatically

text: I want to create a php script that reads the rss feed content from another website and then adds those read information into my WordPress website's database so that when you go to my WordPress website you will see those inserted posts via my php code. **The problem is:** I want to use built in codes of WordPress for adding new posts and I don’t want to go through writing my own code for inserting data into MySQL.   Is there a fast way?   I want to be able to add these information into WordPress by my php script:   1. Post content   2. Post title   3. Tags   4. Post categories   5. Date: for this I want to add the time and date when the new post is inserted into database.   6. Writer At the beginning of my php script that I am writing, I first connect to the wordpress's Database using username and password of that database. Is there a fast way for adding new content by php into wordpress's database? Is there any special function for doing this? And for using that function what should I do in my php script? What should I include in it?


title: How to include wp-postviews plugin directly in the theme

text: I don't want to ask the user to install this and that plugin, I want my theme to be 100% active active without the need to install a plugin like wp- postviews plugin, so how can i do that. I want to include it directly in functions.php file? Thanks in advance.


title: How to isolate code to the post edit screen

text: I've got some jQuery that interacts with items on the post and page editor screens. However, the script is also loading on other admin screens that are driven by post.php Is there a way to target the post/page editor screen exclusively? I'm currently using:               global $pagenow;     if( 'post.php' == $pagenow )     {       //jQuery blocks go here     }      However, since the jQuery has refences to objects that only appear on the post/page editor screens, I'm getting console errors on other pages that are driven by post.php For example, this code throws a console error of "Uncaught TypeError: Cannot read property 'length' of undefined":               var charactersMeta = jQuery("#excerpt").val().length;


title: A static page view call every custom page templates

text: I use wordpress 3.9.1 and I get this strange issue: I created a static page with slug `customer-order` and I created a template `page-customer-order.php` and Permalink: `http://localhost/thanassis/src/customer-order/` I also created a static page with slug `zipfile` and I created a template `page-zipfile.php` and Permalink: `http://localhost/thanassis/src/zipfile`. I also use child theme and these templates are in the child-theme folder. The problem is that when I view `customer-order` page the wordpress not run only the correct template but also run the `zipfile` page template. Is this correct Wordpress's sequence?


title: trying to do if post meta !=0

text: im trying to do a simple if function on my code but for some reason it just isnt working correctly, ive gone over it several times to see if there is anything im missing but no luck, im trying to say my value is 0 then echo nothing if not else the_ratings. very simple...               <?php if( get_post_meta( $post_id, 'ratings_users', true ) === '0' ) {     }else{     the_ratings();     } ?>     <?php if(!get_post_meta( $post_id, 'ratings_users', true ) !='0' ) {     }else{     the_ratings();     } ?>     <?php if(get_post_meta( $post_id, 'ratings_users', true ) =='0' ) {     }else{     the_ratings();     } ?>      edit: at this point ive tried 3 different ways to get this stupid thing to output nothing if the value in the custom field is 0 and still it doesnt work correctly


title: How to get to blog flow and a specific post?

text: How do I get to a specific blog post in the flow without getting inside the specific post? I mean from my homepage i can see a excerpt of the post. When i click on that post i come right to that specific post and cant scroll done if I want to read another post. I want to be able to click on that post and come right to my blog page that already showing the content and still be able to scroll down or up to read more. How do I do that? This is my site: http://d29190245.u193.surf-town.net/ and the post im talking about is the one with a picture saying no image and i want to come to "BLOGG" and not inside the post.


title: Include CSS with PHP without including wp-load?

text: I have a CSS-file generated from PHP. **In my file it says...**               header("Content-type: text/css");     define('WP_USE_THEMES', false);     include '../../../../wp-load.php';      I've read that including wp-load.php like this is not good. Why I do this is to get the environment in there. What is the "correct" way of doing this?


title: Wordpress or plugin need tomcat?

text: I have a managed VPS. It's a CentOS 6.4 + Apache 2.2 + Nginx admin 4.4. When I'm running **top** process in SSH, I can see there's a tomcat process (uses 1.9% RAM). This VPS has only wordpress sites. I want to know Wordpress or its plugin need the tomcat to run? How do I check if a plugin need tomcat?                PID   USER      PR  NI  VIRT  RES  SHR S %CPU %MEM    TIME+  COMMAND     24085 tomcat     20   0  657m  50m 8728 S  0.0  2.0   0:02.57 jsvc


title: Organize media uploads in folders - I have a physical access to (my) server

text: I'm very new to Wordpress. With the help of my friend I installed Wordpress on my server and finally we have our web online. However, I would like to upload some content in media library but I need to organize it in folders. Now we organized it with date-time hierarchy but its not enough. Is it possible having an access to the physical server where I have my site to create some directories and upload files to it using wordpress (I would like to create them inside the date-time directories)? Where do I need to create such folders, how can I check where my friend installed wordpress and find the directory I can create some subdirectories? Do I need a wordpress plugin or can it be done manually on server? We installed our wordpress on Ubuntu 12.04 Server.


title: Pagination stops at page 6

text: The loop below works fine, apart from the fact that the pagination will always stop on page 6. No matter what arguments i specify, it will never show more than 6 pages. Does anyone know why?               <?php          $paged = (get_query_var('paged')) ? get_query_var('paged') : 1;                     $idxargs = array(             'posts_per_page' => '1',             'paged' => $paged,         );              $idxloop = new WP_Query( $idxargs );                        ?>              <?php if ($idxloop->have_posts()) : while ( $idxloop->have_posts() ) : $idxloop->the_post(); ?>                               <?php the_title(); ?>                             <?php endwhile; ?>             <?php next_posts_link( __( 'Next') ); ?>        <?php previous_posts_link( __( 'Prev' ) ); ?>              <?php endif; ?>         <?php wp_reset_query(); ?>


title: register_taxonomy for both 'Post' & 'Page'

text: I'm using following code to register new taxonomy for WP-Post.               function qc22_build_taxonomies(){             register_taxonomy(__( "fullscreen-tags" ), array(__( "fullscreen" )), array("hierarchical" => true, "label" => __( "Fullscreen Tags" ), "singular_label" => __( "Skill Type" ), "rewrite" => array('slug' => 'fullscreen-tags', 'hierarchical' => true)));          }         function qc22_fullscreen_edit_columns($columns){                        $columns = array(                       "cb" => "<input type=\"checkbox\" />",                       "title" => __( 'fullscreen Item Title' ),                     "type" => __( 'type' )                 );                        return $columns;           }           function qc22_fullscreen_custom_columns($column){                   global $post;                   switch ($column)                   {                         case __( 'type' ):                           echo get_the_term_list($post->ID, __( 'fullscreen-tags' ), '', ', ','');                           break;                 }           }                add_action( 'init', 'qc22_build_taxonomies', 0 );         add_filter("manage_edit-fullscreen_columns", "qc22_fullscreen_edit_columns");           add_action("manage_posts_custom_column",  "qc22_fullscreen_custom_columns");       I want to appear this taxonomy on WP-Pages also. I'm new to wordpress. Any help will be appreciated. Thanks


title: Fatal error: Cannot redeclare when switching themes

text: I've built a theme from scratch which is named "core". Core has a child theme called "core_child". My child theme works perfectly and only contains the following:   1. /images   2. screenshot.png   3. style.css Today I needed to activate "core" to make some changes. I received the following error upon activation:               Fatal error: Cannot redeclare add_slug_body_class() in /Applications/MAMP/htdocs/fresh_install/wp-content/themes/core/functions.php on line 3      The error indicates that I have a functions conflict. This prompted me to open up my `functions.php` file. I renamed the function `add_slug_body_class` to `body_slug_core` and this re-produced the error:               Fatal error: Cannot redeclare body_slug_core() in /Applications/MAMP/htdocs/fresh_install/wp-content/themes/core/functions.php on line 3      Here's the function which is causing the problem:               // Page slug body class     function body_slug_core( $classes ) {     global $post;     if ( isset( $post ) ) {     $classes[] = $post->post_type . '-' . $post->post_name;     }     return $classes;     }     add_filter( 'body_class', 'body_slug_core' );      Next I deleted the function completely. This produced the following error:               Fatal error: Cannot redeclare remove_default_image_sizes() in /Applications/MAMP/htdocs/fresh_install/wp-content/themes/core/functions.php on line 23      This error is referring to the next function within `functions.php`. Here's the code:               // Remove WP default image sizes     function remove_default_image_sizes( $sizes) {         unset( $sizes['medium']);         unset( $sizes['large']);         return $sizes;     }     add_filter('intermediate_image_sizes_advanced', 'remove_default_image_sizes');      I repeated what I had tried for the first function (renaming and then deleting the function completely), but it simply flagged the next function as a conflict. I have read that this can be caused by WordPress websites that have been compromised. This is not the case as I've only been running the themes locally via MAMP. I've changed the names of the functions which rule out any conflict with the WordPress core files. I have tried a fresh install of WordPress with a clean database without any plugins running. To regain control of wp-admin, I have renamed the core theme folder to core_. This produces a further warning in wp-admin which may be unrelated:               Warning: implode(): Invalid arguments passed in /Applications/MAMP/htdocs/fresh_install/wp-includes/class-wp-theme.php on line 675      The warning disappears when I refresh the page. WordPress Version: 3.8.3