Get_the_terms restrict output

I have a custom post type Holiday associated with a taxonomy Country. On my single-holiday.php, I use the taxonomy to display in the title. For example Holiday in Spain (Spain being the tax) Rarely, but it can happen, a holiday can be in 2 taxonomy terms. Creating a problem for my title display as I use get_the_terms. Somebody has better solution for me. My code is as follow               $taxonomy = 'country';                 $terms=get_the_terms($post->ID,$taxonomy);                           if($terms) {                         foreach( $terms as $termcountry ) {                      ?>
Holiday in <?php echo $termcountry->name;?>
}}


jQuery does not work

I am working on a project where I need jQuery for. I added this to my functions, and the scripts are loaded in my header if I watch my page source, but jQuery doesn't work. What am I doing wrong?               function stn_script_enqueuer() {              wp_register_script( 'ajax-vote', get_template_directory_uri() . '/js/ajax-vote.js', array('jquery') );                   $nonce = wp_create_nonce("vote_nonce");         $stn_vote_data = array(             'ajaxurl' => admin_url( 'admin-ajax.php'),             'nonce' => $nonce,         );         wp_localize_script( 'ajax-vote', 'stn_vote', $stn_vote_data );                   wp_enqueue_script( 'jquery' );         wp_enqueue_script( 'ajax-vote' );          }     add_action( 'init', 'stn_script_enqueuer' );


403 'GET' Error on Wordpress Jquery Autocomplete

**Overview:** I am trying to create a simple jquery autocomplete in a wordpress theme, on a custom template page containing a form. I wish for it to work both front-end, for logged in users, and the general public. It is part of a theme (not a plugin). I have followed along with a post here, but I am unsuccessful. **The problem:** Even though I am expecting autocomplete to occur as I type in the name field (the one with id="autocompleteID"), I don't see anything happening. Also, there is an error in my GET request, it says '403 forbidden'. (see image below) ![I get an error on the GET request](http://i.stack.imgur.com/bEMx0.jpg) ## INFO: * * * Relevant Directory Structure of the theme root: > >      . >      |--autocompleteAjax.js >      |--template-customers.php >      |--functions.php >   **autocompleteAjax.js:**               jQuery(document).ready(function($){     $("#autocompleteID").autocomplete({         source: function(request, response){             jQuery.getJson(autocompleteAjaxObject.ajaxurl + "?callback=?&action=autocompleteAjaxAction",request,function(data){                 response(jQuery.map(data, function(item){                     jQuery.each(item, function(i,val){                         val.label = val.whatever;                     });                     return item;                 }))             })         }        })       })      **template-cusotomers.php (A custom template page):**               get_header(); ?>

                                      <?php while ( have_posts() ) : the_post(); ?>                                              <?php get_template_part( 'content', 'page' ); ?>                                              <?php                                              if (is_user_logged_in()):?>                                                      <form type="post" action="" id="newCustomerForm">                                                              Name:                                                         <input id="autocompleteID" name="name" type="text" />                                                              Email:                                                         <input name="email" type="text" />                                                              Phone:                                                         <input name="phone" type="text" />                                                              Address:                                                         <input name="address" type="text" />                                                              <input type="hidden" name="action" value="addCustomer"/>                                                         <input type="submit">                                                 </form>

                                                   <?php                                                  global $wpdb;                                                 $customers = $wpdb->get_results("SELECT * FROM friends;");                                                      echo "
";                                                 foreach($customers as $customer){                                                         echo "
";                                                         echo "".$customer->name."	";                                                         echo "
";                                                 }                                                 echo "
";                                         else:                                                 echo "Sorry, only registered users can view this information";                                         endif;                                                                                ?>                                                                                <?php endwhile; // end of the loop. ?>

      **a snippet from Functions.php:**               wp_register_script('autocompleteAjaxHandle',get_stylesheet_directory() .   "/autocompleteAjax.js");     wp_enqueue_script('autocompleteAjaxHandle');     wp_localize_script('autocompleteAjaxHandle', 'autocompleteAjaxObject', array(         'ajaxurl'=>admin_url('admin-ajax.php'),         'autocompleteAjax_nonce'=>wp_create_nonce('autocompleteAjax_nonce_val'),         'action'=>'autocompleteAjaxAction'         ));          function get_autocomplete_suggestions(){         $_GET['term'];         $suggestions_array=array( 'captain crunch', 'chex', 'cheerios');              $response = $_GET["callback"]. "(" . json_encode($suggestions_array) . ")";         echo $response;         exit;     }          add_action('wp_ajax_autocompleteAjaxAction', 'get_autocomplete_suggestions');     add_action('wp_ajax_nopriv_autocompleteAjaxAction', 'get_autocomplete_suggestions');       ** ## Overview of the Question: I aspire to create a simple jquery autocomplete functionality, but I am having a difficult time understanding why the form does not behave as I would expect, and it seems to be producing a GET error. What is causing the problems, and what can I do to be more successful?


Post Pagination Titles

what I'm trying to do is set a different title for each page of the post pagination. So for example example.com/post-title/ title in the header is "Post Title" example.com/post-title/2/ title in the header is "This is another post title" I tried applying what is here post pagination names, not numbers to get to do this without luck (all I got was errors so eneded up deleting it).


Loop through posts of CatA and store value of CatB in separate array

Custom post type "Wines" has two categories: Regions & Producers. "Wines" has a value for both a Region and a Producer. I want to loop through posts in [Category => Region, Term => X] and get each post's respective term in [Category => Producer, Term => ?]. The final goal is to go through the newly created array and:   * Remove duplicate entry terms   * Sort terms by alphabetical order   * Loop through array, and list posts (wines) of each respective entry (producer term) I know you may be asking, "Why not just go to the producer's archive?"...I know. _cry_ The Region's archive needs to display a list of posts ordered by the terms in the producer category. Thanks a bunch.


File(X) is not within the allowed path(s):

I installed wordpress on a windows server with Parellels. It is a shared hosting. When i upload images it gives the following warning: > Warning: file_exists() [function.file-exists]: open_basedir restriction in > effect. File(C:\Windows\Temp\phpEEB0.tmp) is not within the allowed path(s): > (F:\Inetpub\vhosts\ozatashipyard.com\httpdocs) in > F:\Inetpub\vhosts\ozatashipyard.com\httpdocs\wp-includes\functions.php on > line 1998 849 When i check the library, i see that the file is uploaded. I tried adding the below code to `wp-config.php` but it didn't make a change.               define( 'WP_TEMP_DIR', ABSPATH.'wp-content/tmp/') ;      What may be the problem.


How to import XML to Wordpress as post and custom fields?

I need to import content (daily) from a xml file into wordpress. I am not looking for a specific answer, and I don't expect someone to write the whole code here, I just need some guidance on how to accomplish it. I plant to:   1. Write php script to load XML file with simplexml_load_file()   2. Read the file with SimpleXMLElement()   3. Put everything in a loop and use wp_insert_posts to create each post   4. I am going to use ACF for custom fields, not sure if ACF has function to do that programmatically.    5. Run everything with a cron job Does the above seems logical? Or am I going about it the hard way. I would appreciate if someone with more experience importing XML files could give me some tips, or things to consider. Thanks.


Deregister multiple scripts using a function?

I'm trying to deregsiter multiple scripts using the following function.               add_action( 'wp_print_scripts', 'my_deregister_javascript', 100 );     function my_deregister_javascript() {         if ( !is_page(array('order', 'shopping-cart', 'checkout') ) ) {         wp_deregister_script( 'tcp_scripts' );     }      How do I use this function to deregsiter multiple scripts? Thanks in advance.


change a post status when users update posts?

Is there an efficient way to change a post status from 'published' to 'draft' when a user of a certain type tries to update their posts. I tried something along these lines               function change_post_status($post_id)     {       if(current_user_can('rolename'))       {         $current_post = get_post( $post_id, 'ARRAY_A' );         $current_post['post_status'] = 'draft';         wp_update_post($current_post);       }     }          add_action('pre_post_update','change_post_status');       The code looks good to me but for some reason it doesnt work properly and I think it creates an endless loop(forcing me to restart my SQL server).


Assign Role and capablitis on frontend registration

I have created 2 custom roles "customer" & "employee" form admin "members" plugin. I am trying to assign these to user registering for site according to options (customer & employee) they selecting. I have tried with functions in functions.php               function my_new_user_registered( $user_id )      {         global $wpdb;         global $wp_roles;         if ( $_POST['member_type'] )         {                 $member_type = $_POST['member_type'];                 $company_name = $_POST['company_name'];                 $company_code = $_POST['company_code'];                 $user_id;                           //add_role($member_type);  **// here I am trying**             //set_role($member_type);              if($member_type == 'employee')             {                 $owner = 'N';                 $wpdb->query("insert into wp_comapny_user(company_id, user_id, owner) values ('$company_code', '$user_id', '$owner')");                 //$wpdb->query("insert into wp_user_meta(user_id, meta_key, meta_value) values ('$user_id', 'member_type', '$member_type')");                  }             elseif($member_type == 'customer')             {             $owner = 'Y';             $wpdb->query("insert into wp_company(company_name) values ('$company_name')");             $company_id = mysql_insert_id();                  $wpdb->query("insert into wp_comapny_user(company_id, user_id, owner) values ('$company_id', '$user_id', '$owner')");                  }              }     }      But both are not working. It's assigning default "Subscriber" in user meta "wp_capablities" option. How to solve this issue? Any help please.


Login form doesn't log in

I have this code on my website that occasionally will log users in and occasionally just redirect to the wordpress login page. Additionally, if a field was left blank it would actually show errors on the wordpress login page, but now it just does a redirect.                           <form id="wp_login_form" action="<?php echo site_url('/wp-login.php', 'https') ?>" method="post">

Email

<input type="text" name="log" id="log" value="<?php echo wp_specialchars(stripslashes($user_login), 1) ?>" size="25" />

<?php _e('Password') ?>

<input type="password" name="pwd" id="pwd" size="25" autocomplete="off" />

<input name="rememberme" type="checkbox" id="rememberme" value="forever" <?php checked( $rememberme ); ?> /> <?php esc_attr_e('Remember Me'); ?>

<input type="submit" name="submit" value="<?php esc_attr_e('Log In'); ?>" class="button" />
                     <input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>"/>

<a href="<?php echo get_option('home'); ?>/wp-login.php?action=lostpassword">Forgot password?

                     </form>


How to batch update post content with custom post meta value

I have a custom meta box, using WPAlchemy, in which I am looking to get rid of. However, I would like to get all posts that have a specific custom meta value set, and insert it into the begininning of the post content, then delete the meta value. I have a feeling this post gets me close, as I have been able to successfully add content to the beginning of posts, but have been unsuccessful accessing and adding the custom meta value I'm after. I'm also a little unsure of when to hook into WordPress and perform my actions. Anyone have any suggestions on the best way to go about this? I figured I would build a simple plugin, activate it, let it do it's job, then remove it.


How to modify the Loop from a plugin (instead of a theme)

I am building a plugin which sets up a custom post type with some meta information. I'd like that information to show up in the loop (in particular the one on the main page). How can I modify the post-template without writing a theme. I was looking at home_template but it is deprecated for 3.3


Plugin Recommendation: Slideshow Gallery Delayed Image Loadging

I am wondering if there is a WordPress plugin that creates a slideshow of images where: *flash isn't used *images are not all loaded at once and instead are loaded after page load I have a requirement for numerous images to be present in a slideshow that are high res. All images need to be stored locally (e.g. no flickr). I took a cruise through one or two plugins but they include all the images at once. Which murders page load times. Any suggestions?


Search returns everything if search term has a space

When I try to search for terms with spaces, such as "lord of the rings", it returns all of my posts. However, if I just type "lord", it returns results. Any ideas what would be causing this?


Showing All the Posts in the Loop

this code here
             <?php gab_dynamic_sidebar('Subnews1');?>                  <?php             $postnr = of_get_option('of_wn_nr8') + of_get_option('of_wn_nr8a');             if (intval($postnr) > 0 ) { ?>                 <a href="<?php echo get_category_link(of_get_option('of_wn_cat8'));?>"><?php echo get_cat_name(of_get_option('of_wn_cat8')); ?>                 <?php                 $count = 1;                 $args = array(                  'post__not_in'=>$do_not_duplicate,                   'posts_per_page' => $postnr,                   'cat' => of_get_option('of_wn_cat8', 1)                 );                 $gab_query = new WP_Query();$gab_query->query($args);                  while ($gab_query->have_posts()) : $gab_query->the_post(); if (of_get_option('of_dnd') == 1) { $do_not_duplicate[] = $post->ID; }                 ?>                 <div class="featuredpost<?php if($count == of_get_option('of_wn_nr8') or $count == $postnr) { echo ' lastpost'; } ?>">                               <?php if ($count <= of_get_option('of_wn_nr8')) { ?>
                             <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php printf( esc_attr__( 'Permalink to %s', 'wpnewspaper' ), the_title_attribute( 'echo=0' ) ); ?>" ><?php the_title(); ?>

                         <?php                             gab_media(array(   'imgtag' => 1,   'link' => 1,                                 'name' => 'wn-subnews',                                 'enable_video' => 0,                                 'catch_image' => of_get_option('of_catch_img', 0),                                 'enable_thumb' => 1,                                 'resize_type' => 'c',                                 'media_width' => 120,                                  'media_height' => 103,                                  'thumb_align' => 'alignleft',                                 'enable_default' => 0                             ));                         ?>

<?php echo string_limit_words(get_the_excerpt(),27); ?>…
                              <?php gab_postmeta(); ?>                     <?php } else { ?>                              <a class="listtitle" href="<?php the_permalink() ?>" rel="bookmark" title="<?php printf( esc_attr__( 'Permalink to %s', 'wpnewspaper' ), the_title_attribute( 'echo=0' ) ); ?>" ><?php the_title(); ?>                          <?php } ?>
                 <?php $count++; endwhile; wp_reset_query(); ?>             <?php } ?>
      , is this, shown in this image here http://d.pr/i/7efk , on this site http://dev.dmichel.net/adv/ . what i need to happen is to show all 4 posts, rather than just 1. What I tried to do to show all 4 posts is this               <?php                 $count = 1;                 $args = array(                   'posts_per_page' => 4,                   'cat' => of_get_option('of_wn_cat8', 1)                 );                 $gab_query = new WP_Query();$gab_query->query($args);                  while ($gab_query->have_posts()) : $gab_query->the_post(); }                 ?>      But it doesn't seem to work. I'd like help showing all 4 posts above the titles


Is there any better/faster code than this ? It shows the categories that an author had ever posted in

I have this query that shows the categories that a user had posted in. For example if I have 3 cats, name NEWS, MEDIA, PUBLICATIONS and the author had only posted in the first two, it will show NEWS MEDIA Is there any better code than this or an improvement because my db is really huge and it gives me throttling? Thank you.               <?php     $author = get_query_var('author');     $categories = $wpdb->get_results("     SELECT DISTINCT(terms.term_id) as ID, terms.name         FROM $wpdb->posts as posts         LEFT JOIN $wpdb->term_relationships as relationships ON posts.ID = relationships.object_ID         LEFT JOIN $wpdb->term_taxonomy as tax ON relationships.term_taxonomy_id = tax.term_taxonomy_id         LEFT JOIN $wpdb->terms as terms ON tax.term_id = terms.term_id     WHERE posts.post_author = '{$post->post_author}' ");     ?>          <ul>         <?php foreach($categories as $category) : ?>     <?php if ( ($category->ID == '3')   || ($category->ID == '4')  || ($category->ID == '5')) { ?>         <li>             <a href="<?php echo get_category_link( $category->ID ); ?>/?author_name=<?php echo $curuser->user_login; ?>" title="<?php echo $category->name ?>">                 <?php echo $category->name; ?>             </a>         </li>     <?php } ?>         <?php endforeach; ?>     </ul>


Make the Status, Visibility, or Date fields opened by default in the Publish box

By default, the Status, Visibility, and Date fields in the Publish metabox are closed, and you have to click **Edit** to show them. Is there a way to make these fields visible by default? The hidden elements all have a class of `hide-if-js`.


960gs different classes on teasers posts

I'm having hard time trying to use teasers post in my wordpress theme (based on 960gs), as you can see here http://img17.imageshack.us/img17/794/schermata20110420a15045.png what I got till now is one "featured" post and three teasers post with thumbnails that will probably be six (so it'll have seven posts displaied in the homepage). The problem is that to do so I have to assign a class "grid_2 alpha" to the teasers post and I don't know how to assign this class to just the first teaser on the left, lefting the other ones with no alpha or omega class and putting the omega class to just the last teaser post (the seventh). If can help, here's the code I'm using for the loop:               <?php $firstClass = 'firstpost'; ?>     <?php /* Start loop */ ?>     <?php while (have_posts()) : the_post();  ?>              <?php if (function_exists('yoast_breadcrumb')) { if (is_page() && $post->post_parent) { yoast_breadcrumb('
','
'); } } ?>          <div class="post <?php echo $firstClass; ?>">     <?php $firstClass = 'grid_2 alpha'; ?>          <a href="<?php echo get_permalink(); ?>"><img src="<?php echo get_post_meta($post->ID, "Thumbnail", true);?>" width="140" height="100" style="padding-bottom:20px;" />
<a href="<?php echo get_permalink(); ?>"><?php the_title(); ?>
         <?php the_content(); ?>         <?php wp_link_pages(array('before' => '
' . __('Pages:', 'roots'), 'after' => '
' )); ?>
     <?php endwhile; // End the loop ?>      also I would like to know how I can add some text above the teaser section under the first featured post. Sorry for the too many questions and for my bad english, as you can understand I'm not a developer but I searched for one week and couldn't find anything helpful for my problems. Thanks in advance for any help, I really appreciate it. Ok so there are the other loop pages and the front-page.php **front-page.php**               <?php get_header(); ?>             <div id="content" class="<?php echo roots_container_class; ?>">                  <div id="main" class="<?php echo get_option('roots_main_class'); ?> grid_6" role="main">
                         <?php get_template_part('loop', 'page'); ?>

                 <aside id="sidebar" class="<?php echo get_option('roots_sidebar_class'); ?> grid_6" role="complementary">
                         <?php get_sidebar(); ?>

     <?php get_footer(); ?>      **loop-search.php**               <?php /* If there are no posts to display, such as an empty archive page */ ?>     <?php if (!have_posts()) : ?>

Sorry, no results were found.

         <?php get_search_form(); ?>           <?php endif; ?>          <?php /* Start loop */ ?>     <?php while (have_posts()) : the_post();  ?>                  <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?>
                     <time pubdate datetime="<?php the_time('c'); ?>">Posted on <?php the_time('l, F jS, Y') ?> at <?php the_time() ?>.</time>                     <?php if (get_option('roots_post_author') == 'checked') { ?>
                         Written by <?php the_author(); ?>
                     <?php } ?>
         <?php if (is_archive() || is_search()) : // Only display excerpts for archives and search ?>                 <?php the_excerpt(); ?>         <?php else : ?>                 <?php the_content('Continue…'); ?>         <?php endif; ?>
                                      <?php $tag = get_the_tags(); if (!$tag) { } else { ?>
<?php the_tags(); ?>
<?php } ?>
                  <?php comments_template('', true); ?>          <?php endwhile; // End the loop ?>          <?php /* Display navigation to next/previous pages when applicable */ ?>     <?php if ($wp_query->max_num_pages > 1) : ?>
<?php next_posts_link( __( '← Older posts', 'roots' ) ); ?>

<?php previous_posts_link( __( 'Newer posts →', 'roots' ) ); ?>
              <?php endif; ?>      **loop-single.php**               <?php /* Start loop */ ?>     <?php while (have_posts()) : the_post();  ?>              <article <?php post_class() ?> id="post-<?php the_ID(); ?>">
<?php the_title(); ?>
                 <time class="updated" datetime="<?php the_time('c'); ?>" pubdate>Posted on <?php the_time('l, F jS, Y') ?> at <?php the_time() ?>.</time>                 <?php if (get_option('roots_post_author') == 'checked') { ?>
                     Written by <?php the_author(); ?>
                 <?php } ?>                 <?php if (get_option('roots_post_tweet') == 'checked') { ?>                 Tweet                 <?php } ?>
                 <?php the_content('
Read the rest of this entry »
'); ?>
                              <?php wp_link_pages(array('before' => '
' . __('Pages:', 'roots'), 'after' => '
' )); ?>
<?php the_tags(); ?>
                          <?php comments_template(); ?>
          <?php endwhile; // End the loop ?>      **loop.php**               <?php /* If there are no posts to display, such as an empty archive page */ ?>     <?php if (!have_posts()) : ?>

Sorry, no results were found.

         <?php get_search_form(); ?>           <?php endif; ?>          <?php /* Start loop */ ?>     <?php while (have_posts()) : the_post();  ?>                  <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?>
                     <time pubdate datetime="<?php the_time('c'); ?>">Posted on <?php the_time('l, F jS, Y') ?> at <?php the_time() ?>.</time>                     <?php if (get_option('roots_post_author') == 'checked') { ?>
                         Written by <?php the_author(); ?>
                     <?php } ?>
         <?php if (is_archive() || is_search()) : // Only display excerpts for archives and search ?>                 <?php the_excerpt(); ?>         <?php else : ?>                 <?php the_content('Continue…'); ?>         <?php endif; ?>
                                      <?php $tag = get_the_tags(); if (!$tag) { } else { ?>
<?php the_tags(); ?>
<?php } ?>
                  <?php comments_template('', true); ?>          <?php endwhile; // End the loop ?>          <?php /* Display navigation to next/previous pages when applicable */ ?>     <?php if ($wp_query->max_num_pages > 1) : ?>
<?php next_posts_link( __( '← Older posts', 'roots' ) ); ?>

<?php previous_posts_link( __( 'Newer posts →', 'roots' ) ); ?>
              <?php endif; ?>      Really thanks for your help.


What action hook can I use to add a JavaScript to a page post using a theme template that is not including get_header() nor get_footer()?

So the reason why I am don't want to include `get_header()` or `get_footer()` tags is because this page will be loaded as an iframe using the thickbox modal plugin and its content will be a form and I don't want the aforementioned tags to render all the menus and banner images and menus as well as the footer content because it will make for lots of scrolling on this page. However, current I'm running something like this:               add_action('template_redirect', 'my_plugin_add_js');      However, when I take out the `get_header()` and `get_footer`() tags then the JavaScript doesn't load even though the javascripts inside the '`my_plugin_add_js`' are being added within the body HTML tags at the end and not inside the head tags, like so:               wp_register_script("validate_form", plugins_url('js/my_plugin_validate_form.js', __FILE__), array('jquery', 'validation'), '1.0', true);      So I gather that the 'template_redirect' action hook is not the right one to use.


How can I get the last posts by user role?

I have a custom post type ("News"), and a custum user role ("Friends"). How can I get the last "News" written by "Friends" ?


Posts being viewed

I am looking for a way to list posts being viewed but I can't find anything online. Is it even possible? I've seen some websites that have these loops, "What other readers are currently reading". I'm using the following loop to list random set of videos               <?php                 if ( is_home() ){           $cat = get_query_var( 'cat' );           query_posts(array('orderby' => 'rand', 'showposts' => 10, 'cat'=>$cat));           }           while (have_posts()) : the_post();       ?>      How can I show posts being viewed? anyone


Uploading PDF using Media Uploader

I have been using a custom code to upload images to Wordpress using custom metaboxes. Here is the code:               <script type="text/javascript">              jQuery(document).ready(function( $ ) {                  var formfield;                  $('.upload_button').click(function() {                 $('html').addClass('Image');                 formfield = $(this).prev('.upload_image'); // .attr('name');                 tb_show('', 'media-upload.php?type=image&TB_iframe=true');                 return false;             });                  // user inserts file into post. only run custom if user started process using the above process             // window.send_to_editor(html) is how wp would normally handle the received data                  window.original_send_to_editor = window.send_to_editor;             window.send_to_editor = function(html){                      if (formfield) {                     fileurl = jQuery('img',html).attr('src');                          $(formfield).val(fileurl);                     tb_remove();                     formfield = '';                     $('html').removeClass('Image');                      } else {                     window.original_send_to_editor(html);                 }             };              });               </script>      My actual problem is that I have to upload now a PDF. I have try to use the .urlfield input in the media uploader with keeps the URL of the uploaded file. I have changed fileurl = jQuery('img',html).attr('src'); to fileurl = jQuery('.urlfield',html).val(); but it does not work. What can I do please? An alternative tip I would like to know is how can I change the "Insert button" value text to something like "Use this file". Thanks in advance.


How to exclude categories from get_categories() select list inside a widget admin panel

I have a widget that I need to add a category select list to. The end user should be able to select a category and I need to save the category ID with the widget. I've hit a stumbling block in that I cannot get my exclude array to work. The excluded cats still show up in the dropdown. What am I doing wrong?               function form( $instance ) {         $instance = wp_parse_args( (array) $instance, array( 'title' => '', 'text' => '', 'hide_title' => '', 'category_id' => '' ) );         $title = format_to_edit($instance['title']);         $text = format_to_edit($instance['text']);              $hide_title = $instance['hide_title'] ? ' checked="checked"' : '';         $category_id = $instance['category_id'] ? ' selected="selected"' : '';         ?>         <p>             <label for="<?php echo $this->get_field_id( 'title' ); ?>">Title:</label>             <input id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" value="<?php echo $title; ?>" class="widefat" />         </p>         <select id="<?php echo $this->get_field_id( 'category_id' ); ?>" name="<?php echo $this->get_field_name( 'category_id' ); ?>">           <option value=""><?php echo esc_attr(__('Select a Category')); ?></option>           <?php              $args = array('exclude' => array(get_cats()),'hide_empty' => 0 );             $categories=get_categories($args);              foreach ($categories as $category) {                 $option = '<option value="'.$category->cat_ID.'">';                 $option .= $category->cat_name;                 $option .= '</option>';                 echo $option;             }          ?>         </select>          function get_cats(){         $exclude_cats = array(             get_cat_ID('test1'),             get_cat_ID('test2'),             get_cat_ID('test3'),             );         return $exclude_cats;     }


Can I make a parent page of the blog and have it display a paragraph/thumbnail of certain entries?

WP 3.2.1 The title just about says it all. I'd like to make a parent page of the blog that will dynamically show a little teaser of certain entries (either the most recent or random, depending on what my client wants). Is something like this possible? If so, how?


Custom order of terms for custom taxonomy in admin and website

I have a custom taxonomy registered for my custom post type. I need to make it possible for a user to specify the order in which the taxonomy terms should appear (something like menu order for pages). Then when displaying the taxonomy terms on the site I will use the specified custom order to order them. What is the best way to do it? Is there any plugin for it? Many thanks, Dasha


Put standard wordpress options into a theme options panel?

I'm developing a theme for a client, and I want to allow her to change the site title, description, and her password as needed. However, I don't want to give access to all of the other options (e.g. the site URL). I have some experience creating a theme options panel (via this article on nettuts+), and was thinking it would be great if I could put those options into the panel as well. Would be great to get some direction!


Plugin Appends ugly url string to index

A custom background plugin has started to cause certain browsers (FF, IE8,9, Safari) to reveal an appended url string when viewing the index page: http://dearearth.net \- this mostly shows when not visiting the site directly, but rather when going through, for example, google. This persists in IE 9 even after refresh or page reload, but does not on the other browsers. Screenshot: http://i55.tinypic.com/2nv9fh3.jpg I have the following custom permalink structure enabled:`/%category%/%postname%/` Thanks for any input!


Issue to set a default language

I'm working on a multiple language site (Catalan and Spanish). I set by default Catalan as the main language but we found that users who navigates with spanish browsers the content appears in spanish instead of catalan. How can I fix it to always appears the text in catalan regardless of the language of the browser? Sure it's a dummy question but I can't find any workaround to solve it!. Thanks in advance


Why is Wordpress filtering Pastebin URL's

WordPress seems to be filtering Pastebin URLs. When attempting to include pastebin links into either new or pre-existing posts, the following error is returned: > “Not Found” It seems most — if not all — pastebin URLs kill my posts. If a pastebin URL is included in a new post, it is deleted altogether and even the draft is sent into the abyss. If a pastebin URL is included into a pre-existing post, new changes are deleted and the post reverts to the previous draft. I contacted my hosting company and they claimed to have no idea how or why this is occurring. Their only suggestion was that it must be WordPress. So this has me wondering; what is causing this? I can’t think of any plug-ins that would be responsible, and beyond that, I can’t think of much else without seeming paranoid. Whatever the cause, I thought it strange enough to document. If it is a restriction, it is supremely stupid. If only a bug, I’d sure like to know more about it.


Customising the search function?

I'm rebuilding this website - http://www.mediwales.com/news on the WP platform. I'm struggling with the search area in the grey box. I'm removing region and date so we don't have to worry about those but how can I setup the search by keyword AND sector? I've created a custom taxonomy called "news" which will represent the sectors. As far as I know the normal search just searches the entire site for a keyword. How can I setup the search to search for a keyword but if a sector is selected only search for the keyword within that sector? And then display the results. UPDATE:                                       <?php $args = array(         'show_option_all'    => '',         'orderby'            => 'name',         'order'              => 'ASC',         'show_last_update'   => 0,         'style'              => '',         'show_count'         => 0,         'hide_empty'         => 1,         'use_desc_for_title' => 1,         'child_of'           => 0,         'feed'               => '',         'feed_type'          => '',         'feed_image'         => '',         'exclude'            => '',         'exclude_tree'       => '',         'include'            => '',         'hierarchical'       => true,         'title_li'           => '',         'show_option_none'   => __('No categories'),         'number'             => NULL,         'echo'               => 1,         'depth'              => 0,         'current_category'   => 0,         'pad_counts'         => 0,         'taxonomy'           => 'news',         'walker'             => 'Walker_Category' );          ?>              <?php echo wp_list_categories($args); ?>               <?php     function Search_with_in_a_tax( &$query ) {         if ( is_search() && isset($_GET['sector_array'])) {             $tax_query = array(                  array(                     'taxonomy' => 'news',                     'terms' => $_GET['sector_array'],                     'field' => 'term_id',                   )              );              //turn it into a WP_Tax_Query object             $tax_query = new WP_Tax_Query($tax_query);             $query->set("tax_query", $tax_query);         }     }     add_action('pre_get_posts', 'Search_with_in_a_tax', 1);     ?>            <form method="get" id="searchform" action="<?php bloginfo('home'); ?>/">     <div><input type="text" size="18" value="" name="s" id="s" />     <input type="submit" id="searchsubmit" value="Search" class="btn" />     </div>     </form>      This is what I have so far. It seems to be searching the keywords and picking out the news. I can't make the sectors selectable (like the link at the top) though? How could I link the two? The search would then search within that sector (taxonomy) for the keyword.


Additional custom header image

Has anyone seen a way to add a new header_image to a theme? I need to add two configurable images in a theme. It doesn't really matter if it gets added as a new "Header" admin theme menu or if it's added to the existing Apperance->Header menu. I'm a bit new to plugin development so any help in the right direction is appreciated. I can't really find any hooks or actions to attach to. Similar to this request


How to hook wp_mail to add a custom email as BCC for each sent email?

Is there a way to hook into the wp_mail function to add a custom email as hidden (BCC) copy to each email sent? If so, how? -edit- It's not like I want to send an email with BCC, I would like to make the necessary hooks to add the BCC to every sent email (many different functions in my theme make use of `wp_mail`)


How to make the 'request' filter work?

I'm trying to get a Page to display a custom query using the snippet posted here. The following is in my `functions.php`:               function alter_the_query($request) {         $dummy_query = new WP_Query();  // the query isn't run if we don't pass any query vars         $dummy_query->parse_query($request);         // this is the actual manipulation; do whatever you need here         if($dummy_query->is_page('blog')) $request['category_name'] = 'Blog';         // and then         return $request;     }     add_filter('request','alter_the_query');      The page called "Blog" has a basic loop inside- so it should be displaying whatever `WP_Query` tells it to. However, it is only displaying the Page content- which should have been ignored. I can't seem to find a reference that explains the properties of the `$request` object, so I'm not sure what I should do to make this snippet work. Any ideas?


WordPress Tag Page Hook?

Is there any hook for a tag page, so I can alter it's content before outputting?


Custom permalinks structure

I would like to have this structure:               www.mysite.com/2013       (must show all posts of 2013)               www.mysite.com/my-category/2013      (must show all posts of 2013 and of category "my-category")               www.mysite.com/my-category/my-tag/       (must show all posts of category "my-category" and of tag "my-tag")               www.mysite.com/my-category/      (must show all posts of category "my-category")               www.mysite.com/my-category/title-post      (must show the post) How can I do it?


Adding tables to dashboard pages programmatically?

I think that is not possible with some actions or filters, I know that I can do it just with html and using right css styles, and of course php to achieve what I need, or to write some minde actions. Is there already some predefined functions for this or not? Thanks.


Random meta field from specific custom post type

I am loading single images into a post and calling their source from my custom post type template `single-photo.php` :               src: "<?php echo get_post_meta($post->ID, 'single_photo', true); ?>"      I want to pull an image from a random post only from that post type [PHOTO]. I know the url will be `mysite.com/photo/-random-photo-`, how could I grab a radom meta field?


Full text articles in the rss feed (i.e. without the more tag)

I can't seem to remove the "Continue reading..." link in my rss feed. The feed is located here: http://gforge.se/category/r/feed/ I use the <!--more--> tag manually and I've checked that the Settings->Reading->For each article in a feed, show: Full text but I guess this is only for the automated WP summary function. My issue seems to be closely related to this previous post, but I've tried the Full Text Feed plugin to no aid. According to the plugins homepage it's no longer needed... I'm not entirely sure which file Ramkumar suggests the changes for. I've tried editing the Full Text Feed plugin but it seems not to activate properly for my category feed, when I add a:               $content = "test";      it only shows when I'm in the general feed, gforge.se/feed/ but not in the R category where I want it. I've tried to find some other filter hook but after a quick RSS search haven't really found one that seems to do the job: https://codex.wordpress.org/Plugin_API/Filter_Reference \- with the the_category_rss seeming to be the closes one to my need.


wp_remote_get with Google Books API

Trying my hand at pulling some info from Google API, and having a bit of trouble. My code:               $body = array(         'intitle' => 'Test', //Returns results where the text following this keyword is found in the title.         'inauthor' => '',  //Returns results where the text following this keyword is found in the author.         'inpublisher' => '',  //Returns results where the text following this keyword is found in the publisher.         'key' => '', //API key         'subject' => '', //Returns results where the text following this keyword is listed in the category list of the volume.         'isbn' => '',  //Returns results where the text following this keyword is the ISBN number.         'lccn' => '',  //Returns results where the text following this keyword is the Library of Congress Control Number.         'oclc' => ''  //Returns results where the text following this keyword is the Online Computer Library Center number.     );          $args = array(         'body' => $body,         'timeout' => '5',         'redirection' => '5',         'httpversion' => '1.0',         'blocking' => true,         'headers' => array(),         'cookies' => array()     );          $response = wp_remote_get( 'https://www.googleapis.com/books/v1/volumes?q=search+terms', $args );          if( is_wp_error( $response ) ) {        $error_message = $response->get_error_message();        echo "Something went wrong: $error_message";     } else {        echo 'Response:<pre>';        print_r( $response );        echo '</pre>';     }      This consistently returns a 400 Error. If I comment out my `$body` array it returns perfectly (albiet without any custom parameters). Here is the error generated by Google:               Array     (         [headers] => Array             (                 [content-type] => text/html; charset=UTF-8                 [content-length] => 925                 [date] => Thu, 07 Feb 2013 15:09:24 GMT                 [server] => GFE/2.0             )              [body] =>                                 Google               400. That’s an error.          Your client has issued a malformed or illegal request. That’s all we know. [response] => Array ( [code] => 400 [message] => Bad Request ) [cookies] => Array ( ) [filename] => )       And here is a sample when it is returned correctly:               Array     (         [headers] => Array             (                 [expires] => Thu, 07 Feb 2013 15:20:03 GMT                 [date] => Thu, 07 Feb 2013 15:20:03 GMT                 [cache-control] => private, max-age=0, must-revalidate, no-transform                 [etag] => "oJJnsPwmwzPHUK-6EQKPiLmyEMg/ZaxtQy3hi8hix-i3y1_kfXYZAVA"                 [content-type] => application/json; charset=UTF-8                 [x-content-type-options] => nosniff                 [x-frame-options] => SAMEORIGIN                 [x-xss-protection] => 1; mode=block                 [server] => GSE             )              [body] => {      "kind": "books#volumes",      "totalItems": 1433,      "items": [       {        "kind": "books#volume",        "id": "tskCFsTjsnkC",        "etag": "0o/Hdha/+K0",        "selfLink": "https://www.googleapis.com/books/v1/volumes/tskCFsTjsnkC",        "volumeInfo": {         "title": "The Everything Word Search Book",         "subtitle": "Over 250 Puzzles to Keep You Entertained for Hours!",         "authors": [          "Charles Timmerman"         ],         "publisher": "Adams Media",         "publishedDate": "2005-11-15",         "description": "With more than 250 puzzles, 100-plus more than our competition, The Everything(r) Word Search Book provides hours of gaming fun! Searches are organized by amusing themes, including: Work Searches on the Job Global Word Searches Word Searches Alive! Word Searches for Big Bucks Decades of Word Searches to Search or Not to Search? The Everything(r) Word Search Book is sure to excite gamers of all abilities with humorous and challenging puzzles.",         "industryIdentifiers": [          {           "type": "ISBN_10",           "identifier": "1593374313"          },          {           "type": "ISBN_13",           "identifier": "9781593374310"          }         ],         "pageCount": 304,         "printType": "BOOK",         "categories": [          "Games"         ],         "averageRating": 4.0,         "ratingsCount": 3,         "contentVersion": "1.3.3.0.preview.3",         "imageLinks": {          "smallThumbnail": "http://bks0.books.google.com/books?id=tskCFsTjsnkC&printsec=frontcover&img=1&zoom=5&edge=curl&source=gbs_api",          "thumbnail": "http://bks0.books.google.com/books?id=tskCFsTjsnkC&printsec=frontcover&img=1&zoom=1&edge=curl&source=gbs_api"         },         "language": "en",         "previewLink": "http://books.google.com/books?id=tskCFsTjsnkC&printsec=frontcover&dq=search+terms&hl=&cd=1&source=gbs_api",         "infoLink": "http://books.google.com/books?id=tskCFsTjsnkC&dq=search+terms&hl=&source=gbs_api",         "canonicalVolumeLink": "http://books.google.com/books/about/The_Everything_Word_Search_Book.html?hl=&id=tskCFsTjsnkC"        },        "saleInfo": {         "country": "US",         "saleability": "FOR_SALE",         "isEbook": true,         "listPrice": {          "amount": 14.95,          "currencyCode": "USD"         },         "retailPrice": {          "amount": 9.99,          "currencyCode": "USD"         },         "buyLink": "http://books.google.com/books?id=tskCFsTjsnkC&dq=search+terms&hl=&buy=&source=gbs_api"        },        "accessInfo": {         "country": "US",         "viewability": "PARTIAL",         "embeddable": true,         "publicDomain": false,         "textToSpeechPermission": "ALLOWED",         "epub": {          "isAvailable": true         },         "pdf": {          "isAvailable": true.....      Thank you so much for any help you can offer.


Get author full name

I'm trying to display the first and last name of an author without having to change the "Display publicly as..." setting. Problem is, I can only seem to find solutions for either or, or at best display/nice/nickname. I would like to display the full name no matter what the user/author has chosen to "Display publicly as". Ideally I'd like to combine the below if possible.               get_the_author_meta('first_name')       and               get_the_author_meta('last_name')       Any help would be appreciated! EDIT (FINAL CODE):               $fname = get_the_author_meta('first_name');             $lname = get_the_author_meta('last_name');             $full_name = '';                  if( empty($fname)){                 $full_name = $lname;             } elseif( empty( $lname )){                 $full_name = $fname;             } else {                 //both first name and last name are present                 $full_name = "{$fname} {$lname}";             }                  $nicknames = "";             //get_author_role()             $userjob = get_cimyFieldValue(get_the_author_meta('ID'), 'JOBTITLE');             //$userjob = "";             ob_start();             coauthors_links();             //coauthors_firstname();             $authornames = $full_name;             ob_end_clean();                  if (empty($authornames)) {                  $authornames = get_the_author();             } else {                 $userjob = NULL;             }             $linkpre = "";             $linkpost = "";             if (custom_author_byline("") !== ""){                 $authornames = get_the_author();                 $linkpre = $linkpost = "";                 $userjob = NULL;             }             //echo coauthors_links();             //get_the_author_meta("nickname")             echo "
By ".$linkpre.$authornames.$linkpost."

".$categories_list." | ".get_the_date()."
";


How to create Custom image post?

I want to create a custom post type in which a post is only an image, title and description. I want to have a front-end option for users to enter such a post. What plugins do i need to play with in order to achive this? I Mean can i just use a taxonomy plugin and that's it? or is there some custom post plugin to base it on and the rest hard coded? And the most important - how can i get a front-end post option? The plugins i found contained an editor. As by now you understood, i'm completely lost, ANY help would be accepted with the highest regards, Thanks in advance.


How do you use prepare when asking for a list of id's

I'm looking to get a number of records back from the database given a list of numbers and was wondering how I would use $wpdb->prepare to do this (to take advantage of the sanitising vs SQL injection attacks that it gives me). A wrong way of going about what I'd like to achieve is `$wpdb->query($wpdb->prepare('SELECT * FROM wp_postmeta WHERE post_id IN (' . implode(',', $ids) .')` but this gives the chance of an SQL Injection attack (imagine one of the ids having the value "0); DROP TABLE wp_posts;"). NOTE: I'm not trying to select data from wp_postmeta, I'm just using it as example.


Back End US English > Front end other language

Asked and answered 3 years ago here: Different Language for Frontend and Backend However, step #2 of the top answer has me confused. Because WordPress is coded in US English (en_US) -- there doesn't seem to be a .mo file available. I do realize there are some plugins out there, but they don't seem to play well with multisite. Not sure if this rates a new post, but the system wouldn't let me comment on the other one.


How can I easily verify a core or plugin update has not broken anything?

I'm looking for ways to make updating WordPress less frightening for me. I created around 30 company websites based in WP in my career and I feel somewhat responsible for them in regards to security. Even if clients don't pay me for maintenance - clicking the "update" button every few months shouldn't be a big deal, right? I'm always resistant to upgrading for a couple of reasons   1. if something breaks on the website during updating clients are often not willing to pay for the time it takes to fix all the plugins. "It did work, why did you have to change it?!" Only option then is a roll-back and locking down the site.   2. if something breaks the website and I don't notice it I'm screwed. Explaining why a contact form would not work for several weeks after updating is something I don't want to do again.    3. updates for company websites are often not really mandatory. Most security issues happen around user submitted content, ajax and xml-rpc APIs - things I don't have to bother with when creating static pages that only get a few hundred visits per month. These websites tend to lie idle which of course increases the risk of updating. I have no problem updating a website that is only 2 months old - but I feel resistant to updating a 2 year old website running pre-3.0 or even pre-2.7. This makes it a game where I have nothing to win and can only loose. What are your ways of handling this? Any suggestions are highly appreciated and benefit to more secure WP installations out there? :) (for clarity: I'm mainly talking about small company websites or private blogs here where automated tests are not a realistic option)


Display Title by tags ( mysql )

I want to display in a sepparated page all the titles ( with link ) and a short description ( first 30-40 words from an article ) by a specific tag. For example, i use a "SPECIFIC TAG" on all my important articles and i want to export from mysql in a sepparated page title with link and a short description by that specific tag.


ACF Plugin How to make the customer add more fields in the post?

Example: I created a field with the name, "my-field", there can add it on the post, with a button "add another item" is that I want to create a list with several items, we only need to create multiple fields thus the client how they want to add. Further explained: I created a "Text" field in the "Advanced Custom Fields" to Custom Post Type: "tariff", the field is for notes, example of how it would look on the panel: Remarks: 1 - Note 1 | + add one more observation Then the customer clicked on "+ add one more observation" to automatically add a new field.


Broken Gravatar images in comments

I have no idea why, but recently, all new comments on my WordPress site have broken avatar image links. Here is a page that shows the issue: http://joshnh.com/2012/10/12/how-does-line-height-actually-work/#comments Any idea why this is happening? I haven't installed any plugins recently, so why has it started playing up all of a sudden?


register_setting - validation callback weirdness

I'm working on a plugin and having some issues validating input on its settings page. I'll try to explain as briefly as possible what I'm doing in the plugin file:               if (is_admin()) {         add_action('admin_init', 'register_mysettings');         add_action('admin_menu', 'my_menu');     }          function t1k_twitter_menu() {         add_options_page('My Plugin Options', 'My Plugin', 'manage_options', 'my_plugin', 'my_plugin_options');     }          function t1k_twitter_options() {         // include my form         include 'my_plugin_options.php';     }          function register_mysettings() { // whitelist options         register_setting('my-group', 'setting_1', array($this, 'validate'));         register_setting('my-group', 'setting_2', array($this, 'validate'));     }          function validate($input) {         // This is where I want to do some validation...     }      From various examples I've seen, it seems that I should be receiving a key- value array as $input in the validate function. What I actually see is a simple string containing the posted value. Have I misunderstood, or is my implementation wrong? The options will save ok (if I remove my validate function, or just set it to return the posted value). Thanks.


Use query->set or make new query?

I'm writing a loop for multi post types with meta_key filters. The filters are inputs from visitors. When visitor click a link(filter), The form submitted and I get the filter. Now, should I just use `$query->set()` to change the query args, or should I submit new query? Currently I'm using this function to get arguments from input and pass the arguments to wp_query:               function get_args($args){     $defaults= array(         // some standard query args        )     $args = wp_parse_args ( $args, $defaults );     extract ( $args );     if(!empty($args['filter'])){        switch ($args['type']){           case 'top_voted':              $args['post_type'] = 'docs';              $args['meta_key'] = '_vote_total';              $args['order'] = 'DESC';              $args['orderby']='meta_value_num';            break;           case 'unanswered_questions':              $args['post_type] = 'topics';              $args['blabla'] = 'blabla;           break;           default:               blabla;            break;     }     return $args;     }      In the template, I use this:               $key = isset( $_POST['filter'] ) ? array_keys($_POST['filter']) : null;     $query_args = get_args(array('user_id'=>$user_id, 'filter'=$key));     $r = new WP_Query( $query_args);      In the above example, I think I'm using new query each time the filter changes. If query->set() or other filters can improve the performance, please help me understand how to do it. Thanks!


Customizing the Widget content markup

I am using bootstrap to create panels for the sidebar widgets, and I can set the container markup for the widget, as well as the markup for the panel header, but I cannot provide the markup for the panel content. I have this so far:               register_sidebar(array(         'name' => __('Right Sidebar'),         'id' => 'home_right_1',         'before_widget' => '
',         'after_widget' => '
',         'before_title' => '

',         'after_title' => '

'     ));      bootstrap panels need to look like this:

Panel heading without title

         Panel content

      How can I add the '
###
' to each widget?


How to query posts based on lat-lng coordinate as post meta?

I'm planning a custom WordPress theme where the Custom Post Type (CPT) will have latitude and longitude coordinate as it's meta value. The latitude and longitude will be displayed as a Marker in a Google Map. So far I don't have any problem in showing the Google Map and the CPT as it's Marker. That is if I query the CPT using the default order. The problem occurs when I need n CPTs that is closest to a coordinate whether it is current user position or a location clicked on the map. Another situation is to query all CPTs that is in x km radius of a coordinate. The question is : How do I query posts based on latitude-longitude value that is saved on the post meta? I'm not really sure how to do it, but I think the latitude and longitude value should be saved in a separate custom field. Thank you in advance.


How to obtain the user ID of the current profile being edited in WP-Admin?

Is there a way of obtaining the user ID of the profile being edited in `wp- admin`? I know it's in the URL if you are editing a user, EX: `./wp-admin/user- edit.php?user_id=427`. Could always `$_GET['user_id']` to retrieve the user's ID, but what about when you're editing your own profile in `wp-admin`? The user ID wouldn't be in the URL. EX `./wp-admin/profile.php` Is there an easy or broad way of retrieving the user ID of the current user profile being edited in `wp-admin`?


How do I add google tracking code to a wordpress.com site?

I want to add google analytics to my free wordpress.com blog. I have the html tracking code but I can't figure out how to add it to my blog from the wordpress.com dashboard.


wp_nav_menu inside an object -- how do I deal with fallback_cb?

I'm trying to create a class that allows me to generate a navigation menu. Here's a simplified version of what I'm using:               class PJ_Menu {         function make_menu() {             $args = array(                 'theme_location' => 'location',                 'fallback_cb' => array( $this, 'pj_page_menu' ),             );             wp_nav_menu( $args );         }         function pj_page_menu() {             // a bunch of code here         }          }     new PJ_Menu();      I can't seem to work out what I need in the `fallback_cb` parameter. `array( $this, 'pj_page_menu' );` didn't work, and neither did `'self::pj_page_menu'`. Am I missing something obvious, or is it not possible to do this?


How can I display a list of categories of my posts

I have a Post Category called 'Podcasts' and under it are many other sub- categories. On a page I have titled "Podcast Categories", I would like to list all categories under the "Podcasts" category, as links to their category page. I'm fairly new to Wordpress, what would be the best way of accomplishing this? Thank you very much! Note: I do not want to display any kind of post content on this page, only the category name as a link. When I do google searching, I'm finding lots of info on how to post content from these categories. UPDATE 1: page-podcast-list.php                         <div id="content">                 <?php                             $cat = get_category_by_slug( 'podcasts' );                   $catid = $cat->ID;                 ?>                 <?php                   wp_list_categories( array(                     'child_of' => $catid;                   ) );                 ?>               </div><!-- /content -->      This isn't doing what I expected. It's printing out: Parse error: syntax error, unexpected ';', expecting ')' in /path/to/page- podcast-list.php on line 49 I'm not sure what line 49 is specifically at the moment, since I'm using the Built in WordPress Editor, without line numbers unfortunately.. I'm not familiar with php for the record, but am familiar with basic programming.


How to get user ID on the registration and add in to custom table

I am trying to get user ID on registration and automatically add that ID to my custom table. I am using wp-members plugin for registration. So is it possible to get user ID on the fly while registering and add that ID to another custom table with WP-Members plugin. Or I can use custom registration page if require. But need some guideline how to get user ID on the fly during registration. **Anyone please help me..**


get_post_meta inside echo

I have a serious problem :) I have this code:               <?php global $wp_query;     $postid = $wp_query->post->ID;     echo get_post_meta($postid, 'provinciadestacada', true); ?>      And i want include here:               <?php if ( in_category( '951' )) { echo 'Online'; }     else     ?>      After else i want get post_meta "provinciadestacada" Maybe something like this?               <?php if ( in_category( '951' )) {     echo 'Online. Todas las provincias'; }     else echo "global $wp_query;     $postid = $wp_query->post->ID;     $meta = get_post_meta($postid, 'provinciadestacada', true);"     ?>


Wordpress Relative Path

I have multisite blog for 2 languages, and I want to easily switch it.               www.example.com/page/post      I would like to switch to               www.example.com/english/page/post      I have **get_blog_option(2, 'siteurl')** which returns `www.example.com/english/` but I cant find any function which returns only `/page/post/` I have one which returns `www.example.com/page/post` but how put there `/english/` inside Thanks


Can I use $wpdb for my custom tables in the WordPress database?

I am building a custom application based on WordPress. I have my custom tables in the WP database. Can I use $wpdb to work with them, or is that class solely for the WP related tables? For example, If I have a database that keeps up with dogs and cats, and I create a custom table named animals (animalid, animal_type, etc.). Do I use $wpdb? I don't know if "interacting with the WordPress database" with $wpdb is intended solely for the stock tables or not. EDIT: I created the tables by hand with MySQL Workbench. They were tables upsized from Microsoft Access. I have not "informed" WordPress of their existence or know if I should.


Preventing Cache for Text Content but not for CSS files and Images

I am front-end developer and my knowledge is limited for server-side. Excuse me if I am mistaken on terminology. I have Wordpress blog that I write blog posts about javascript. I update the same post by generally 12-13 days or so. But sometimes I push updates daily. After I update my article and publish to changes, I go to the article page with Firefox but I see the cached page rather than the updated one. Here is an example post url. http://example.com/?p=1111 This is my response header for the same page if it is first time viewed. ![Response Header](http://i.imgur.com/WgTHxbA.png) After it is viewed first time, if I click in location bar of Firefox and press Return, the page is loaded from cache. Request header is below. Because it is loaded completely from cache it does not have Response Header. ![Request Header](http://i.imgur.com/pUuKIA3.png) It seems clear the Cache-Control might be the main issue but I do only want to prevent page (HTML) cache but not the style and image files. I already have WP-Cache plugin to cache files and I use CDN to serve site images. In this context, I find Firefox useful to load CSS, Javascript and Image files from cache but I do not want Firefox to cache page text context. To get the latest version of my page content, I have to use CTRL + SHIFT + R to force reload the page but this time all CSS, Javascript and image files are also downloaded from server unnecessarily. Is it possible to download page content always from server but load CSS, Javascript and Image file from cache?


using stats_get_csv to return a list of popular posts by views with thumbnails

I recently learned that if you have Wordpress.com Stats installed, you can take advantage of `stats_get_csv()` (Part of the WordPress.com Stats Plugin).               <?php if ( function_exists('stats_get_csv') && $top_posts = stats_get_csv('postviews', 'days=-1&limit=4') ) : ?>
     <?php foreach ( $top_posts as $p ) : ?>
<a href="<?php echo $p['post_permalink']; ?>"><?php echo $p['post_title']; ?>
     <?php endforeach; ?>
     <?php endif; ?>      That's how I have my code set up now. The problem is that it shows pages as well as posts. Also, I want to add the featured thumbnail next to each item as well as an array of custom post types. Is this possible? If so, can someone help me out?


Error "The given object ID is not that of a menu item" on menu with 40+ items

When ever I try to add menu items past about 40 I get an error "The given object ID is not that of a menu item" and many of my menu items will disappear from the menu at random. The site I am working on has approx 65 pages in total but I am unable to get them all in because of this. I am referring to the new WordPress menu management interface


How do I make an HTML table from a database table?

is there a built-in wordpress function to make the HTML or should I use plain- old PHP?


Display custom field values from posts on frontpage

How can I pull a custom field with meta_key "proprty_feature" (and has a value) for all posts and display them on my frontpage? Would like to display the post name as a link above the value..


Having trouble understanding custom post type and taxonomy :/

I am developing a Wordpress site that will have a database of car modifications and an embedded youtube video with the results. For example: search for Honda Civic with a spoiler and exhaust. This would generate several posts. Each post has there own video, attributes, and an adsense ad. I am using the term posts loosely though, I really don't want to post them on the blog of the site. I am struggling to see how (if) this can work with the custom post type and taxonomy features in 3.0. Also I found this $200 theme on WooThemes, I'm not positive it will work and they wont talk to me about technical stuff unless i'm a "member". I would Like to insert youtube videos instead of their dealer listing, but it seems like the theme is a great start.   WooThemes - "Listings"   Thanks for any help and insight, I am at my wits end try to see if this is do- able.


Wordpress menu walker - get the parent item

I want to implement a menu walker system where only those submenu items get listed which have a specific parent. So let's say I have two level one menu items, A and B. On a page I want to get listed the descendant items of menu A only. I want to use the same menu across the site, so creating two different menus for A and B is not an option. What I want to know basically, is there a way to get to know the parent item when the walker is going through the menu, so that I skip certain items based on that information.


How did you incorporate WooCommerce in your own WordPress theme?

This has most probably been asked before, but I really need to show WooCommerce products in my template, but I don't know what hooks to add where. It's my first time working with WooCommerce. Can anybody maybe help me out? Quick step by steps of the process are all I'm asking? And a little more advice would be **greatly** appreciated. Also, just a URL explaining the complete process would be bonus, as I can't find anything on the net at the moment.


Which hook callback has priority if both plugin and theme use the same hook?

If a theme and a plugin uses the same action hook, for example `comment_form` is used by both theme and plugin. Then , which one will be called first? the function associated with the theme's hook or the function associated with the plugin's hook.


Add a class to post if it has been recently updated

I'm trying to add 'updated recently' after the post title. I've discovered some code which works but because of plugins and some theme coding it affects numerous instances of `the_title` that it shouldn't. This issue is covered here https://pippinsplugins.com/use-the_title-and-the_title_attribute- correctly/ \- I've made some corrections / fixes but some plugins are a little beyond my capabilities. The existing code (credit http://www.themesandco.com/snippet/adding-an-update- status-to-posts-in-wordpress/) is...               // add label to updated posts     add_filter('the_title' , 'skips_add_update_status');     function skips_add_update_status($html) {     //First checks if we are in the loop and we are not displaying a page     if ( ! in_the_loop() || is_page() )         return $html;          //Instantiates the different date objects     $created = new DateTime( get_the_date('Y-m-d g:i:s') );     $updated = new DateTime( get_the_modified_date('Y-m-d g:i:s') );     $current = new DateTime( date('Y-m-d g:i:s') );          //Creates the date_diff objects from dates     $created_to_updated = date_diff($created , $updated);     $updated_to_today = date_diff($updated, $current);          //Checks if the post has been updated since its creation     $has_been_updated = ( $created_to_updated -> s > 0 || $created_to_updated -> i > 0 ) ? true : false;          //Checks if the last update is less than n days old. (replace n by your own value)     $has_recent_update = ( $has_been_updated && $updated_to_today -> days < 14 ) ? true : false;          //Adds HTML after the title     $recent_update = $has_recent_update ? 'Recently updated' : '';          //Returns the modified title     return $html.' '.$recent_update;     }      I'd like to adapt this to add an extra class 'update' using `post_class` and then I'll target the post title using CSS and add a pseudo element. My problem is I'm unsure how to adapt the code to insert...               $classes[] = 'update';     return $classes;      Presumably in place of the `//adds html...` onwards section of the existing code. Can anyone assist? This is my starting code but it adds 'update' class to all posts not just those updated in the last 14 days, I guess because there's no link to the logic calculation. If there is a better alternative approach I am open to ideas.               function skips_add_update_status($classes) {          //Instantiates the different date objects     $created = new DateTime( get_the_date('Y-m-d g:i:s') );     $updated = new DateTime( get_the_modified_date('Y-m-d g:i:s') );     $current = new DateTime( date('Y-m-d g:i:s') );          //Creates the date_diff objects from dates     $created_to_updated = date_diff($created , $updated);     $updated_to_today = date_diff($updated, $current);          //Checks if the post has been updated since its creation     $has_been_updated = ( $created_to_updated -> s > 0 || $created_to_updated -> i > 0 ) ? true : false;          //Checks if the last update is less than n days old. (replace n by your own value)     $has_recent_update = ( $has_been_updated && $updated_to_today -> days < 14 ) ? true : false;          //add update class     $classes[] = 'update';          return $classes;     }     add_filter('post_class' , 'skips_add_update_status');


Previous Question - Subdirectory WP install Still not working "correctly"

http://wordpress.stackexchange.com/posts/160035/revisions I had post the above question earlier and received answers.. Thank you!! But its still not working correctly... now it says it can find the page 404 only this time from the hosting service. The main install is on the root directory and the other install is in a subfolder on the root. If it helps for some reason the favicon still shows up.


Advanced video gallery plugin needed

OK doing a website for a client who has a multi-level video gallery. All the video gallery plugins I found (even paid ones) don't function the way we need it to. I thought of rolling my own solution but it would probably take too long. The gallery must:   * Be able to support videos in sub-folders   * Allow users to navigate these sub-folders using a menu system   * Show a player, then below that, show thumbnails of the other videos in the current folder   * Allow the user to search for videos   * Play the next video in the current folder once the current video is done playing (optional) Does such a plug-in exist? If not, I might do my own.


Change path to child of page when uploading image via custom field

Is it possible to change the path of an image when it is uploaded via a custom field so that instead of appearing as _www.mysite.com/wp- content/uploads/2014/05/file.pdf_ it will appear as _www.mysite.com/page- name/file.pdf_ ??


Archive.php is not displaying tags

I have a fairly standard "if" construct to detect what archive.php should display (see below) I also have a custom post type and a custom category. When a user clicks a displayed category (taxonomy) term in my postmeta, it loads archive.php and goes all the way to the "else" case, and displays the matching "Design Pattern" taxonomy term that was clicked. Fine. However, the same is not true for tags. If a user clicks on a Tag in the postmeta, archive.php loads with its "nothing found" displayed, with this URL: `mysite.com/wordpress/tag/action-button/` I would expect the code below to match the "tag" condition and display the tag "action-button".               <?php             if ( is_category() ) :                 single_cat_title();                  elseif ( is_tag() ) :                 echo 'foobar';                 single_tag_title();                  elseif ( is_author() ) :                 /* Queue the first post, that way we know                  * what author we're dealing with (if that is the case).                 */                 the_post();                 printf( __( 'Author: %s', 'upbootwp' ), '' . get_the_author() . '' );                 /* Since we called the_post() above, we need to                  * rewind the loop back to the beginning that way                  * we can run the loop properly, in full.                  */                 rewind_posts();                  elseif ( is_day() ) :                 printf( __( 'Day: %s', 'upbootwp' ), '' . get_the_date() . '' );                  elseif ( is_month() ) :                 printf( __( 'Month: %s', 'upbootwp' ), '' . get_the_date( 'F Y' ) . '' );                  elseif ( is_year() ) :                 printf( __( 'Year: %s', 'upbootwp' ), '' . get_the_date( 'Y' ) . '' );                  elseif ( is_tax( 'post_format', 'post-format-aside' ) ) :                 _e( 'Asides', 'upbootwp' );                  elseif ( is_tax( 'post_format', 'post-format-image' ) ) :                 _e( 'Images', 'upbootwp');                  elseif ( is_tax( 'post_format', 'post-format-video' ) ) :                 _e( 'Videos', 'upbootwp' );                  elseif ( is_tax( 'post_format', 'post-format-quote' ) ) :                 _e( 'Quotes', 'upbootwp' );                  elseif ( is_tax( 'post_format', 'post-format-link' ) ) :                 _e( 'Links', 'upbootwp' );                  else :                 _e( 'Design Patterns', 'upbootwp' );                  endif;         ?>


Drag and Drop Metadata Menu Order

I'm not sure this has been answered previously.. I have a frontend form where the user fills out a form that has dynamic fields where they can add more fields if they choose to. The jquery names the input fields as follows data[0] data[1] data[2] data[3] etc.. depending on how many fields the user wants. When the form is submitted, all the data goes into one record as metadata. Is there a way to have the user be able to reorder the metadata with a drag and drop functionality? And save the metadata order?


Calling apply_filters on non-documented hooks

I have been trying to learn how to write plugins and I thought the best way would be to look at other plugins. I was taking a look at this one and the first lines               /**      * Plugin Name: Media Library Categories      * Plugin URI: http://wordpress.org/plugins/wp-media-library-categories/      * Description: Adds the ability to use categories in the media library.      * Version: 1.4.1      * Author: Jeffrey-WP      * Author URI: http://codecanyon.net/user/jeffrey-wp/?ref=jeffrey-wp      */          /** register taxonomy for attachments */     function wpmediacategory_init() {         // Default taxonomy         $taxonomy = 'category';         // Add filter to change the default taxonomy         $taxonomy = apply_filters( 'wpmediacategory_taxonomy', $taxonomy );         register_taxonomy_for_object_type( $taxonomy, 'attachment' );     }     add_action( 'init', 'wpmediacategory_init' );      There is this line:               $taxonomy = apply_filters( 'wpmediacategory_taxonomy', $taxonomy       that I don't understand. I have look around the Wordpress documentation and I didnt find a hook called `wpmediacategory_taxonomy`. Besides due to the name, I am sure that is something related to the plugin. So how does it exactly work? Is that a custom hook? Where was it defined?


My Dashboard<< Appearance << Menu page won't open

![enter image description here](http://i.stack.imgur.com/IGRJL.png) When ever i try to open wp_nav_menu.php this fatal error thingy appears. Please help :(


CSS class on last post in loop ( custom query )

I have been using this question to try to do this but I am having some difficutlty. I have a custom post type, media, and I am working on the archive-media.php template. I have it partially working in that when I delete the **if** condition out of the code it does add the class, but of course to every post. I have determined that `$wp_query->current_post` is not returning a value, so I feel I must not be using this right. I have the code in my functions.php file. The codex says that current_post is available in the loop, so I am a bit confused.               add_filter('post_class', 'my_post_class');     function my_post_class($classes){       global $wp_query;       if(($wp_query->current_post+1) == $wp_query->post_count) $classes[] = 'last';       return $classes;     }


Redirect all page templates to index.php and turning Wordpress into a Single Page Application CMS

I’m trying to push the boundaries of Wordpress by turning it into a SPA CMS. Everything works fine until now except for a redirection issue. github angularpresstheme **How it works:** When I create a page and publish it (or update) wordpress will generate an Angularjs html view template. All pages are redirected to the index.php (hence the name SPA) where there is a directive that handles all view states. I use HTTP_API to do it. **Issue:** If you go for the first time ( _the second time is loaded using php_ .You may need to clear your browser session) to http://angularpresstheme.com/full- width/ you will see that the page briefly appears and then reloads ( this doesn’t happen if you just go to ‘/’). I use JavaScript (Angularjs) to redirect the page. The main problem with this approach is that it is pretty slow and the pages flickers. This happens because it was the only way I could find to avoid the following:   * Whenever I tried to create a page and published it the resulting Angularjs html template was always based on index.php template! This occurred because I simply had redirected all pages to index.php (using .htaccess or php) . **What I did to mitigate the problem:**   * I solved part of the problem by redirecting the “/” (front-page) and the other pages (when loaded for the second time) using PHP.   * When pages _other than the front-page_ (“/” ) are loaded for the first time I had to use Javascript in order to avoid the “index.php” only template generation effect. **What I would like to do:** On click publish or update it must ignore that we are redirecting all pages to index.php (using .htaccess or PHP) and just keep the normal wordpress template system flow. For example: I could create a page with slug called home and use a front-page.php template and then it should generate a Page called Home based on the front-page template (as Wordpress normally does) . **To Resume:**   * I would like to redirect all pages to index.php using .htaccess (even better) or PHP   * And when creating or editing a new page Wordpress should work just as normal for the front-end and back-end **Possible ways to solve it:**   * Use Wordpress rewrite rules with template_redirect   * Another way to generate html template other than HTTP_API or OB_START. Could someone help me out with this, please? II would be very nice! **Code:**                       /**              * When page (frontpage '/') loads or reloads then set a template_req session              * at the template_redirect hook time (just before template_include).              * After that redirect to index.php with redirect_all_pages_to_index_template() using              * 'template_include' hook.              *              * */             function angp_set_index_for_redirect() {                      if (!is_front_page()) return;                      angp_set_session('index.php', 'template_req');                  }                  add_action('template_redirect', 'angp_set_index_for_redirect', 10);                       /**              * When pages (other then the frontpage) loads the first time  then set a              * template_req_pages session at the wp_head(for page preview) and get_header(for frontend) hook time.              * But redirection will just happens after page is reloaded from the second time onwards with              * redirect_other_pages_to_index_template() using 'template_include' hook.              *              * */             function angp_set_index_for_pages_redirect() {                      if (is_front_page()) return;                 angp_set_session('index.php', 'template_req_pages');                  }             add_action('wp_head', 'angp_set_index_for_pages_redirect');             add_action('get_header', 'angp_set_index_for_pages_redirect', 10);                      /**                  * when  '/' is reloaded (for the first time or not)                  * check if there is a  session key 'template_req'(that is set at template_redirect hook time                  * in angp_set_index_for_redirect()) and if yes redirect to  index.php                  *                  * */                 function redirect_all_pages_to_index_template($template) {                     global $pagenow;                          if (('template_include' == current_filter()) && $pagenow                         == 'index.php'                     ) {                              $key = 'template_req';                         if (isset($_SESSION[$key])) {                                  $array = $_SESSION[$key];                             $req_url = $array['url'];                                  $new_template = locate_template($req_url);                                  if ('' != $new_template) {                                      return $new_template;                                  }                         }                     }                          return $template;                 }                      add_filter('template_include', 'redirect_all_pages_to_index_template', 10, 1);                           /**                  * when a page other then '/' is reloaded (for the first time or not)                  * check if there is a  session key 'template_req_pages' and , if yes redirect to index.php                  * The session 'template_req_pages' is set in set-index-redirect.php with get_header and wp_head                  * hooks                  * */                 function redirect_other_pages_to_index_template($template) {                     global $pagenow;                          if (('template_include' == current_filter()) && $pagenow                         == 'index.php'                     ) {                              $key = 'template_req_pages';                         if (isset($_SESSION[$key])) {                                  $array = $_SESSION[$key];                             $req_url = $array['url'];                                  $new_template = locate_template($req_url);                                  if ('' != $new_template) {                                      return $new_template;                                  }                         }                     }                          return $template;                 }                      add_filter('template_include', 'redirect_other_pages_to_index_template', 20, 1);                      /**                  * This tells the browser at the init hook phase that we are loading a page for the first time                  * ever. It works for pages other then '/'. Redirection will be done by angularjs in app.js                  * MainCtrl                  *                  * */                 function angp_is_page_first_loaded() {                     if (!isset($_SESSION['template_req_onload'])) {                         angp_set_session('template_req_onload', 'template_req_onload');                          }                 }                      add_action('init', 'angp_is_page_first_loaded', 10);                      /**                  * This tells the browser at the get_header hook phase to delete 'template_req_onload' after the                  * page is fully loaded, so that dont get into a redirection loop. It checks if $_COOKIE['is_page_loaded']                  * or $_SESSION['page_loaded'] were already set. *                  *                  * */                 function destroy_session_index_onload() {                     //cookie set in app.js                     if (isset($_COOKIE['is_page_loaded']) || isset($_SESSION['page_loaded'])) {                         unset($_SESSION['template_req_onload']);                          }                 }                      add_action('get_header', 'destroy_session_index_onload', 20);                      /**                  * Set session page_loaded when page is fully loaded                  * $_COOKIE['is_page_loaded'] does the same for google chrome canary                  *                  * */                      function angp_page_fully_loaded() {                     angp_set_session('page_loaded', 'page_loaded');                 }                 add_action('wp_footer', 'angp_page_fully_loaded');                 add_action('get_footer', 'angp_page_fully_loaded', 20);                      /**                  * This code generates the angularjs html views templates                  * It uses HTTP-API with  wp_remote_get()                  * */                 function angp_get_template_content($new_status, $old_status) {                     global $post;                          if (isset($post->post_name)) {                         $post_slug = $post->post_name;                              $file = get_template_directory() . '/library/views/pages/' . $post_slug . '.html';                              if (($old_status != 'trash' && $new_status == 'trash')) {                             if (file_exists($file))                                 unlink($file);                         }                     }                     if (($old_status != 'publish' && $new_status == 'publish') || did_action('wp_insert_post') === 1) {                                   angp_get_page_http_api(site_url(), 'newsloop');                         $pages = get_pages(array('sort_order' => 'asc'));                              if (!empty($pages))                                  foreach ($pages as $page) {                                      $slug = $page->post_name;                                 $url = get_page_link($page->ID);                                      angp_set_session('index.php', 'template_req');                                 angp_get_page_http_api($url, $slug);                                  }                     }                 }                                if ($_SERVER['REQUEST_URI'] == '/wp-admin/nav-menus.php'                     || (isset($_POST['action']) && $_POST['action'] == 'add-menu-item')                     || (@$_POST['post_type'] == 'post')                 ) return;                           add_action('quick_edit_custom_box', 'angp_get_template_content', 10,2);                 add_action('wp_insert_post', 'angp_get_template_content', 20, 2);                 add_action('transition_post_status', 'angp_get_template_content', 20, 2);                 add_action('wp_restore_post_revision', 'angp_get_template_content', 10, 2);                      if (!function_exists('angp_get_page_http_api')) {                     function angp_get_page_http_api($url, $slug) {                 /*                  * request a page extract content between tags <content></content> or <homenewsloop></homenewsloop>                  * */                         $response = wp_remote_get($url);                              if (is_wp_error($response) || (200 != wp_remote_retrieve_response_code($response))) {                             wp_die('Request could not be executed.');                              }                              try {                             $result = wp_remote_retrieve_body($response);                             //extract content and pass it to a html template_generator                             if ($url !== site_url()) {                                 preg_match_all('/<content[^>]*>(.*?)<\/content>/is', $result, $t);                                      angp_wp_to_angular_template_generator($slug, $t[1][0]);                                  } else {                                 preg_match_all('/<homenewsloop[^>]*>(.*?)<\/homenewsloop>/is', $result, $t);                                 angp_wp_to_angular_template_generator($slug, $t[1][0]);                                  }                              } catch (Exception $ex) {                             return $ex;                              }                          }                      }                      if (!function_exists('wp_to_angular_template_generator')) {                     function angp_wp_to_angular_template_generator($slug, $body_response) {                         if ($slug === 'newsloop') {                             $file = get_template_directory() . '/library/views/loops/' . $slug . '.html';                         } else {                             $file = get_template_directory() . '/library/views/pages/' . $slug . '.html';                         }                              if (!empty($body_response)) {                                  try {                                 global $checkfile;                                      if(file_exists($file)){                                     $checkfile = file_get_contents($file);                                      }                                 //just write content if file content is empty or content is different than the                                 //$body_response                                 if ($body_response !== $checkfile || $checkfile === '' || !isset($checkfile)) {                                          file_put_contents($file, $body_response, LOCK_EX);                                          return false;                                 }                                  } catch (Exception $ex) {                                      return 'Could not write file!';                             }                         }                     }                 }                      if (!function_exists('angp_set_session')) {                          function angp_set_session($key_name, $template_req_name) {                              $template_req = $key_name;                         $key = $template_req_name;                         $_SESSION[$key]['url'] = $template_req;                          }                 }


Custom Meta Box - Multiple Checkbox for Users

My question is in regard to this article: http://wp.smashingmagazine.com/2012/01/27/limiting-visibility-posts- username/comment-page-1/#comment-154111 This article:   1. creates a custom metabox    2. the custom metabox queries 'subscriber' users    3. saves the metabox value as a radio button What I would like to know is if anyone knows how:   1. change the metabox to multiple checkboxes (pretty straightforward)    2. save the multiple checkbox values in one field, separated by commas (i.e. an array). The code: (in functions.php)               /* Fire our meta box setup function on the post editor screen. */     add_action( 'load-post.php', 'smashing_post_meta_boxes_setup' );     add_action( 'load-post-new.php', 'smashing_post_meta_boxes_setup' );          /* Meta box setup function. */     function smashing_post_meta_boxes_setup() {              /* Add meta boxes on the 'add_meta_boxes' hook. */         add_action( 'add_meta_boxes', 'smashing_add_post_meta_boxes' );              /* Save post meta on the 'save_post' hook. */         add_action( 'save_post', 'smashing_flautist_access_save_meta', 10, 2 );     }          /* Create one or more meta boxes to be displayed on the post editor screen. */     function smashing_add_post_meta_boxes() {              add_meta_box(             'smashing-flautist-access',         // Unique ID             esc_html__( 'Post Viewing Permission', 'smashing_flautist' ),       // Title             'smashing_flautist_access_meta_box',        // Callback function             'destinations',                 // Admin page (or post type)             'normal',                   // Context             'default'                   // Priority         );     }          /* Display the post meta box. */     function smashing_flautist_access_meta_box( $object, $box ) { ?>              <?php wp_nonce_field( basename( __FILE__ ), 'smashing_flautist_access_nonce' ); ?>

     Username	         	     Visiblity	         	     Name
     <?php     global $post;         $users = get_users('role=subscriber');         foreach ($users as $user) {                 $user_info = get_userdata( $user->ID );                 if(get_post_meta( $object->ID, 'smashing_flautist_access', true ) == $user->user_login) $ifchecked = 'checked="checked" ';                 echo "
";                 echo "$user->user_login	    	";                 echo "<input type=\"checkbox\" name=\"smashing-flautist-access\" id=\"smashing-flautist-access\" value=\"$user->user_login\" " . $ifchecked ."/>	  	";                 echo "$user_info->last_name, $user_info->first_name	    	";                 echo "
";                 unset($ifchecked);              } ?>
               <?php }          /* Save post meta on the 'save_post' hook. */     add_action( 'save_post', 'smashing_flautist_access_save_meta', 10, 2 );          /* Save the meta box's post metadata. */     function smashing_flautist_access_save_meta( $post_id, $post ) {              /* Make all $wpdb references within this function refer to this variable */         global $wpdb;              /* Verify the nonce before proceeding. */         if ( !isset( $_POST['smashing_flautist_access_nonce'] ) || !wp_verify_nonce( $_POST['smashing_flautist_access_nonce'], basename( __FILE__ ) ) )             return $post_id;              /* Get the post type object. */         $post_type = get_post_type_object( $post->post_type );              /* Check if the current user has permission to edit the post. */         if ( !current_user_can( $post_type->cap->edit_post, $post_id ) )             return $post_id;              /* Get the posted data and sanitize it for use as an HTML class. */         $new_meta_value = ( isset( $_POST['smashing-flautist-access'] ) ? sanitize_html_class( $_POST['smashing-flautist-access'] ) : '' );              /* Get the meta key. */         $meta_key = 'smashing_flautist_access';              /* Get the meta value of the custom field key. */         $meta_value = get_post_meta( $post_id, $meta_key, true );              /* If a new meta value was added and there was no previous value, add it. */         if ( $new_meta_value && '' == $meta_value )             {             add_post_meta( $post_id, $meta_key, $new_meta_value, true );             $wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'private' WHERE ID = ".$post_id." AND post_type ='post'"));             }         /* If the new meta value does not match the old value, update it. */         elseif ( $new_meta_value && $new_meta_value != $meta_value )             {             update_post_meta( $post_id, $meta_key, $new_meta_value );             $wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'private' WHERE ID = ".$post_id." AND post_type ='post'"));             }         /* If there is no new meta value but an old value exists, delete it. */         elseif ( '' == $new_meta_value && $meta_value )             {             delete_post_meta( $post_id, $meta_key, $meta_value );             $wpdb->query($wpdb->prepare("UPDATE $wpdb->posts SET post_status = 'public' WHERE ID = ".$post_id." AND post_type ='post'"));             }     }