How to retrieve taxonomy terms of the current custom post?

I have a custom taxonomy _worktype_ and I have 3 types in this latter custom taxonomy: - creation - collaboration - lab I have also a custom post type "works". _worktype_ is used only for the custom posts type _works_ I have single-works.php as a template and everything is ok BUT, I need to retrieve the worktype of the current single post. How can I do that ? (the final idea: build a breadcrumb like that > ; in order to navigate a bit better)


how to register / add multiple options into one field in wordpress?

How can I register or add multiple options into one field. For example, we save a logo in get_options() by registering the setting and adding fields by add_settings_field() function and we output it accordingly. But what if we want to save multiple options into one field, like we have an option on our page called "Select your favourite colour" and there are check- boxes with different colours and user needs to select multiple colours (not a single colour) then how would we save that in WordPress options and how to output it too?


Is it possible to add a sidebar in a woocommerce hook?

I'm trying to add a sidebar to woocommerce woocommerce_before_shop_loop hook. I'm using the following code in the functions.php file:               add_action( 'woocommerce_before_shop_loop', 'my_custom_before_shop_loop_sidebar', 1);     function my_custom_before_shop_loop_sidebar() {           echo get_sidebar('my_custom_sidebar');     }      The problem that I got is that it displays the wordpress default sidebar instead of the sidebar with the my_custom_sidebar id. is there a way to accomplish this? thanks! Ah by the way, I'm registering the sidebar like this :               /**      * Register sidebars     */     function meir_widgets_init() {         register_sidebar( array(             'name' => 'My Custom Sidebar',             'id' => 'my_custom_sidebar',             'description' => 'Sidebar for top filters.',             'before_widget' => '
',             'after_widget' => '

',             'before_title' => '
',             'after_title' => '

',         ) );     }     add_action( 'widgets_init', 'meir_widgets_init' );


Buddypress Group Activity Loop Filter activity type

I'm using Buddypress 1.8.1 When the group home page load I want to show only 'activity_update' and 'joined_group' activities in Activity Loop. Here is my Activity Loop code. It is standard loop code.               <?php if ( bp_has_activities( bp_ajax_querystring( 'activity' ) ) ) : ?>         <?php while ( bp_activities() ) : bp_the_activity(); ?>                  <?php locate_template( array( 'activity/entry.php' ), true, false ); ?>              <?php endwhile; ?>     <?php endif; ?>      How to filter these activities in page load. Thanks.


Is this correct usage of filters in WordPress

I am building a plugin and I'm getting doubts whether the code I am using is the correct way of doing things with regards to WordPress hooks and filters. The scenario is that the code at a particular point needs to know whether to do one thing or another. Simple thing, I could use an option in the plugin's admin. But in order not to clutter the plugin's admin, and given that this option will likely be used by a very tiny percentage of users, I opted to not have a GUI option and instead have this true/false value set via code (the Genesis framework uses this methodology a lot). We start with the default value in variable:               $force_default_thumbnail = apply_filters( 'image_priority', FALSE );     // rest of logic goes here      So the variable starts out being FALSE, and a user of the plugin can modify that by using a filter in their theme's functions.php (or as a separate plugin) as follows:               add_filter( 'image_priority', 'my_force_default_thumbnail' );      That would in turn trigger the following function which is also included in the main plugin file.               function my_force_default_thumbnail( $force ) {         return TRUE;     }      When that function is triggered the default value changes to true and the logif of the plugin changes based on that modification. I hope I explained it well enough, and look forward to your advice.


Theme My Login Plugin Change Site Language to The Default Language

I have three websites with the same issue: I use qTranslate and theme my login plugins. If the user wants to register, login or retrieve a password and he provides wrong data (empty text field, wrong username or wrong email), the language changes to the default one. All the error messages are shown newly changed default language. example: if user wants to register in x language and the url was:               example.com/x/register/      and enters wrong email/username and then hits _register_ , the language changes to the default. Error message and everything else is shown in the default language and the url becomes:               example.com/register/


Show recent ads from certain categories

I ask you to help experts, the problem is: I'm using a template classified, are shown on the home for the latest upload, but I would like to show ads in different categories. Let me explain, I would like to display the latest in a given category. This is the code in index.php regarding the latest:               <?php      $latest=get_option('colabs_latest_submit');     if(''==$latest)$latest=10;     $the_query = new WP_Query('post_type=ad&showposts='.$latest);     if($the_query->have_posts()):     ?>

<?php _e('Latest Submit','colabsthemes');?>

         <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
                 <?php colabs_image('width=42&height=42');?>                 <a class="latest-title" href="<?php the_permalink();?>"><?php the_title();?>
         <?php endwhile; ?>

     <?php endif;?>      Many thanks to all!


Adding Controls to Theme Customizer If Certain Page Template is Active

How to Conditionally add controls on Theme Customizer panel. Conditional like `is_page()` or `is_page_template()` obviously does/will not work because the page is being shown is `customize.php`. ## Code Example               add_action( 'customize_register', 'my_theme_customize_register', 11 );          function my_theme_customize_register($wp_customize){         if( is_page_template('my-template.php'){             // add special control         }     }      **Another observation** is, customization setting control panel does not refresh when we switch to pages. It uses ajax to load theme preview. So, I guess theme customizer did not intend to use for post/page specific settings. So, am I hitting a dead end?


Plugin custom post type - Internal server Error

I need to create a plugin in wordpress 3.9 for custom post types.When i activate the plugin, am getting an internal server error 500. Also plugins are not listing in admin dashboard. Here is my code:               <?php       /**     * Plugin Name: Name Of The Plugin     * Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates     * Description: A brief description of the Plugin.     * Version: The Plugin's Version Number, e.g.: 1.0     * Author: Name Of The Plugin Author     * Author URI: http://URI_Of_The_Plugin_Author     * License: A "Slug" license name e.g. GPL2     */          add_action('init', 'register_wp_questions');          $labels = array(     'name' => __( 'Questions', 'wp_question' ),     'singular_name' => __( 'Question', 'wp_question' ),     'add_new' => __( 'Add New', 'wp_question' ),     'add_new_item' => __( 'Add New Question', 'wp_question' ),     'edit_item' => __( 'Edit Questions', 'wp_question' ),     'new_item' => __( 'New Question', 'wp_question' ),     'view_item' => __( 'View Question', 'wp_question' ),     'search_items' => __( 'Search Questions', 'wp_question' ),     'not_found' => __( 'No Questions found', 'wp_question' ),     'not_found_in_trash' => __( 'No Questions found in Trash','wp_question' ),     'parent_item_colon' => __( 'Parent Question:', 'wp_question'),     'menu_name' => __( 'Questions', 'wp_question' )     );               $args = array(     'labels' => $labels,     'hierarchical' => true,     'description'  => __( 'Questions and Answers', 'wp_question' ),     'supports'     => array( 'title', 'editor', 'comments' ),     'public'       => true,     'show_ui'       => true,     'show_in_menu'       => true,     'show_in_nav_menus'       => true,     'publicly_queryable'       => true,     'exclude_from_search'       => true,     'has_archive'       => true,     'query_var'       => true,     'can_export'       => true,     'rewrite'       => true,     'capability_type'       => true     );          register_post_type ('wp_question', $args);          ?>      Please help. How can i figure out the error? Thanks


Add third level menu on wordpress

I would like to add a third level menu on WordPress. This is the code I've added to the functions.php file to create the secondary menu, but when trying to repeat the same code with a third menu, I get an error.               add_action( 'init', 'my_custom_menus' );       function my_custom_menus() {          register_nav_menus(             array(       'primary-menu' => __( 'Primary Menu' ),       'secondary-menu' => __( 'Secondary Menu' )


How to set global variables in template page?

I know this works.   In `functions.php` do:               $variable = "value";      and in `header.php` use:               global $variable;     echo $variable;      Is it possible to set a global variable in template page or include php file?


Make first child link default instead of its parent

I want to do something like this: if a parent have kids get page link of the first child else get page link of itself. For example: Page 1   * Sub-page 1 ( **get this link** )   * Sub-page 2   * Sub-page 3 Page 2 ( **get this link** ) Page 3   * Sub-page 1 ( **get this link** )   * Sub-page 2 Page 4 ( **get this link** )


APC fragmention woes on Apache AWS EC2 Small instance with WordPress and W3TC

> Asked this question at serverfault, and got confirmation that W3TC is most > likely causing the issue, but several of my more W3TC/Wordpress specific > issues weren't able to be answered. Reposting here as this community had > hopefully answer those better. I emboldened them below.* AWS EC2 Small instance, Apache 2 running WordPress and W3TC. Within an hour, my APC fragmentation hits 100%. My APC settings are:               apc.enabled = 1     apc.shm_segments = 1     apc.shm_size = 100M     apc.optimization = 0     apc.num_files_hint = 512     apc.user_entries_hint = 1024     apc.ttl = 7200     apc.user_ttl = 7200     apc.gc_ttl = 3600     apc.cache_by_default = 1     apc.use_request_time = 1     apc.filters = "apc\.php$"     apc.mmap_file_mask = "/tmp/apc.XXXXXX"     apc.slam_defense = 0     apc.file_update_protection = 2     apc.enable_cli = 0     apc.max_file_size = 2M     apc.stat = 1     apc.write_lock = 1     apc.report_autofilter = 0     apc.include_once_override = 0     apc.rfc1867 = 0     apc.rfc1867_prefix = "upload_"     apc.rfc1867_name = "APC_UPLOAD_PROGRESS"     apc.rfc1867_freq = 0     apc.localcache = 0     apc.localcache.size = 256M     apc.coredump_unmap = 0     apc.stat_ctime = 0     apc.canonicalize = 1     apc.lazy_functions = 0     apc.lazy_classes = 0     /etc/php.d/apc.ini      More poop can be seen here. Mostly cribed settings from here. The shm was meant to be whittled down from such a high value after some observation, but apparently such a large value isn't even high enough.... I found an similar question/answer here. I do have some virtual hosts setup, but they aren't being touched much at all. Having users logged into the admin panel of WP does make things worse, but that's certainly not the main culprit. The question asker seems to suggest that it turns out W3TC is probably causing the problem, which the plugin author seems to agree with, but there aren't any helpful details beyond that. **Why is it causing the problem? Could this be fixed?** **Do I just turn for now and turn off object caching with APC? Is there nothing I can do? Does APC turned on without being used for object caching actually help anything? Would memcache be an ok substitute just for object caching here? Finally, maybe I just shouldn't worry so much about the fragmentation?**


Jquery NoConflict Problem

i'm creating a wordpress theme and i am utilizing some scripts that use jQuery. It was working fine, until i enabled a particular plugin, named 'Paid Downloads'. This actually made all of jquery dependencies not working anymore. So, i am thinking, that maybe i am doing something wrong. For instance, i am using prettyPhoto and initializing it like :               /* Pretty Photo */         wp_register_style('pretty-photo-css', LIBRARIES_URI . "prettyPhoto/css/prettyPhoto.css");         wp_enqueue_style('pretty-photo-css');          wp_register_script('jquery-pretty-photo', LIBRARIES_URI . "prettyPhoto/js/jquery.prettyPhoto.js");         wp_enqueue_script('jquery-pretty-photo', array('jquery-my'));      jquery.prettyPhoto.js is the actual prettyPhoto file and i have just added these few lines in the end of that file, in order to trigger the prettyPhoto effect :               jQuery.noConflict()          jQuery(function(){       jQuery("a[rel^='prettyPhoto']").prettyPhoto();     });      JQuery is enqueued like :                   wp_register_script('jquery-my', "http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js");         wp_enqueue_script('jquery-my');      As i mentioned, this used to work before enabling the 'Paid Downloads' plugin. I am wondering. Am i doing something wrong ? When the plugin is enabled, i get errors like that in Chrome javascript console :               Uncaught TypeError: Object [object Object] has no method 'prettyPhoto'      It seems that there is a conflict because the plugin adds jquery for its own purpose ? Any ideas ?


How can a shortcode can take the place of the featured image in a post?

When there is a specific shortcode in a post (example `[sc]anything[/sc]`), I want to hide the featured and take it's place. How can I do that? I add this on my theme function               // TopWide Shortcode     function wpsite_topwide( $atts, $content = null ){         return '
' . do_shortcode($content) . '
';     }     add_shortcode( 'topwide', 'wpsite_topwide' );          /**       * Find if content has topwide shortcode in it.       */      function wpsite_has_topwide_shortcode() {          global $post;               if ( ! is_single() )              return;               if ( false === strpos( $post->post_content, '[topwide' ) )              return false;               return true;      }      and this on single post               <?php     if (wpsite_has_topwide_shortcode() && has_post_thumbnail() ) {          echo '
' . get_the_post_thumbnail( $post->ID, 'full' ) . '
';      }      ?>      But doesn't takes the place of the featured image in the post...


RSS feeds and wordpress?

I'm working on my first wordpresss website and I've really never worked with RSS feeds. However my friend that I'm doing a website for wants it in there. so I guess I'm in a crash course learning session with google to learn all I can about RSS feeds. I was hoping to find a plugin that just allowed the visitor to subscribe to the websites blog but they are all pretty ugly, or not what I want. ![enter image description here](http://i.stack.imgur.com/M4Jyw.png) I'm hoping to have an email field that I can style like the way I have designed it here. Or even something like the way this website has it done Are there any good plugins and articles to read up for a beginner wordpress theme developer to learn this RSS feed information?


How to find the WordPress Nextgen galleries which are not used in WordPress posts?

I am using **WordPress** with **Nextgen Gallery** by Alex Rabe for quite sometime. Once upon a time I had a good amount galleries in my website which were used in many posts through nextgen gallery shortcode. But for quality enhancement I have deleted many posts but the galleries related to those posts remain there in file system as orphan. How to find the galleries not used in post database? ## **Table added by nextgen gallery:** ### wp_ngg_gallery               Column          Type            Null    Default     Comments     gid             bigint(20)      No            name            varchar(255)    No            slug            varchar(255)    No            path            mediumtext      Yes     NULL          title           mediumtext      Yes     NULL          galdesc         mediumtext      Yes     NULL          pageid          bigint(20)      Yes     0         previewpic      bigint(20)      Yes     0         author          bigint(20)      * * * ### wp_posts (Wordpress default table)               Column          Type        Null    Default         Comments     ID              bigint(20)  No                post_author     bigint(20)  No      0         post_date       datetime    No      0000-00-00 00:00:00           post_date_gmt   datetime    No      0000-00-00 00:00:00           post_content    longtext    No         gid is the gallery id. for an example if the gid is 8 i use the nextgen gallery shortcode **[nggallery id=8]** in the post and it is saved in the post_content field of wp_posts table. i want to know the gid's which are not present in any post_content of whole wp_posts table.


How to add a " waiting" icon for an ajax in WP frontend?

This is my search js code for processing search :               jQuery(document).ready(function($){              $('#searchsubmit').click(function(e){              e.preventDefault();                  var searchval = $('#s').val(); // get search term                  $.post(                 WPaAjax.ajaxurl,                 {                     action : 'wpa56343_more',                     searchval : searchval                 },                 function( response ) {                     $('#results').empty();                     $('#results').append( response );                 }             );         });          });      My question is how to add an icon of waiting (the one that is used in WP admin) near the search button (#searchsubmit) so the user knows after the click that it's working? The best would be if I use only javasccript inside my existing js code I have posted here.


current-menu-item class for custom post type parent

Im having a problem with my menu and custom post type. I have a custom post type of "services". I have created new page for it called Services. On that page Im displaying a list of all the post from that custom post type. The current-menu-item class is working as itended. But the problem is when I click on one of the services and go to mysite.com/services/service-1, the current-menu-item from services page in menu dissapears. I need to show that this current post is a child of Services page. All of the menu items have the same HTML:
Služby
      There is no CSS class that I could use to style this link as parent. Something like current-menu-parent or something. How could I fix this? Thanks.


Replace TimThumb in existing WordPress Themes

I'm sure most are aware of the most recent Timthumb issues. I know they have put a band-aid on the problem, but I really don't care for the script for several reasons. Before I started building my themes I purchased several from various markets. I'm trying to figure out the best method for removing Timthumb and replacing it with something else. I've successfully replaced it for one theme using the_post_thumbnail, but it was quite a bit of work. I'm just curious if someone knows of a better method. As it stands now, I have to weigh the time it will take using my method vs. how much do I actually like the theme. Can you provide any suggestions or links to proven articles?


How to create a non-responsive WordPress Theme Using Genesis Framework?

I am new to coding and I really don't know how to create a non-responsive child theme which runs on the Genesis framework. Besides that, I tried to modify a child theme and it all went well but one day when i tried to re-size the browser window i noticed that the theme was all messed up and looked ugly. I really want to know whether it is possible to remove the responsiveness from a Genesis child theme or not.


POST from jQuery to PHP

I have a form that passes field values to jQuery, which validates the fields and creates the variables being sent in `data: {}` in the snippet below.               $.ajax({         type: "POST",         url: "<?php bloginfo('stylesheet_directory'); ?>/process.php",         dataType: "json",         data: {             "title":title,             "goals":goals,             "progress":progress,             "categories":categories,             "tags":tags,             "video":video,             "audio":audio,         },         success: function() {             //get permalink for post from php and go to it         }     });      process.php is not receiving any data, or it's not posting the data. I'm not sure why. Here is process.php               <?php              $user_submitted_title = sanitize_text_field($_POST['user_submitted_title']);         $user_submitted_progress = $_POST['user_submitted_progress'];         $user_submitted_goals = $_POST['user_submitted_goals'];         $user_submitted_categories = $_POST['user_submitted_categories'];         $user_submitted_tags = sanitize_text_field($_POST['user_submitted_tags']);         $user_submitted_video = sanitize_text_field($_POST['user_submitted_video']);         $user_submitted_audio = sanitize_text_field($_POST['user_submitted_audio']);              $user_post = array(             'comment_status' => 'open',             'post_author'    => $user_ID,             'post_category'  => array($user_submitted_categories),             'post_content'   => '
Project Progress
' . $user_submitted_progress . '
Project Goals
' . $user_submitted_goals,             'post_status'    => 'publish',             'post_title'     => $user_submitted_title,             'post_type'      => 'post',             'tags_input'     => $user_submitted_tags         );              $user_post_id = wp_insert_post($user_post);         add_post_meta($user_post_id, 'wpcf-video', $user_submitted_video);         add_post_meta($user_post_id, 'wpcf-audio', $user_submitted_audio);              $user_post_redirect = get_permalink($user_post_id);          ?>      I need to figure out why nothing posts when I use the form, and I need to figure out how to send $user_post_redirect back to jquery so I can redirect to it. Can someone please help?


Move terms from one taxonomy to another keeping the hierarchy

I am creating a **custom taxonomy** for the first time. I am trying to add a `Location` taxonomy. What I am actually trying to do is use existing _categories_ to make them into _locations_. I went into the database table `wp_term_taxonomy` and manually changed the `taxonomy` column of the ones I wanted from `category` to `location`.   This seemed to work pretty well, posts are assigned to the desired locations and everything seems to be fine, until I go to the _Locations_ page in the admin interface and find myself with an empty list, even though it detects the existing locations and lists them: ![screenshot](http://zaharamh.com/locationwtf.gif) If I manually add a new _Location_ through the interface it appears on the list correctly. What could be causing this?


wp_signon() does not authenticate user guidance needed

I use form to send POST request to a page and to login user with `wp_signon()` in order to authenticate user to my wordpress installation as described in WP documentation:               $creds = array();     $creds['user_login'] = $_POST["user-login"];     $creds['user_password'] = $_POST["user-password"];     $creds['remember'] = true;          $user = wp_signon( $creds, false );      After this little piece of code I'm checking if user was logged in:               if ( is_user_logged_in() ) { echo "SUCCESS"; } else { echo "FAIL!"; }      But I got `FAIL!` all the time. Then after sniffing around I found this little trick:               wp_set_current_user( $user );     if ( is_user_logged_in() ) { echo "SUCCESS"; } else { echo "FAIL!"; }      I've got `SUCCESS` on this one but when I leave this page I got `FAIL` again and again. Can anyone explain me how to login user with `wp_signon()` without logging her out after page is changed or reloaded or whatever. * * * I've got desirable result when I go to `/wp_admin` and login with WP's default login form. I can navigate through every page of my WP site remaining logged- in all the time. But when I try to do this outside the default form I `FAIL`. Guide me! PLEASE!


Why does One Click Update fail on localhost using FTP with 777 permissions on site files?

I can successfully upload/remove media, add/remove plugins and edit theme files within admin CP. The one thing I can not do in admin CP is a normal one click update from WordPress 3.7.1 to 3.8. Ideas? The error message when I try to run updates: > Downloading update from https://wordpress.org/wordpress-3.8-new-bundled.zip… > > Unpacking the update… > > The update cannot be installed because we will be unable to copy some files. > This is usually due to inconsistent file permissions.: wp- > admin/includes/update-core.php > > Installation Failed For testing purposes, I have all directories and files from the parent down set with 777 permissions and user:group ownership set to my web server user www-data. > -rwxrwxrwx 1 www-data www-data every-freakin-file.php Output of `grep www-data /etc/group` show my vsftpd user and my main login. > www-data:x:33:ftps,ryan The site files are located in a sites-enabled user directory outside of /var/www This is installed on a LAMP private localhost with ports.conf configured as follows. > NameVirtualHost *:80 Listen 127.0.0.1:80 > > # If you add NameVirtualHost *:443 here, you will also have to change   >  # the VirtualHost statement in /etc/apache2/sites-available/default-ssl   >  # to   >  # Server Name Indication for SSL named virtual hosts is currently not   >  # supported by MSIE on Windows XP.   >  Listen 443 > >   >  Listen 443 Final thoughts: Is there another user that must be added to the www-data group? Does having 777 permissions on every file and directory rule out permissions as the reason for update failure? I see one solved thread with a selected answer about a "vsftp" config file, but it's too vague to be useful. My /etc/vsftpd.conf configuration is working great except of when I try one click updates.   WP upgrade can't create directory even though perms are 777 **Update:** My phpinfo.php shows APACHE_RUN_USER and APACHE_RUN_GROUP is www- data. I have confirmed that this user:group owns all files with read/write/execute permissions.


Allowed memory size exhausted. WordPress side solution

I'm getting a well known error from the question title. The problem is, website is running on a shared server and I don't have access to php.ini file. I've set `php_value memory_limit' inside .htaccess to higher value. I've set `WP_MEMORY_LIMIT` inside wp_config.php to higher value. `phpinfo()` says that `max_execution_time` is set to 30 and `safe_mode` is off. My question is, can I change something inside my WordPress installation to make my website work? I've read about `set_time_limit`. Can it help me somehow, or the only solution is to move onto another server?


Show some content if the user has done something

I am looking for an easy way to set conditions that the user has to meet before some content will be available for him. I want to make something like a tunnel of pages, for instance, where the user will be able go to a certain page only from specific URL. Or some page will be available for him only if he visited URL X. Is there something simple to accomplish this or will I have to start messing with code?


How to use wp_remote_get in place of file_get_contents?

I am trying to implement this plugin( http://wp.tutsplus.com/tutorials/creative-coding/creating-a-simple- backuprestore-settings-feature/ ) with my theme. Everything's working great. but the problem is in a wordpress environment I cannot use `file_get_contents`. I have to use `wp_remote_get` or `wp_remote_post`. I tried various methods to implement those. But its not working. Can you anyone help me replace the file_get_contents with wordpress equivalent? Thanks. Here is the full code:               <?php      /*     Plugin Name: I/E Option     Plugin URI: http://wp.tutsplus.com/     Description: This is a sample plugin with backup and restore options feature.     Author: Lee Pham     Version: 1.0     Author URI: https://twitter.com/leephamj     */     ob_start();     function register_ie_option() {         add_menu_page('IE Option Page', 'IE Option', 'activate_plugins', 'ie-option', 'ie_option_page', '');             add_submenu_page('ie-option', 'Import', 'Import', 'activate_plugins', 'ie-import-option', 'ie_import_option_page');         add_submenu_page('ie-option', 'Export', 'Export', 'activate_plugins', 'ie-export-option', 'ie_export_option_page');      }          /*        *  Main page      */     function ie_option_page() {     ?>

Backup & Restore

This is only a sample plugin that demonstrate how to create a simple import/export feature for your own templates or plugins.

Hope it useful for you!

Get in touch with me:

E-mail: leephamj@gmail.com

Twitter: @leephamj

Facebook: Lee Pham

     <?php        }          /*        *  Import feature      */     function ie_import_option_page() {     ?>

Import
             <?php                 if (isset($_FILES['import']) && check_admin_referer('ie-import')) {                     if ($_FILES['import']['error'] > 0)                          wp_die("Error happens");                             else {                         $file_name = $_FILES['import']['name'];                         $file_ext = strtolower(end(explode(".", $file_name)));                         $file_size = $_FILES['import']['size'];                         if (($file_ext == "json") && ($file_size < 500000)) {                             $encode_options = file_get_contents($_FILES['import']['tmp_name']);                             $options = json_decode($encode_options, true);                             foreach ($options as $key => $value) {                                 update_option($key, $value);                                 }                             echo "

All options are restored successfully.

";                         }                            else                              echo "

Invalid file or file size too big.

";                     }                 }             ?>
Click Browse button and choose a json file that you backup before.

Press Restore button, Wordpress do the rest for you.
             <form method='post' enctype='multipart/form-data'>
                     <?php wp_nonce_field('ie-import'); ?>                     <input type='file' name='import' />                     <input type='submit' name='submit' value='Restore'/>
             </form>
     <?php     }          /*        *  Export feature      */     function ie_export_option_page() {         if (!isset($_POST['export'])) {      ?>

Export

When you click <tt>Backup all options</tt> button, system will generate a JSON file for you to save on your computer.

This backup file contains all configution and setting options on our website. Note that it do NOT contain posts, pages, or any relevant data, just your all options.

After exporting, you can either use the backup file to restore your settings on this site again or another Wordpress site.
                 <form method='post'>
                     <?php wp_nonce_field('ie-export'); ?>                     <input type='submit' name='export' value='Backup all options'/>
                 </form>
     <?php          } elseif (check_admin_referer('ie-export')) {                  $blogname = str_replace(" ", "", get_option('blogname'));             $date = date("m-d-Y");             $json_name = $blogname."-".$date; // Namming the filename will be generated.                  $options = get_alloptions(); // Get all options data, return array                  foreach ($options as $key => $value) {                 $value = maybe_unserialize($value);                 $need_options[$key] = $value;             }                  $json_file = json_encode($need_options); // Encode data into json data                  ob_clean();             echo $json_file;             header("Content-Type: text/json; charset=" . get_option( 'blog_charset'));             header("Content-Disposition: attachment; filename=$json_name.json");             exit();         }     }     add_action('admin_menu', 'register_ie_option');


Retrieving JSON data in ajax request from media uploader

I'm having some problems getting my JSON data that's being passed via an ajax request. I'm trying to implement the media uploader into a plugins settings page. I've got it functioning properly using **this method** as far as the media uploader functionality is concerned. I'd like to be able to retrieve the 'attachment' data in PHP, decode it and then process it once the media uploader is closed and the images have been selected. The ajax request is working because I can echo back a response and it receives it, but when I try and decode the JSON string and perform a vardump it returns null, and if I try and access an array key it is empty. Here is the js code...               jQuery(document).ready(function($){            var file_frame;            jQuery('.upload_image_button').live('click', function( event ){              event.preventDefault();              if ( file_frame ) {           file_frame.open();           return;         }              file_frame = wp.media.frames.file_frame = wp.media({           title: jQuery( this ).data( 'uploader_title' ),           button: {             text: jQuery( this ).data( 'uploader_button_text' ),           },           multiple: true          });              file_frame.on( 'select', function() {                var selection = file_frame.state().get('selection');           selection.map( function( attachment ) {             attachment = attachment.toJSON();             $.post(ajax_object.ajaxurl, {                action: 'ajax_action',                data: attachment             }, function(data) {                console.log(data);               });           });         });               file_frame.open();       });          });      And here is the php function that is located in the main plugin file that receives the ajax request...               function ajax_action_stuff() {         $image_data = $_POST['data'];         $data = json_decode( $image_data, true );         var_dump( $data );         // echo $data[url];         die();      }     add_action( 'wp_ajax_ajax_action', 'ajax_action_stuff' );      And the enqueued scripts that are located in the main plugin file...               function gzmu_load_scripts() {         wp_enqueue_media();         wp_enqueue_script( 'gzmu-media-upload', plugin_dir_url(__FILE__) . 'gzmu-media-upload.js' );         wp_localize_script( 'gzmu-media-upload', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );         wp_enqueue_style( 'admin-styles', plugin_dir_url(__FILE__) . '/css/admin.css' );     }     add_action( 'admin_enqueue_scripts', 'gzmu_load_scripts' );      I've never worked with JSON before so I'm a bit confused on how to handle the data. Any advice on what I could be doing wrong would be greatly appreciated. Thanks...


How to set up wp multisite?

After installing falling all the steps (http://codex.wordpress.org/Create_A_Network) I tried to create sites. I can't access the dashboard of any site created. It says page not found (error 404). To start fresh I uninstalled WP and then Installed following every step. I have no clue what to do. I can only access the dashboard of the root site. All the rest I can't.


where does this $post_id come from?

I was trying to figure out why `save_post` wasn't being fired upon 'Quick edit', and found the solution here - apparently global `$post` is not available when updating a post in Quick edit mode. So - I got it working now - see working example below, but I don't understand _why_ it's working.               function mytestfunc($post_id)      {         $key = 'test';         $data = 'this is a test';         update_post_meta( $post_id, $key, $data );     }     add_action( 'save_post', 'mytestfunc' );      Can someone explain to me where this `$post_id` is coming from? I'm not passing the value in `add_action` - so I don't understand why `mytestfunc` knows which post I'm targeting?


Bookmarking a post in exchange for an email?

I was asked to implement a feature that this website https://medium.com/ has, which is the ability to bookmark a specific post by making the user register an account with the website. This is the ideal scenario: a user would be able to bookmark once they submit their email and it automatically gets added to a database (in this particular case, it would be MailChimp). Maybe if I start a database of emails (this should be safe generally speaking, I heard about making sure there's an SSL thing..) and then somehow I could pass those emails to MailChimp?.. I have installed a plugin called "WP Favorite Posts" and they offer the ability to make a post "favorite" if they have a WP account, or it can just be so that it's save in the user's browser's cookies.. But that doesn't quite cut it with the idea above. I don't really know how easy/hard would be to pull something like this off. Any suggestions?


including php file from payment gateway

I'm implementing a payment gateway called point, is a Swedish company. Everything is fine with this files, because I already tested outside of wordpress.<> But now that I'm implementing this on wordpress I got a few issues The structure of my folders: ![enter image description here](http://i.stack.imgur.com/8EYWS.png) This is the best way to include this files? And now, In one template I'm including `'./point/createForm.php';` No problems including this file. But this file include `'signatureutil.php'`. This file tries to create a object from Crypt/RSA.php   This is the problem, the code breaks on `$rsa = new Crypt_RSA();` Here parts of my code. createForm.php:               $fields["s-t-256-256_signature-one"] = generatesignature($datatosign);     renderorder($fields);      signatureutil.php:               /** Creates signature for data      * @param $data data to creta      * @return string      */     function generatesignature($data) {         include('Crypt/RSA.php');         include 'configvars.php';              $rsa = new Crypt_RSA(); //IT BREAKS HERE         $rsa->setSignatureMode(CRYPT_RSA_SIGNATURE_PKCS1);         $rsa->loadKey(file_get_contents($shop_private_key_file, true));         $signature = $rsa->sign($data);              return strtoupper(bin2hex($signature));     }      I don't think is because of my code, because I tested exactly the same, that is inside point folder, in a empty project and no erros.


Is there a way to randomize and connect a background and header image?

Right now I am using a different CMS, and I wrote a little bit of PHP which helps me (by using content from hidden pages) bring in a connected background and header and randomly display them, UNLESS the URL is one for a tag page. Here's the code I use for my other CMS right now:               <?php $randarts = $this->find('/random-header-background/')->children(array());     $randart = array_rand($randarts, 1);      $rand = $randarts[$randart]; ?>      This is combined with two other PHP calls to bring in the background and the header (which are inside of specific pages under the "Random Header Background" page set...               <?php if (url_match('/glorkian') OR url_match('/dino-run') OR url_match('/potato')){echo $this->content('background');}         else {echo $rand->content('background');}     ?>      and                <?php if (url_match('/glorkian') OR url_match('/dino-run') OR url_match('/potato')){echo $this->content('header');}       else {echo $rand->content();} ?>      Is there a way to do this in Wordpress? Or to randomly use backgrounds XYZ and if the background = X then use X header image, unless page (tag or category) = Y in which case you would always use background & header Y? Does this make sense? Check out http://pixeljam.com for an example (only the main page doesn't cache for this effect, the rest are cached but random except for the "Dino Run", "Glork" and "Potatoman" pages display their associated header & background. Edit: OK, after some working on this I feel like I've come up with a solution, but it doesn't seem to work for some reason, maybe I can get some recommendations on this solution:               <?php $bg = array('dinorun.css','potatoman.css','glorkian.css','somethingelse.css','anothersomething.css');         $randombg = mt_rand(0,3);     if (in_category('dino run')) { ?>                 <link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/dinorun.css">     <?php } elseif (in_category('potatoman')) { ?>                 <link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/potatoman.scss">     <?php } elseif (in_category(array('glorkian','glork'))) { ?>                 <link rel="stylesheet" href="<?php bloginfo('stylesheet_directory'); ?>/glorkian.css">     <?php } else { ?>                 <link rel="stylesheet" href="<?php bloginfo('stylesheet_directory') . $bg[$randombg]; ?>"     <?php } ?>`      This way I could just skip my in_category statements for the header and just change the css for the header background and the page background and header would always be matched.


Separation of view and logic

I find that very easily my views become cluttered with logic, e.g. null checks, email validation, and retrieving values from the post object. How would you separate this out in Wordpress? Is there any sort of MVC framework you have experience with? EDIT: It seems like everything in Wordpress is global. I don't have to much experience with PHP.


Common functionality between my own plugins

I read that when creating new post types, creating a settings page, and creating a new taxonomy, you should create a plugin. So I have done that. But I have functionality, which could be generalized, or are identical, in my plugins. An example of this would be the function which saves to the database. Since everything seems to be put in the global scope, if there is such a thing in PHP, should I create another plugin with shared functionality, or put shared functionality in the `functions.php` file?


'Dehighlighting' navigation once clicked

I'm using the Twenty Fourteen theme and I'm loading the pages using Ajax. What I want to happen - the menu bar to unfocus the previous page on the navigation bar and highlight the current page. What is actually happening - Nothing, it just stays the same. My code:               // highlight the current menu item     jQuery('ul.menu li').each(function() {         jQuery(this).removeClass('current-menu-item');     });     jQuery(thiss).parents('li').addClass('current-menu-item');      I have also tried this               jQuery('ul.menu li').each(function() {     jQuery(this).removeClass('current-menu-item');     jQuery(this).removeClass('current_page_item');     });     jQuery(this).parents('li').addClass('current_page_item');     jQuery(this).parents('li').addClass('current-menu-item');      The Navigation bar should be setup as it would be in a stock WP install as I'm using the default theme               <nav id="primary-navigation" class="site-navigation primary-navigation" role="navigation">      The CSS file contains this               .site-navigation li .current_page_item > a,     .site-navigation li .current_page_ancestor > a,     .site-navigation li .current-menu-item > a,     .site-navigation li .current-menu-ancestor > a       So the JS does appear to be using the correct call. Is there an alternative way I can try to make this work? I have another JS script which toggles the navigation bar when the button is viewable (mobile) which is executing correctly. EDIT: After suggestions in this question I've also tried this code               jQuery('ul.menu li').each(function() {     jQuery(this).removeClass('current-menu-item');         jQuery(this).removeClass('current_page_item');         jQuery(this).removeClass('current_page_ancestor')         jQuery(this).removeClass('current_menu_ancestor')          });     jQuery(this).parents('li').addClass('current_page_item');     jQuery(this).parents('li').addClass('current-menu-item');


Include post on external custom site

How do I include single post ( I mean image, title, and a bit of text ) on my own custom site? I have wp in subdirectory and I just want to make "Recent article" box on my site. I was looking for it 2 hours by now and nothing. I have something like this by now, but it only shows icon of post. ( I share a lot of videos on WP so video miniature won't show) and of course it looks bad. ( I want look of my theme)               // The Loop     the_post();     echo '
';     the_post_thumbnail( array(180, 120) );      echo '

';     the_title();     echo '
';     echo '';


Why does WordPress still not support SFTP?

It has been many years now with WordPress 2, WordPress 3 and now even WordPress 4 which is expected to be released shortly that WordPress Publishing Platform does not support SFTP as the option to upload themes, download upgrades and configure plugins? Many other platforms such as MovableType and ExpressionEngine and Umbraco are also enterprise driven as WordPress has proven itself to be an enterprise product but why does it still not support SFTP? Regards


Page that links to category content

I have a page called: fruit...then I have three child pages called cherry, lemon, and peach. I also have a category called fruit, and three child categories called cherry, lemon, and peach. What I am trying to do is when a user clicks on one of the child pages IE: "Cherry" the user gets a category page with all posts associated to the "Cherry" category. Normally this wouldn't be a big deal, I'd manually do an `<?php if (is_page("cherry")) { ?>` in my template, but what I'm looking for is a way to do it dynamically so that if someone creates a new child page and a matching child category then everything will be good to go without having to manually adjust the template. I guess it would be taking the page and redirecting to it's corresponding category page, but is that possible? Thanks,   Josh


jQuery not working when used with wordpress menu

I'm using a starter theme that was provided to me by a friend, and have successfully implemented jQuery several times on the website. I want a background image inside a div to change when the user click a li in the menu.               <ul class="mainNav">         <?php wp_nav_menu( array( 'container' => false, 'theme_location' => 'primary' ) ); ?>     </ul>          $(function(){     $('.menu-item-23').click(function(){       $('#changeMe').css('background-image','url("../wp-content/themes/theme-name/i/logo4.png")');     });      I am able to make this work if I replace .menu-item-23 with other elements on the page - so I know it isn't a file path issue, and I don't think it's the jQuery code. It seems like I'm not selecting the list item properly, but I have tried dozens of different selectors, (li#menu-item-23, li.menu-item-23, ul.mainNav li#menu-item-23 etc etc)


Which of my blog and personal data is being transfered when Wordpress automatically checks for updates?

I'm generally concerned about privacy and I've heard that with each contact to the Wordpress API for update checks and similar a lot of my blogs data is being transfered. To get a better impression, I'd like to more specifically know which data is being transfered and when. What's done with the information and who has access to the information? How long is it stored? I found no information about that in the packages readme nor on the worpdress.org website so far.


adding checkbox to theme customizer

I have been trying to add a checkbox into the theme customizer. I have a checkbox added using this code in my functions.php               function theme_customizer_register_checkbox($wp_customize) {          $wp_customize->add_section( 'savior_global_options', array(         'title'          => 'Global Options',     ) );          $wp_customize->add_setting( 'show_supporters', array(         'default'        => true,         'type'           => 'option',         'capability'     => 'edit_theme_options' )     );          $wp_customize->add_control( 'display_supporters', array(         'settings' => 'show_supporters',         'label'    => 'Show supporters section',         'section'  => 'savior_global_options',         'type'     => 'checkbox',     ) );      }      add_action( 'customize_register', 'theme_customizer_register_checkbox' );      Once I got the checkbox working. I found that when I checked the box, it wouldn't change state. It always stayed checked. I did some searching and found post on this site that was solved but didn't leave an answer. The post led me to think that I needed to change the value in my `$wp_customize->add_control()` function to a unique value. So I changed it to `display_supporters`. This solved my issue but now I can't get the value of the checkbox. When I dump this variable,               $supporters = get_theme_mod('display_supporters);      I get bool(false) and it stays at that. no matter what I do to the checkbox. What am I missing?


Extending post by email

Just putting my feelers out on this one, I need to be able to accept incoming emails and add them as posts, however I want to be able to do a bit of processing first, for example I want to change the slug, prepend a string to the title etc. Is there a way I can hook into the email function, change some data and then let it continue. I also might want to reject the email if it isn't sent from an approved domain (this will be a field in a custom post type). Are my requirements achievable or am I barking up the wrong tree? **Edit** I have discovered the `save_post` hook, although it fires after the post has saved... not really what I'm looking for. Is there a hook that gets fired before a post is saved, giving me all the info about the post, especially where it's been created from. **Edit 2** Alternatively is there a way to add a post manually... so I handle the receiving of the email with my own code + cron, then have an API to create a new post with?


Choosing images size when uploading

Is there a way to choose which image size I want to resize to when uploading? I need one image type to be for a featured image (resizing would be for thumbnail size and 900x350) and the other type for a gallery (resizing each image for thumbnail size and 640x480). So when I want to upload an image i get to choose which type i want to work with. I have read about registering image sizes in Wp codex and thats all clear just that I dont know how to put selections for it during upload. Couldnt find any plugin either that would do this. Any information no matter how small is really welcomed


Dynamically create/remove terms in taxonomy when custom post type is published/trashed

Am struggling a bit with creating & removing terms based on when a custom post type is published and trashed. Ideally, I would like to create a new term in my custom taxonomy when a custom post type is published. Then, when that post in the custom post type is trashed, I need to check and make sure that the count on that term is 0, and if so automatically delete the appropriate term. Here's what I have thus far. The creation function is working correctly, but for I cannot figure out the trashed function. Your expertise is much appreciated!!               <?php     /**       * Automatically creates terms in 'custom_taxonomy' when a new post is added to its 'custom_post_type'       */     function add_cpt_term($post_ID) {         $post = get_post($post_ID);              if (!term_exists($post->post_name, 'custom_taxonomy'))             wp_insert_term($post->post_title, 'custom_taxonomy', array('slug' => $post->post_name));     }     add_action('publish_{custom_post_type}', 'add_cpt_term');     ?>      ...and now for the function I'm having a hard time getting to work the way I want it to:               /**       * Automatically removes term in 'custom_taxonomy' when the post of 'custom_post_type' is trashed       */     function remove_cpt_term($post_ID) {         $post = get_post($post_ID);         $term = get_term_by('name', $post->post_name, 'custom_taxonomy', 'ARRAY_A');              if ($post->post_type == 'custom_post_type' && $term['count'] == 0)             wp_delete_term($term['term_id'], 'custom_taxonomy');     }     add_action('wp_trash_post', 'remove_cpt_term');     ?>


Wordpress Enqueue for homepage only, functions.php, wp-framework

I'd like to replace my:                   if(is_home())         {             wp_enqueue_script( 'homestuff', get_theme_part( THEME_JS . '/home.js' ), array( 'jquery' ), null, true );             wp_enqueue_script( 'jquerycolor', get_theme_part( THEME_JS . '/jquery.color.js' ), array( 'jquery' ), null, true );         };      Which is currently in header.php, by putting it in a functions.php file instead. Trying to tidy everything up on a sprawling client's site. I'm using wp-framework and ideally would stick this inside the enqueue_assets function in the main parent_theme class. Although this isn't really a wp-framework issue, I'd just like to know: How can I get is_home() to work from a functions file? Is there an alternative, using globals, I need to know about?


Struggling with add_rewrite_rule

I've read this: Wordpress redirection to get url friendly That led me to this: 1) wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-the-basics/ 2) wp.tutsplus.com/tutorials/creative-coding/the-rewrite-api-post-types- taxonomies/ and per the end of #1, I installed this: wordpress.org/extend/plugins/monkeyman-rewrite-analyzer/ With the plugin I can see and test the rule I added via add_rewrite_rule. However, when I try the same URL request on the front end site I get a 404. I'm struggling to sort out why the rule isn't being applied. p.s. Sorry about the links not being links but my rep from StackOverFlow doesn't seem to carry over to wp.SE


Link listings with image

So I'm really new to Wordpress and I'm trying to create a simple widget. I want the widget to list the logos of my site's affiliates (similar to the "check out our shows" section on http://www.howstuffworks.com/). I also want it to be easy for the administrators to add/remove images from the list of partners. In other words, I don't want to have to modify the widget's code in order to change the partners. At a very high level what are the steps that I might follow to build this widget?


Displaying the last page of posts

I'm using a custom loop to display posts using pagination. My query shows 4 posts per page, and there are 4 pages, so 16 posts in total. Is it possible to load in the last page of posts first? So when I load the query, it first shows page 4, then when I click 'show next' it shows page 3, et cetera?


How to manage a big collection of files with wordpress?

I have a collection of nearly 3000 swf files that will be used in some of WP's post. Two options that I can think of--   1. Upload them to WP Media Library,they'll become attachments, I can query attachment to get them.    2. FTP to host, create database table, query them directly. Which way would you recommend?


How to get Facebook to see YouTube/Blip embeds when sharing a link?

I run a sketch comedy channel that posts new content regularly. On our site (powered by WordPress.org) we embed Blip.tv players. The problem is, whenever we share a link on Facebook to one of our video pages on our site, it doesn't recognize that there's a video on the page at all. It just loads the featured image of the post. I'd like viewers to be able to watch our videos from their walls - anyone got an answer? In case you're not sure what I'm talking about, here's a link to one of our video pages so you can test on FB for yourself: http://www.juliansmith.tv/2009/11/malk/


Using spellchecker plugin in TinyMCE

I have installed PSpell and updated the config file to use it instead of GoogleSpell. Then in my functions file I have added spellchecker to the plugins part and the button. The button shows up but it doesn't work. After looking at the source code I see that spellchecker is not included in the TinyMCE init.               function customize_tinymce($in) {     $in['remove_linebreaks'] = false;     $in['gecko_spellcheck'] = false;     $in['keep_styles'] = true;     $in['accessibility_focus'] = true;     $in['tabfocus_elements'] = 'major-publishing-actions';     $in['media_strict'] = false;     $in['paste_remove_styles'] = false;     $in['paste_remove_spans'] = false;     $in['paste_strip_class_attributes'] = 'none';     $in['paste_text_use_dialog'] = true;     $in['wpeditimage_disable_captions'] = true;     $in['plugins'] = 'inlinepopups,tabfocus,paste,media,fullscreen,wordpress,wpeditimage,wpgallery,wplink,wpdialogs,wpfullscreen,spellchecker';     $in['content_css'] = get_template_directory_uri() . "/editor-style.css";     $in['wpautop'] = true;     $in['apply_source_formatting'] = false;     $in['theme_advanced_buttons1'] = 'formatselect,|,bold,italic,underline,|,bullist,numlist,blockquote,|,link,unlink,|,pastetext,pasteword,removeformat,spellchecker,|,charmap,|,outdent,indent,|,undo,redo,|,wp_fullscreen';     $in['theme_advanced_buttons2'] = '';     $in['theme_advanced_buttons3'] = '';     $in['theme_advanced_buttons4'] = '';     return $in;     }      Viewing the source I see the plugins being loaded but not spellchecker.               ref : {plugins:"inlinepopups,tabfocus,paste,media,fullscreen,wordpress,wpeditimage,wpgallery,wplink,wpdialogs,wpfullscreen",theme:"advanced",language:"en"}      What am I missing?


Woocommerce exclude specific category products from related products

I'm trying to exclude products from two specific categories from showing up in the related products on the content single products page. The closest idea I have stumbled upon is this code from http://docs.woothemes.com/document/exclude-a-category-from-the-shop-page/. Any idea how to modify it for related products and NOT for the shop page?               add_action( 'pre_get_posts', 'custom_pre_get_posts_query' );          function custom_pre_get_posts_query( $q ) {          if ( ! $q->is_main_query() ) return;     if ( ! $q->is_post_type_archive() ) return;          if ( ! is_admin() && is_shop() ) {              $q->set( 'tax_query', array(array(             'taxonomy' => 'product_cat',             'field' => 'slug',             'terms' => array( 'knives' ), // Don't display products in the knives category on the shop page             'operator' => 'NOT IN'         )));          }          remove_action( 'pre_get_posts', 'custom_pre_get_posts_query' );      }


Change default post style to columns

I'm trying to format each post that the user uploads. I need the paragraphs to be floated to the left in the first column, and the images to be in a floated left in the second column. (I've tried posting an image, but I need at least 10 reputation) I am new to Wordpress development, so I apologise if this is a silly question.


I'm using $wpdb to connect to a different database than my WordPress one like this:               $newdb = new wpdb(DB_NEW_USER, DB_NEW_PASSWORD, DB_NEW_NAME, DB_NEW_HOST);      I need to insert multiple rows into the database. I used the code from this StackOverflow answer. To run the query, I used the following code:               $newdb->query( $newdb->prepare("$query", $values));      When I did `echo $query`, this's the result: (there are more than 3 columns, but I shortened if for times sake)               INSERT INTO table (column1, column2, column3) VALUES ('%s', '%s', '%s')      When I did `var_dump($values)`, it returned an array with the same amount of strings as I have columns. When I ran the query, I got the following error: > WordPress database error: [Query was empty] I tried selecting from the database in a similar fashion and it did work, so my connection to the db is working. What am I doing wrong?


HTML5 Summary tag in editor

I'd like to use the summary tag to summarise the content of a post but i'm facing a couple of issues doing that:   1. There isn't an option for it in the wysiwyg - how can i add in elements to the format drop down?   2. Wordpress strips out the element when the editor loads, so saving the page again removes the tag. How can i white list "summary"?


Date-Based Conditional Tag

I'd like to have a conditional tag that is something like this:               <?php if (is_single()&&is_older_than_october_2011()){do this}; ?>      The part I'm trying to highlight is the is_older_than_october_2011() aspect. There doesn't appear to be any conditional tag that WP offers which has this functunality? Thanks, Brad


What is the official way to consume the Wordpress API? (api.wordpress.org)

Was wondering if anyone knows here if the API at api.wordpress.org is free to use without keys. I haven't really found any information about key registration. I'd like to use it to make a few requests a day, really not many < 50 requests. What's the official way to go about consuming that API? Thanks!


Using AJAX in a plugin to submit form - REALLY confused

Having a bit of trouble using all the Wordpress ajax hooks, and functions. Been reading this post: 5 Tips for Using Ajax in Wordpress But became confused after trying all the code and applying it to an Ajax form. I am calling a function from my plugin class to echo a from on the single posts pages for users to "Swoon" over. The form prints fine. Here's the form code:               //the html form for the front end     function ds_swoons_form(){     global $post, $current_user;     get_currentuserinfo();              $form = '
';         $form .= '
';              $form .= '<form id="entry_swoon_form" name="entry_swoon_form" action="" method="POST">';             $form .= '<input type="hidden" name="ds_postid" value="'.$post->ID.'" />';             $form .= '<input type="hidden" name="ds_userid" value="'.$current_user->ID.'" />';             $form .= '<input type="submit" value="Swoon" class="swoon-submit" />';         $form .= '</form>';          return $form;     }//end ds_swoons_form      My Enqueues:               wp_enqueue_script('json-form');          // embed the javascript file that makes the swoons AJAX request     wp_enqueue_script( 'swoon_ajax_request', plugins_url('ds-swoons/js/swoon-ajax-form.js'), array( 'jquery' ) );          // declare the URL to the file that handles the AJAX request (wp-admin/admin-ajax.php)     wp_localize_script( 'swoon_ajax_request', 'SwoonAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );          //add the AJAX action     add_action( 'wp_ajax_swoons_submit_action', array('DS_Swoons','ds_ajax_swoons_form_submit') );      And my javascript:               jQuery('#entry_swoon_form').ajaxForm({     target: '#swoon-response',     dataType: 'html',     data: {            action: 'swoons_submit_action'           },     url: SwoonAjax.ajaxurl,     success : function(responseText) {               jQuery('#swoon-response').html('Swooned!');     }     });      I'm a newbie when it comes to AJAX so I may be way off on this. The article I read was good until I got to the end where it showed a sample ajaxForm request and I got lost. The ajax form function never runs and the page just reloads. SO I am guessing that one of my enqueue functions is not correct. Thanx in advance. EDIT -------------------------------------------------------- New jQuery.post method code - but it still not working               jQuery(document).ready(function(){     jQuery('.swoon-submit').click(function(){         jQuery.post(             // see tip #1 for how we declare global javascript variables             SwoonAjax.ajaxurl,             {                 // here we declare the parameters to send along with the request                 // this means the following action hooks will be fired:                 // wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit                 action : 'swoons_submit_action',                 //nonce for validation                 //swoonNonce : SwoonAjax.swoonNonce,                 // other parameters can be added along with "action"                 postid : SwoonAjax.postid,                 userid : SwoonAjax.userid             },             function( response ) {                 alert( response );             }         );     });     console.log(SwoonAjax.ajaxurl)     });      I do get a really quick error in FireBug but I can't see whats going on quick enough before the request ends. And no error remains after the .post has run. No data is being updated in the DB so I know it is not getting fired. Thanx EDIT 2 ----------------------------------------------------------------- I've gotten the form to submit and it updates the DB using the following code:               jQuery(document).ready(function(){     jQuery('.swoon-submit').click(function(){         var $form = $( 'form#entry_swoon_form' ),             postid = $form.find( 'input[name="ds_postid"]' ).val(),             userid = $form.find( 'input[name="ds_userid"]' ).val();         jQuery.post(             // see tip #1 for how we declare global javascript variables             SwoonAjax.ajaxurl,             {                 // here we declare the parameters to send along with the request                 // this means the following action hooks will be fired:                 // wp_ajax_nopriv_myajax-submit and wp_ajax_myajax-submit                 action : 'swoons_submit_action',                 //nonce for validation                 //swoonNonce : SwoonAjax.swoonNonce,                 // other parameters can be added along with "action"                 ds_postid: postid,                 ds_userid: userid                  },             function( response ) {                 alert( response );             }         );         return false;     });      However: I cannot seem to get the form field values (hidden) to be sent to the PHP function for DB insertion. The info is in the Firebug console as being sent but no information gets to the PHP function. I think it has something to do with how I am sending the fields to the PHP function but am unsure. Thanx!


What is the best way to add an advanced / intermediate / beginner tag to a post

Suppose you have a WordPress blog that you are using to produce tutorials, and that you would like to split up your posts according to skill level (i.e. beginner, intermediate, advanced) depending on how technical/difficult/advanced the tutorial is. Furthermore, the blog in questions spans several categories, so using these might be inappropriate. So what's the best way? Using custom field?, tags?, post-type? or even sub- categories? I'm assuming that it shall never be required to retrieve all 'beginner' posts from all categories, though this flexibility would be a bonus.


Change or update WordPress loop based on dropdown selection

I have a Contact Us page which is showing 9 locations on the sidebar by querying the custom post type "Distributors." I want the user to be able to use a drop down that is populated by the taxonomy "Location." For example, if the user selects "California" from the drop down, it will automatically update the list with just those posts tagged with California. What is the best way to go about this? Also, I don't mind if the page refreshes when the user narrows down to their Country or State. Ideally, I'd like the parent categories to be shown in one drop down, ie. Germany, Japan, USA, etc. Then a second drop down become populated with the children of that category. For example, the first drop down would display USA, then California would show up in the second drop down. Thanks.


How to automatically activate users after registration without activation email?

I want to auto-login my users after signup without an activation email requirement (I'm not concerned about spammers). How might I go about doing this? Thanks!


How to access & display images from a post without textual content ( and vice versa) according to best wordpress practices

Looking to create a customized single.php for my posts. In one column I'd like to display all images added through the add media function (inserted into post). In the next column all other content associated with the post (except images). What I need is the proper / best practice method of doing so. I am just beginning to decipher php but want to do things properly from the VERY beginning. So how can look at the post, pull just the attachment images for display in one column, pull just the textual content (with markup) for another column? Also, when would I consider creating this as a function for functions.php instead of the process residing inside of single.php or any other template file for that manner? Here's what I have so far:
     <?php if(have_posts()) : while(have_posts()) : the_post(); ?>
         <?php         $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID );          $attachments = get_posts($args);         if ($attachments) {             foreach ( $attachments as $attachment ) {                 the_attachment_link( $attachment->ID , false );             }         }         ?>

<?php single_post_title(); ?>
         <?php the_content(); ?>
     <?php endwhile; ?>     <?php else : ?>
<?php _e('Sorry, no posts matched your criteria'); ?>
     <?php endif; ?>


wpdb->prepare function remove single quote for %s in SQL statment

I am using the below wpdb->prepare function in a sql statement. I am passing in several variables some field names and some values. When I try to use the %s for the field name it puts single quotes around it. How can I prevent the single quotes around the field name? The sql statement will not execute with the single quotes? ` $query = $wpdb->prepare("SELECT DISTINCT wp_geo.%s, wp_geo.$field2 FROM wp_geo WHERE wp_geo.$field3=%s",$field1, $typevalue);` Output with single quotes around 'county_short' field name: `SELECT DISTINCT wp_geo.'county_short', wp_geo.county_slug FROM wp_geo WHERE wp_geo.type='trailers'`


media resize/crop possibilities?

Under admin panel -> media settings there are no minimal width option for thumb or other image modes ex: I would like to crop image widthout distortion -> height 124px and minimum-width 124px and maximum-width 500px So it doesnt allow images to crop below 124px and over 500px but holding always 124px height How to make it happend? some script for functions.php, some plugin?


Hook with jquery script is not working in wp-admin

This is the hook and script Im using, the jquery script itself is working as you can see in this fiddle:               function my_custom_admin_footer(){                  echo '                       <script type="text/javascript">                          jQuery(document).ready(function($) {                         $(".checkIt").change(function (e) {                             if ($("input:checkbox:checked").length > 1) {                                      alert("Only one attribute is allowed.");                                 $(e.target).prop('checked', false);                             }                         });                     });                 </script>             ';      }          add_action('admin_footer', 'my_custom_admin_footer');      in wp-admin, i get only blank page instead, the problem is definitely in jquery because simple alert script does work:               jQuery(document).ready(function(){         alert("Hello");      });      I don't get it. Although, I'm not pro in jquery neither php so maybe Im missing something. Thank you for your help


bulk deleting empty items in the media library

I wrote a function, which should rename my attachments, based on the post title. Unfortunately this function created over 10.000 empty instances in my media-library, before I was able to stop it. The instances are all attached to a single post, which I could delete if it's necessary. I'm really sorry to bother you with the ask for help, but I'm a bit scared to screw things up again.


Moved Wordpress site to new server, directory permissions not working correctly

I built a Wordpress on my hosting space and then transferred it my clients server - followed all the instructions and pretty much everything works fine. The ONLY problem I have is that the directory permissions aren't working correctly, they're all set correctly (generally 755) - but I cannot update/install plugins and cannot upload media. Any ideas? Thank you


Installed domain-based Multisite but can't access wp-admin (redirect loop)

I've installed a domain-based Multisite on my server, and everything works including each of the subdomains. Here I should explain that I imported a Database that was on my Local Mac, and then changed the details in the database for each site. However, I now can't access wp-admin for the main domain or any of the subdomains, Chrome just tells me there is a Redirect Loop (http://cl.ly/Qg7K). Let me just clarify that I can't access wp-admin at all, i.e not even the login page. I'm reasonably confident with Wordpress, Databases and servers, so I can most likely get any data back for you and carry things out to test, try to fix etc. Thanks for any help! **EDIT** : People asked for my .htaccess code. It was copied from my localhost installation but I was using a Virtual Host so there were no paths involved. I'm no expert with .htaccess though so something could be wrong.               RewriteEngine On     RewriteBase /     RewriteRule ^index\.php$ - [L]          # uploaded files     RewriteRule ^files/(.+) wp-includes/ms-files.php?file=$1 [L]          # add a trailing slash to /wp-admin     RewriteRule ^wp-admin$ wp-admin/ [R=301,L]          RewriteCond %{REQUEST_FILENAME} -f [OR]     RewriteCond %{REQUEST_FILENAME} -d     RewriteRule ^ - [L]     RewriteRule ^(wp-(content|admin|includes).*) $1 [L]     RewriteRule ^(.*\.php)$ $1 [L]     RewriteRule . index.php [L]


Adding a custom admin page

I want to add a page of content (a readme file) in the WordPress admin, I can't seem to find how to do this in the codex - can anyone point me in the right direction? It will literally just be a simple page with a few paragraphs of content.


Asian language multisite IDN subdomain

Using an IDN internationalized domain name in Thai appears to work fine. However when using WP Multisite Subdomain network and trying to ADD SITE as a SUBDOMAIN - it is not accepting the Thai characters and generates error "Missing or invalid site address." I tried changing some setting in phpMyAdmin collation and wp-config.php but didn't really know what to do with that, and plugin intlWP which looked like it would do it, has not fixed the problem of using Thai as the subdomain site address. this isn't a translation issue, it's a URL and WP Admin interface issue I think. there has to be a way to have a WP multisite using Thai language subdomains... any suggestions welcome. thanks


Custom Post Type Definition should not be in the theme - how?

Is there a way to define a custom post type independent from a theme? All sources I found in the web do that in the theme, fuctions.php or via including other theme-specific php-files. But in my eyes this makes no sense. Where is the separation between content (custom post type) and layout (theme)? An other problem I see is changing the theme. Data is still in database, I know, but no way to edit or add new items.


Possible to enqueue scripts and CSS to Multisite Network dashboard?

Is it possible to enqueue scripts and css **only** to the Network Admin Dashboard? To edit the network admin menu, you have this hook: `network_admin_menu`, so I also tried `network_admin_enqueue_scripts`, but this didn't work. Thanks! Roc.


Search results highlight breaks my read more link

I am attempting to add highlighting to my search results in the theme that I am coding. I found the way to do it on this thread: How to highlight search terms without plugin and it worked wonderfully. However, it is conflicting with my read more link whenever a permalink contains the search term by trying to do the replacement in the read more link causing the link to break oddly. Does anyone have a suggestion or fix for it? The following codes I use are as follows:               function search_excerpt_highlight() {         $excerpt = get_the_excerpt();         $keys = implode('|', explode(' ', get_search_query()));         $excerpt = preg_replace('/(' . $keys .')/iu', '\0', $excerpt);         echo '
' . $excerpt . '
';     }          function supralegal_auto_excerpt_more( $more ) {         return '…' . supralegal_read_more_link();     }     add_filter( 'excerpt_more', 'supralegal_auto_excerpt_more' );          function supralegal_read_more_link() {         return ' ' . __( 'Read more', 'supralegal' ) . '';     }


How to add categories to page editor?

I'm trying to add the categories selector to the "page" editor workspace. The code below does the trick, however, none of the values are saved with the page. Any help much appreciated!               add_action('admin_menu', 'my_post_categories_meta_box');     function my_post_categories_meta_box() {         add_meta_box('categorydiv', __('Categories'),              'post_categories_meta_box', 'page', 'side', 'core');     }


Run search query again without pagination gives no results?

## Update: This question isn't really relevant anymore. I switched some code, so now the filtering works. Looks like the query wasn't working, because I triggered the `indexTaxonomyCounts` function from a template? But I now have another problem, but will write a different question for that. ## Original question: I want to filter my custom products by some taxonomy and meta filters. This works for regular queries, but not for my search results. At least, the filtering works, but getting the right counts somehow does not. What I do is the following:   * I hook in to the `pre_get_posts` hook and use the data from the $_GET to create taxonomy and meta queries.   * Then I store the query I just created (including the filtering), so on the result page I can calculate for each taxonomy/meta filter, how many results there totally are. But somehow when I run the stored search query again (but now with `posts_per_page=-1`) I get no results? No idea why. Does the search perform different queries then regular queries? Maybe it's more clear with some code snippets. The following function works, the search results are filtered and all:               add_action('pre_get_posts', array($this, 'pre_get_posts_hook'));          public function pre_get_posts_hook( $query_obj )     {         //check if this isn't the internal query, since that doesn't need filtering ^^         if( empty($query_obj->query_vars['internal-query']) || $query_obj->query_vars['internal-query'] != true ) {         $tax_query = array();         $meta_query = array();              if(isset($_GET['someMetaFilter']) {             foreach(explode(',', $_GET['someMetaFilter']) as $tax_value) {                 $meta_query[] = array(                     'key' => urldecode($tax_value),                     'value' => array(''),                     'compare' => 'NOT IN',                 );             }         }              if(isset($_GET['someTaxonomyFilter']) {              foreach(explode(',', $_GET['someTaxonomyFilter]) as $tax_id) {                 $ids[] = urldecode($tax_id);             }                  $tax_query[] = array(                 'taxonomy' => $type,                 'field' => 'term_id',                 'terms' => array_map('intval', $ids),                 'include_children' => false,                 'operator' => 'AND'             );         }              if(count($tax_query)) {             $tax_query['relation'] = 'AND';                  $query_obj->set('tax_query', $tax_query);         }              if(count($meta_query)) {             $meta_query['relation'] = 'AND';                  $query_obj->set('meta_query', $meta_query);         }              //only set it if we have set a specific filter set         if(count($tax_query) || count($meta_query)) {             self::$query_vars = $query_obj->query_vars;         }              return $query_obj;     }      This function is called from the result-page, to calculate all the counts for the taxonomies. But this just results in 0 results :S The only thing I do is getting the previously used query_vars and set the `post_per_page` to -1 (so I can get all the results, instead of only for this page)               public static function indexTaxonomyCounts()     {         if (isset(self::$query_vars)) {             $query_vars = self::$query_vars;             $query_vars['posts_per_page'] = -1;             $query_vars['internal-query'] = true; //to prevent the pre_get_posts_hook to adjust the query                  $wpQuery = new WP_Query($query_vars);                  //somehow in the regular query, this works. But when I do this in a search result page, the $wpQuery->have_posts() is empty! But the result page does have 30+ results or something :S                   // The Loop             if ( $wpQuery->have_posts() ) {                 while ( $wpQuery->have_posts() ) {                     ...                     do some calculations based on the taxonomy and such                     ...                 }             }                  /* Restore original Post Data */             wp_reset_query();         }     }      I tried so many things, I don't even know what anymore. I copied the query_vars, I copied the WpQuery. I tried to reconstruct the WpQuery by adding the `?s=$_GET['s']` or something. But to no result. So if anyone knows what's the cause of this, I would be so grateful! ## Additional information (1) Ok, I did some logging (using the `posts_request` filter and I have 2 dumps of data. It's way too big to dump it here. So I uploaded them to my Dropbox: This one works: https://www.dropbox.com/s/a07defqjx1d95j0/regular-page.php   And this one does not: https://www.dropbox.com/s/zboiw4fjqojotw7/search- page.php As you can see in the code snippets above, I just use the same query_vars. The two query_vars differ only slightly, but I'm not sure what's causing that. The `SELECT * FROM mug_posts WHERE 1=2` is weird, but the search does give back results - so I figured that search does some other query??? ## Additional information (2) Ok, it's getting even weirder. I simplified the logic, I stripped out the whole taxonomy filtering and such. In the `pre_get_posts` I store the query and on a page I call a function, which checks that stored query and runs that again. But I get no results back!               public function pre_get_posts_hook( $query_obj )     {         if( $query_obj->is_page() == false ) {             if( $query_obj->query_vars['post_type'] == 'products' ) {                     if ( ($query_obj->is_main_query() == false && $this->filterIsActive())                         || $query_obj->is_search()) {                         self::$query_vars = $query_obj->query_vars;                 }             }         }              return $query_obj;     }          public static function indexTaxonomyCounts()     {         if (isset(self::$query_vars)) {             $query_vars = self::$query_vars;                  $wpQuery = new WP_Query($query_vars);                  echo $wpQuery->have_posts(); // -> false                  /* Restore original Post Data */             wp_reset_query();         }     }      I printed the query_vars for a regular page and for the search page and they are almost identical: Query vars on a regular page: https:// www . dropbox.com /s/nxy75avclwtr5xt/results.php   Query vars on a search page: https:// www . dropbox.com /s/g72nhsfwej9q95c/no- result.php (sorry for the weird link, but I don't have enough reputation yet to post more links) You'd think since the query vars are (almost) identical, they'd give the same result. Nope :P


How to return number of found rows from SELECT query

I wrote a function which is supposed to return the number of rows found in a SELECT query but it always either seems to return 0 or an array. I have been messing around with this for about an hour now and I still can't figure it out! I'm sure I'm doing something stupidly wrong. The MySQL Table               +--------+-------------+---------------------+     | postid |     ip      |        time         |     +--------+-------------+---------------------+     |   1234 | 192.168.0.1 | 2014-01-29 14:27:02 |     |   5678 | 192.168.0.2 | 2014-01-29 14:27:02 |     +--------+-------------+---------------------+      PHP               ### Search for IP in database     function postviews_get_ip($id, $ip) {         global $post, $wpdb;              $wpdb->get_results("SELECT * FROM $wpdb->wp_postviews_ips WHERE postid = $id AND ip = $ip");              $rowcount = $wpdb->num_rows;              return $rowcount;     }          postviews_get_ip($id, $_SERVER['REMOTE_ADDR']);     //both $id and $_SERVER['REMOTE_ADDR']) return the values I'm searching for in the database


SQL query to update post_date (one post = one single date & time)

I have 120 posts of one category ready for my wordpress blog. For the moment, posts are drafts and I don't want to schedule them manually. I want to publish them like this:   * 4 articles each day from the 1st of August 2013   * 1 at 10am / 1 at 2pm / 1 at 5pm / 1 at 8:30pm What I need is the SQL query to:   * Update date_post for the 120 posts, based on the needs described above   * Change "draft" mode to "pending"   * The publication order is based on the creation date of the posts: the older will be the first published. I'm lost in the queries and loops. If someone could help, it would be very very appreciated. Thanks a lot, Chris


Dynamically Set Wordpress Post Title To The Category Name

I have a few custom post types set up. However, a couple of them have the title field removed from the edit screen because a title does not make sense in some aspects. However, I now find that all posts are being saved improperly with the text "Autosaved Post" or whatever. Is it possible to set the post title upon saving the post to be the assigned category name? The reason I want this is because I am building a record label website with the following custom post types:   * Artists   * Homepage Carousel   * Videos   * Tours The homepage carousel does not need a title and I would like it to perhaps be the following format: "Bandname Carousel" bandname being the category name of which would only be band names. Should I add the title field back in and use jQuery to perhaps set the title instead of writing a custom Wordpress plugin and set the field to read only so the user can't make changes to it? The reason I want to set the title is to stop the annoying "Autosaved Post" value being added to the title hence preventing the user from being able to sort through and differentiate between posts that have been added.


Custom Query num_rows returns wrong amount

So I have a custom query that fetches all posts in a given category. I am trying to get the number of rows returned but it is giving me the wrong number. Instead of 11, I am getting 14. Does anyone know why?               <?php     $pageposts = $wpdb->get_results($wpdb->prepare("         SELECT * FROM $wpdb->posts         LEFT JOIN userContests ON ($wpdb->posts.ID = userContests.contestID)         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)         WHERE $wpdb->posts.post_status = 'publish'          AND $wpdb->posts.post_type = 'post'          AND $wpdb->posts.post_date < NOW()          AND $wpdb->term_taxonomy.taxonomy = 'category'         AND $wpdb->term_taxonomy.term_id IN(3)         ORDER BY $wpdb->posts.post_date DESC         "), OBJECT);          /*   $rows = $wpdb->num_rows;  <------ Wrongly returns 14 */          /*   $rows = $wpdb->get_var($wpdb->prepare("      <--------- Correctly returns 11             SELECT COUNT(*) FROM $wpdb->posts             LEFT JOIN userContests ON ($wpdb->posts.ID = userContests.contestID)             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)             WHERE $wpdb->posts.post_status = 'publish'              AND $wpdb->posts.post_type = 'post'              AND $wpdb->posts.post_date < NOW()              AND $wpdb->term_taxonomy.taxonomy = 'category'             AND $wpdb->term_taxonomy.term_id IN(3)             ORDER BY $wpdb->posts.post_date DESC")); */     echo "Number of rows = " .$rows;     ?>      My work around seems like a waste of resources. Is there something more efficient?


Settings api sanatize callback not being triggered

I'm creating a custom settings page for a custom theme however the callbacks for sanatizing the data in the fields are not being called (I put in xdebug breakpoints in them to check).               /**     *------------------------- Admin Page Titles -------------------------     */          function header_options_text() {         echo '
These options affect the Header content.
';     }          /**     *------------------------- Header Options -------------------------     */          function phone_number_input() {         $option = get_option('header_phone');         echo '<input id="header_phone" name="header_phone" size="40" type="text" value="'.$option.'"> </input>';     }     function header_logo_input() {         $option = get_option('header_logo');         echo '<input id="header_logo" name="header_logo" size="40" type="text" value="'.$option.'"> </input>';     }          /**     *------------------------- Header Validation Options -------------------------     */          function header_phone_validate($input) {         $new_input=trim($input);         if(get_option( 'header_phone' ) === $new_input || !preg_match('/^[\+\d\(\)\- ]*$/', $new_input))             $new_input=get_option( 'header_phone' );         return $new_input;     }     function header_logo_validate($input) {         $new_input=esc_url_raw(trim($input));         if(get_option( 'header_logo' ) === $new_input && !filter_var($new_input, FILTER_VALIDATE_URL))             $new_input=get_option( 'header_logo' );         return $input;     }          /**      *------------------------- Actually create the pages and add to menu -------------------------      */          add_action( 'admin_menu', 'ec1_admin', 10, 0 );     function ec1_admin() {         add_menu_page( 'EC1 Theme Options', 'EC1 Theme Options', 'manage_options', 'ec1-theme-options', 'ec1_theme_options_page' );     }          function ec1_theme_options_page() {         ?>

EC1 Theme Options
             <form action="options.php" method="post">                 <?php settings_fields('header-options'); ?>                 <?php settings_fields('header-logo-options'); ?>                 <?php do_settings_sections( 'ec1-theme-options' ); ?>                 <input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />             </form>
         <?php     }               add_action('admin_init', 'plugin_admin_init');     function plugin_admin_init(){         register_setting( 'header-options', 'header_phone', 'header_phone_validate' );         register_setting( 'header-logo-options', 'header_logo', 'header_logo_validate' );         add_settings_section('header-options-pane', 'Header Options', 'header_options_text', 'ec1-theme-options');         add_settings_field('header_phone', 'Phone Number', 'phone_number_input', 'ec1-theme-options', 'header-options-pane');         add_settings_field('header_logo', 'Header Logo', 'header_logo_input', 'ec1-theme-options', 'header-options-pane');     }     ?>


Do I have anything to worry about when switching to a default theme to test for plugin conflictions?

WordPress noob here. I want to test a site I'm working on for plugin conflicts. I've heard that switching to a default theme and testing the plugins will do this. My question is, is this going to mess my theme up when I reactivate it? Is it going to be as simple as hitting 'reactivate'?


Is there a way to localize role labels?

I'm using Justin Tadlock's Members plugin to create new roles and WP Role on Registration to display them on the registration form. I've got a multilang site (English and Spanish) and I've localized my custom taxonomies using qTranslate. I can't use qTranslate's quicktags in the Role Label field on the Member's plugin because it doesn't save it properly (even with `$new_role_label = strip_tags( $_POST['role-label'] );` commented out on role-new.php) and I can't go into the database to make the changes there because then it breaks. I've seen very scarce info about the WP function translate_user_role but I'm not sure it. There's not much else to go on.


How do I modify this wpdb query to include posts that have a post_status of publish and draft?

I'm using the following function to count the number of posts an author has made from a custom post type.               <?php     function count_user_posts_by_type($userid, $post_type) {         global $wpdb;         $where = get_posts_by_author_sql($post_type, TRUE, $userid);         $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );         return apply_filters('get_usernumposts', $count, $userid);     }     ?>        To echo out the count I use               <?php echo count_user_posts_by_type(wp_get_current_user()->ID, 'custom_post_type_name'); ?>      From my testing it seems to count just the posts that have a `post_status` of `publish`. How can I modify the function so it also counts posts that are `draft` ? I've tried to modify the query as follows but it seems to have no effect whatsoever:               $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where AND post_status IN ('publish','draft')" );


How to best include widget area just on homepage?

I have a front-page.php defining the homepage of my theme (a Genesis child theme). In it, I have some custom widget areas, like so:               genesis_register_sidebar( array(         'id'    => 'cta',         'name'    => __( 'How do I Connect?', 'site' ),         'description'    => __( 'This is the cta widget for the home page.', 'site' ),     ) );          add_action( 'genesis_after_header', 'cta_widget' );          function cta_widget() {        genesis_widget_area( 'cta', array(            'before' => '

How do I Connect?
',            'after' => '

'        ) );     }      I originally had it in the functions.php and it worked fine.. I added some widgets to it, etc with no problems. But now I moved it to front-page.php as I saw mentioned as a way to restrict it to the home page, and now it is listed under inactive widgets, although I can still edit them it is confusing for the user, plus I cannot add any more in this way. Is this expected behaviour?


How can I let users access a specific attachment?

I'm trying to add a XML file to my site that users can access when I give them the url. www.domain.com/blank01/blank02/file.xml As of right now, blank01 and blank02 don't exist as pages. Down the road they will have content and links that eventually take you to "file.xml" and others. But for right now I just want to put this file on my WP and make it accessible to my users when they go to this specifically designated url, but I can't figure out how to. I tried to upload it to the library, but the file type wasn't accepted, but I fixed that. Once I did get it uploaded to the library, I couldn't change the link. Also, what do I need to do to make blank01 and blank02 exist without being pages, just categories for now? Or do they have to be pages?


Wordpress pagination on custom script

I am using WP for my RealEstate project where all properties are pulled from a custom table (wp_listing) and displayed in a custom page template (page- realestate.php). I know WordPress has built-in pagination methods to deal with paged content (pages, posts lists). I want to use that same pagination methods for the list of properties I am fetching from my custom DB table. Is this possible? How? [EDIT] Code is something like:               echo '
';     $properties = $listing->getProperties();     for($i = 0; $i < count($properties) ; $i++) {         echo '
' . $properties[$i]['address'] . '
';     }     echo '
';


How to allow wordpress to create username with symbols like +

I want to allow users to create username with **+** symbol. but wordpess removing the symbol by the register validation process. If I gave username as **abcd+123** , the user registered with username as **abcd123**. I need the username registered as it is with **+** symbol. Answers are greatly appreciated.


How to change the output of gallery shortcode

I would like to **add the media description as a data-attribute** to each image of the gallery. All the other answers favour the solution to copy the whole code from media.php to functions.php and change it there. But isn't there a more intelligent way? It's way to much **code duplication** in order to change one single line of code!