What is the correct way for plugins to create tables with special charset/collation considerations?

I'm using WordPress >=3.8. The default charset/collation values in wp- config.php are               define('DB_CHARSET', 'utf8');     define('DB_COLLATE', ''); // Becomes utf8_general_ci      I am in a situation where `utf8_general_ci` would be _adequate_ , but something more specific (`utf8_danish_ci`) will always be able to describe my data better. It is also the case that the data, which is fetched from an external source, will always be UTF-8. I am developing a plugin that creates some table               CREATE TABLE plugin_table(         some_id INT NOT NULL,         some_data VARCHAR(100) NOT NULL,         PRIMARY KEY  (some_id)     ) ENGINE=InnoDB;      What is the correct way to handle charset and/or collation? One solution is to use the above statement, falling back on global configuration. As mentioned, this will work in my situation, and from a developer perspective I think it is reasonable to require that either `utf8` or `utf8mb4` is specified. The other solution is to explicitly set the charset/collation settings:               ...) ENGINE=InnoDB [DEFAULT CHARSET=utf8] [COLLATE utf8_danish_ci];      This will allow me to configure the table in the most appropriate way for the data I need to store, and in testing I have confirmed that the letter `Å`, which is treated differently by `utf8_general_ci` and `utf8_danish_ci`, is compared correctly. This _appears_ to work, but I don't know if it is good or bad practice, and, in particular, I don't know if this could cause complications elsewhere (e.g. should I be changing settings when querying the table?). This question has several cousins but this doesn't seem to be a duplicate. The answer that comes closest also mentions the explicit method above, with a comment that it may be more appropriate to use the default values "so the user can override them if they have good reason". If I were going to go out of my way to use the core configuration, then it seems silly to specify these settings in the first place. It is important to understand that there will never be a "good reason" to use non-UTF-8. With respect to collation, the question is less clear. The question boils down to the following: given some non-UTF-8 core configuration, which would be considered unsupported, should I take steps to make my plugin behave correctly?


Sort custom-posts in archive.php via meta-key?

this question is strongly related to this question where I already got a working answer. I have a custom-post-template named "wr_event" and a custom-taxonomy named "event_type". This "event-posts" have a meta-box where I set the event date and I use this …               function change_order_for_events( $query ) {         //only show future events and events in the last 24hours         $yesterday = time() - 24*60*60;               if ( $query->is_main_query() && is_tax('event_type') ) {             $query->set( 'meta_key', '_wr_event_date' );             $query->set( 'orderby', 'meta_value_num' );             $query->set( 'order', 'ASC' );             $query->set( 'meta_value', $yesterday );             $query->set( 'meta_compare', '>' );         }          }          add_action( 'pre_get_posts', 'change_order_for_events' );      … to sort all "event-posts" via its event-date. This works just fine and does exactly what I want. Only thing that doesn't work so far is the "archive.php" where I want the same to take effect. I added `'has_archive' => 'events'` to my custom-post-template. `/events` displays now my "archive.php" file where I already use `is_post_type_archive('wr_event')` for my headline. However I want my archived events also to be in its right date-order. So the same function above `change_order-for_events()` should work on my "archive.php" template. Of course in this case the function should show just old events that have already taken place. Any idea how I could do that? **update:** I'm storing the timestamp with the MetaBox and CustomFields Class               $meta_boxes[] = array(         'id'         => 'event_date',         'title'      => 'Event Date',         'pages'      => array( 'wr_event', ),         'context'    => 'normal',         'priority'   => 'high',         'fields'     => array(             array(                 'name' => 'Event Date Picker',                 'desc' => 'The date the event takes place',                 'id'   => $prefix . 'event_date',                 'type' => 'text_date_timestamp',             )         ),     );      I query it in my template files with               $wr_event_fields = get_post_custom();     $wr_event_fields['_wr_event_date'][0];


Integrate Bugzilla into WordPress

I am working on WordPress and Bugzilla. Now I want to integrate the Bugzilla into WordPress. That is, I am getting comments in Bugzilla and I want to show them in WordPress also. How do I integrate the Bugzilla into WordPress?


WordPress set custom field to true, sets all others to false?

So, if I'm publishing a post, and set a value for this posts custom field, can I set the custom field value of all other posts to false? * * * Well that's good to hear that it is possible, but maybe there is a better way to achieve my goal: I'm fairly new to WordPress, and the WordPress stack exchange site so I apologize if I'm not putting out all the required info. I have a "Designer" custom post type for creating profiles of designers, and I would like to have the option for "Featuring" 1 particular designer and un- featuring the previously "Featured" designer. I am using "Custompress" plugin for post types, taxonomies, and custom field, currently. Thoughts on how I might achieve this are all very welcome! * * * I like the sounds of mfields suggestion, but I have yet to discover what a "custom setting" is. Would you mind elaborating or pointing me in the right direction?


Add a page that appears in the backend admin that lists files to download? WP 3.3

I am currently using WP 3.3.1. Basically I just want a page for users who login via wp-login.php and see the backend admin panel to be able to see a page that shows a list of files they can download.   1. The files will either be .zip, .pdf, or .txt.    2. Would be awesome if the list of downloads had the same exact format as when you view Posts>> All Posts.    3. To get things started, it doesn't need a sort or filter functionality. Although one would be nice. Not exactly sure how I will upload the files. But whatever route would make the above easiest is the okay with me. Any tips or code snippets that will either do the above or get me started in the right direction would be awesome! Thank you in advance.


will post_id ever change? Can I safely use post_id for custom queries?

What are the best practices for using post_id? Can I use this safely in my templates to call specific posts, or will these post_id's ever change? The reason I ask is that randomly today the post_id's changed on my site, and I'm wondering what could have caused it. It didn't mess up any of the permalinks (thankfully!) but I did have to go switch some custom queries which were calling content specifically by the post_id (specifically in some custom_post_types I've created) So... should I use a different query to get a specific post? The query I'm using looks like this.               <?php query_posts('post_type=home_feature&p=36')?>      Just earlier today, post_id for this post was 139 and my query was:               <?php query_posts('post_type=home_feature&p=139')?>      Obviously, when the post_id changed, my query (and subsequently the custom home feature) broke. I'm just not sure what could have caused this change.. and if that means I shouldn't be using the post_id in custom queries.. Thoughts?


Clean database from unused tables

I used to have many plugins installed on one of my sites, and after deleting most of them, I still have a database full of extra tables, I am sure most of them are unused. How do I clean them off?


Image dimensions same as image size

So if I set the large image size in the media library to say 600x600 pixels, and then upload an image which is the same dimensions it won't get set as the 'large' image. There is talk on this question about it being the ratio, but I don't think this is the case. Also I don't want to setup another custom image size as its will just bloat the server with redundant images, when 'large' should work! Is there a filter or setting where I can change the logic of the images, so if the dimension is larger than , OR equal to the media library setting it gets set as the large image. At the moment the equal to seems to be missing. Thanks


Automatically determine minimum WordPress version required for a plugin?

When developing a plugin, is there a way to automatically determine the minimum version of WordPress that's required to run it? I want to make sure that the `Requires` header is accurate, but manually checking every time I call a new core function is tedious and error-prone. I'm thinking a script could figure it out easily enough:   1. Scan all the files in a plugin.   2. Parse out all the class instantiations and function calls based on the `new foo( [...] )`, `foo::bar( [...] )`, `bar( [...] )`, `call_user_func( [...] )`, etc syntax.   3. Parse the WP source to determine when each of those classes/functions were added to WordPress, using the `@since` phpDoc tag.   4. Generate a report listing each class/function and the version it was added, along with the earliest version of WordPress that includes all of the classes/functions. I've looked around but couldn't find anything like it, and don't have the time to write it myself. Does anyone know of an existing solution?


Wordpress WP_Query() Not working properly

We would like to know that how we occur error when we implement this code in our sidebar.php               $categories = get_categories();      foreach($categories as $category)      {        printf('
%s

', $category->cat_name);       $posts = new WP_Query('cat='.$category->cat_ID);       while($posts->have_posts())       {              $posts->the_post();         echo '
', the_title(), '
';        }          print '
';       }      The error we are getting: > Fatal error: Cannot use object of type WP_Query as array in > C:\xampp\htdocs\wordpress\wp-includes\query.php on line 2374


Wordpress Contact Form 7

I have a simple contact form using CONTACT FORM 7 PLUGIN on a page on my site. I want user to be able to download a video file only after he/she fills out the form and the form submission is successful. How do i check whether the form is successfully submitted so that I can then put in the code for force download of the file?


Implementing an image hosting website using WordPress?

I am exploring the idea of implementing a (vertical) **image hosting service** on a self-hosted WordPress platform. I have found several php scripts that can be used for a basic image hosting service and I am trying out one of them - but WordPress is such a great platform, and I am more familiar with it, so I would prefer to use WP if possible. I have found some relevant plugins for WP (Cincopa, BuddyPress etc.), but when I look at their details, they don't look like they would deliver what they promise. How could I go about it?   What plugins could I perhaps combine to do this?   Do I need to use BuddyPress? I would like users to be able to post photos, arrange them in galleries/albums, comment/tag them, complete other custom fields relating to the photos - and, **CRUCIALLY** , be able to **_mark them as public, private or friend._** More advanced membership handling (including membership levels and payment options) would be desirable. I know there are several membership plugins that I could hopefully bring it or customize. Many thanks for any advice.


How can I automatically add child pages to pages in a WP menu?

In the WP menu creation GUI there's the `Automatically add top level pages` option. I would like to do the opposite, for any page that is in the menu, automatically add it's child pages. Is there a way to do that ?


Media Editor uppercase extensions to lowercase

What's the reason for making the extensions on uploaded images lowercase as soon as the upload is complete?


Display recent posts on front page

I am new to theme development in wordpress i am working on a theme, i have a front page on which i want to display only the most recent 4 posts of any category to be displayed my code for this is               <?php $the_query = new WP_Query( ‘showposts=4′ ); ?>             <?php while ($the_query -> have_posts()) : $the_query -> the_post(); ?>
             <a href=”<?php the_permalink() ?>”><img src="<?php bloginfo('template_directory'); ?>/img/post-images/Adithi_Dinner_blog.jpg" class="border" alt="image" />
<?php the_title(); ?>

<?php echo substr(strip_tags($post->post_content), 0, 100);?>

             <?php endwhile;?>      but it gives me error that unexpected "=", if i remove 4 from the showposts=4 than it shows all the posts on that page, kindly help me how i fix it, thanks


Sorting meta box values by start- and enddate and all dates in between

What I've been attempting to write is a function that will allow me to sort a list of WordPress posts by their meta values start date, end date and all dates in between. I've set up a custom metabox with three fields:   * Name of the event (ID `evenement-name`)   * Start date of event (ID `evenement-datum-start`), stored as YY-mm-dd   * End date of the event (ID `evenement-datum-end`), stored as YY-mm-dd What I'd like to have is a list of events that would take place in the future, grouped by year, month and day. Example:   * Event A takes place from 2013/11/24 till 2013/11/26   * Event B takes place on 2013/11/25 Example result: > 2013 > >> November >> >>> 24 >>> >>>> Event A >>> >>> 25 >>> >>>> Event A >>>> >>>> Event B >>> >>> 26 >>> >>>> Event A Unfortunately, that all sounds so much easier in theory. I did manage to get the metaboxes working and run query to return a list of posts of which the meta value `evenement-datum-end` is today or in the future. I even managed to get a list of all dates between `evenement-datum-start` and `evenement-datum-end`, so what I now have is this: > 2013/11/24 - Event A > > 2013/11/25 - Event A > > 2013/11/26 - Event A > > 2013/11/25 - Event B My code:               //This is the function I use to get all the dates between the start date and the end date:     function getDateRange($startDate, $endDate, $format="Y-m-d"){         //Create output variable         $datesArray = array();         //Calculate number of days in the range         $total_days = round(abs(strtotime($endDate) - strtotime($startDate)) / 86400, 0) + 1;              //Populate array of weekdays and counts         for($day=0; $day<$total_days; $day++)         {             $datesArray[] = date($format, strtotime("{$startDate} + {$day} days"));         }         //Return results array: de inhoud van de array wordt uitgelezen          return $datesArray;     }               //Query     $args = array (          'cat'               => '1,6',         'post_type'         => 'post',          'meta_key'          => 'evenement-datum-start',         'posts_per_page'    => -1,         'meta_query'        => array(             array(                 'key'       => 'evenement-datum-end',                 'value'     => date('Y-m-d'),                 'compare'   => '>=',                 'type'      => 'DATE'             )         ),      );          $agenda_query_full = new WP_Query ( $args );               if ( $agenda_query_full->have_posts() ) {     echo '
';              while ( $agenda_query_full->have_posts() ) {             $agenda_query_full->the_post();                  $meta_event_name    = get_post_meta( get_the_ID(), 'evenement-name', true );             $meta_event_start   = get_post_meta( get_the_ID(), 'evenement-datum-start', true );             $meta_event_end     = get_post_meta( get_the_ID(), 'evenement-datum-end', true );             $dateRange      = getDateRange($meta_event_start, $meta_event_end);                   asort($dateRange);             $today              = date('Y-m-d');                  foreach ($dateRange as $key => $val) {                 $datum      = date("d-m-Y", strtotime($val));                         if($val>=$today) {                          if(in_category( 'acties' ) ){                         echo '
'.$datum.' - ' . $meta_event_name . '
';                     }                     else {                         echo '
'.$datum.' - ' . $meta_event_name . '
';                     };                 };             }         }         echo '
';     } else {         echo 'No events found.';     }          wp_reset_postdata();      As I understand it, and I'm only a beginner at PHP, is that I can't query for a list of dates before I run the loop. But when I do run the loop, I can't get the dates to be sorted chronologically, because I've already retrieved a single post. Impasse reached. I've been working on this for several days now and getting desperate... Any help?


Compare "Main" post ID to ID inside wp_query loop

I have a video viewing section on my site. The single post template displays a large area where the video plays and then there's a column of thumbnails representing other videos along the right side. Much like YouTube. If the current video that is being displayed (let's say the post ID is 123) matches one of the thumbnail on the right (also ID 123) I want to give the thumbnail a different css class (represented by the inline style below) so I can highlight it, letting the user know this is the video currently playing. I'm using wp_query to grab the posts for the right sidebar portion and I can't figure out how to compare the two IDs while in the loop. Below is a simplified version of what I thought would work, but it just gives the class to all iterations of the loop instead of just the current one.               <?php while ( have_posts() ) : the_post();      $primaryid = get_the_ID(); ?>     <?php                  $args = array (                     'post_type' => 'post',                     'post_status' => 'publish',                     'orderby' => 'meta_value_number',                     'meta_key' => 'episode',                     'order' => 'ASC',                     );                 // The Query                 $query = new WP_Query( $args );                      // The Loop                 if ( $query->have_posts() ) { ?>                          <?php while ( $query->have_posts() ) {                         $query->the_post(); ?>                         <?php if (get_the_ID() == $primaryid) {                             $style = 'style="border: 1px solid #fff;"';                             } ?>     <?php endwhile; // end of the loop. ?>


How to disable "Audio Player" to show up on the main page

I have a post with audio player with autostart enabled, and i decided to put it in the beginning of the post, before putting "read more" excerpt feature. So the problem is, that audio player plays music on the main page, but i want it to work only on post page. Is it possible to do? I've put my post in drafts for now, until i solve this little problem...


unapprove comments on custom post type

I have registered a custom post type and I want to unapprove comments by default on this custom post type without affecting the default posts/pages which is set to approve. I've looked through the CODEX but I can not find anything related to what I'm trying to do. I've found just how can I display the un-approved comments. Code for registering custom post type:               // Register Custom Post Type          function debate_post_type() {                    $labels = array(         'name'                => _x( 'Debates', 'Post Type General Name', 'text_domain' ),         'singular_name'       => _x( 'Debate', 'Post Type Singular Name', 'text_domain' ),         'menu_name'           => __( 'Debate', 'text_domain' ),         'parent_item_colon'   => __( 'Parent Debate:', 'text_domain' ),         'all_items'           => __( 'All Debates', 'text_domain' ),         'view_item'           => __( 'View Debate', 'text_domain' ),         'add_new_item'        => __( 'Add New Debate', 'text_domain' ),         'add_new'             => __( 'New Debate', 'text_domain' ),         'edit_item'           => __( 'Edit Debate', 'text_domain' ),         'update_item'         => __( 'Update Debate', 'text_domain' ),         'search_items'        => __( 'Search debates', 'text_domain' ),         'not_found'           => __( 'No debates found', 'text_domain' ),         'not_found_in_trash'  => __( 'No debates found in Trash', 'text_domain' ),     );     $args = array(         'label'               => __( 'debate', 'text_domain' ),         'description'         => __( 'Here you can post your debates', 'text_domain' ),         'labels'              => $labels,         'supports'            => array( 'title', 'editor', 'excerpt', 'thumbnail', 'comments', 'custom-fields', 'page-attributes', 'post-formats', ),         'taxonomies'          => array( 'category', 'post_tag' ),         'hierarchical'        => true,         'public'              => true,         'show_ui'             => true,         'show_in_menu'        => true,         'show_in_nav_menus'   => true,         'show_in_admin_bar'   => true,         'menu_position'       => 5,         'menu_icon'           => '',         'can_export'          => true,         'has_archive'         => true,         'exclude_from_search' => false,         'publicly_queryable'  => true,         'capability_type'     => 'page',     );     register_post_type( 'debate', $args );     }     // Hook into the 'init' action     add_action( 'init', 'debate_post_type', 0 );      Any suggestions on how can I do this ? Thanks!


How to create a posts archive page showing only the date and the post title

I have the following question about how to create an archive page on my website. As you can see opening this link: http://lnx.asper-eritrea.com/ Under the header slideshow I have 3 boxes, the second one (names **Archivio** ) have to be linked to a page that show a list of all published posts (belonging to all the categories). My problem is: how can I create this page? If I go in the **administration panel ---> Appreance ---> Menus** I see that I can create a voice that open a page showing the posts belonging to a specific category (but not to all categories). What can I do to create an archive page that show all my posts (as in the homepage, but then I will set a different content visualization using an unordered list and showing only the posts title)? Can I create a static page and insert into it the posts loop? What is the best way to do it? Tnx


next gen gallery thumbnail problem

Does anyone know why nextgen gallery doesn't support thumbnails with png transparency??? I'm working on this project http://decolabel.andresmijares.com/smaakvolle- etiketten/ And as you can see the slideshow work the image properly, however the thumbnails have a black background. I'd really appreciated any kind of help :)!


body_class hook for admin pages

The body_class hook seem only to work with non-admin pages. When I do               add_filter('body_class', 'add_body_classes');     function add_body_classes($classes) {             $classes[] = 'myclass';             return $classes;     }      Is there another hook i should be using if i want to add a class to the body of an admin page?


Using catch_the_image to get the thumbnail size

I use front end posting on my site so I don't get a chance to set a featured image for alot of my posts. So I use catch_the_image to get thumbs but it gets the original size and then scales it which is hurting page speed. Basically what I want to do is add "-150x150" into the string in the function so it pulls the smallest size of the 3 it stores in the uploads folder. So instead of picture.png it returns picture-150x150.png. Any idea how to add that to this function?               function catch_that_image() {      global $post, $posts;      $first_img = '';      ob_start();      ob_end_clean();      $output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);      $first_img = $matches [1] [0];           return $first_img;     }


the_author_posts_link() for authors of custom post types

I have both regular blog posts and a custom post type in a blog. The page template shows the author posts link. If you click on that link for an author that has authored some posts, that page (blog/authors/mr-author) shows the expected bio information and a list of the author's posts. However, if you create a user that is an author, but who has only authored the custom post type, and no regular posts, the link generated by the_author_posts_link() (which is still the correct link: blog/authors/mr- author) shows an unpopulated page (ie: the fields are all empty, and the posts listing is the full list of all posts for all authors). Clearly, we're not getting the right data inside the $authordata global. But why? `author.php` is using standard template tags like `get_the_author_meta('display_name')` to display author information, but this is all showing blank results for an author that has no posts. I'm currently digging through core to figure out where and when $authordata gets populated to see if it's linked to a specific post type being present, but so far have yielded nothing useful. Anyone run into this before? EDIT: SOLUTION BASED ON CHIP'S ANSWER               add_action('pre_get_posts', 'hdb_add_custom_type_to_query');          function hdb_add_custom_type_to_query( $notused ){          if (! is_admin() ){             global $wp_query;             if ( is_author() || is_home() ){                 $wp_query->set( 'post_type',  array( 'post', CUSTOM_TYPE ) );             }          }     }      Assumes you've defined CUSTOM_TYPE constant at some point, probably when you declare the custom post type.


need to add attach thumbnail from my form

i need to add [attach thumbnail] to this form functions.php Code:               if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) &&  $_POST['action'] == "new_post") {              // Do some minor form validation to make sure there is content         $title =  $_POST['title'];         $ordertype = $_POST['ordertype'];         $price = $_POST['price'];         $ordertime = $_POST['ordertime'];              // Add the content of the form to $post as an array         $new_post = array(             'post_title'    => $title,             'post_content'  => $description,             'post_category' => array($_POST['category']),             'post_status'   => 'publish',             'post_type' => 'post'         );         //save the new post         $pid = wp_insert_post($new_post);          add_post_meta($pid, 'ordertype', $ordertype, true);         add_post_meta($pid, 'price', $price, true);         add_post_meta($pid, 'ordertime', $ordertime, true);         wp_redirect('/'); exit;         //insert taxonomies     }      source: Form to Add Posts to Custom Post Type


Getting categories to change appropriately when using $cat = ' ';

The code below is based on a couple of forum posts from a couple of places. To a certain extent, it works. The issue I am having is that it only shows "Activities", no matter what parent category I'm in. I tried replacing "activities" with a number of very unsuccessful alternatives (conditionals, get functions, and others); nothing worked.               <?php $cat = 'Activities'; /* This is the problem area.        Trying to get $cat to equal the name of the selected parent categories; the rest of        the code seems to be working, at least for the Activities category. */          $catID = get_cat_ID($cat);     echo '
' . $cat . '
';     $subcats = get_categories('child_of=' . $catID);     foreach($subcats as $subcat)     {         echo '
' . $subcat->cat_name . '
';         echo '
';         $subcat_posts = get_posts('cat=' . $subcat->cat_ID);         foreach($subcat_posts as $subcat_post)         {             echo '
';             $postID = $subcat_post->ID;             echo '';             echo get_the_title($postID);             echo '';             echo '
';         }         echo '
';     }?>


How to make certain page templates visible to admin only

Making a site for a client, I have some pages that the client won't be able to edit or delete. These pages rely on specific page templates. However, I don't want these templates to be available for the client when creating new pages. Is there someway to hide these certain page template from the page attributes dropdown when creating new pages? Thanks


Show child pages when on a child page

On my site I have a number of parent pages with associated child pages. How can I show all the child pages of one particular parent when a visitor is either on the parent page or one of it's children? For example; If someone clicks onto the "Story" parent page, they'll see a list of "story" child pages in the sidebar (As well as a link to the parent page). Then if they click through to one of those child pages, they'll still be able to see the list in the sidebar


Why is there a code error in my plugin's search description?

So, I have finally uploaded my plugin to the WordPress list, but when I search for it an error comes up in the description: ![enter image description here](http://i.stack.imgur.com/oyfVq.png) I don't even have that line of code in my trunk/ Going into the plugin page, the issue disappears and my description & excerpt work fine. There doesn't seem to be a problem when I search within my blog either: ![enter image description here](http://i.stack.imgur.com/LVAQz.png) Having taken the template readme.txt and used that as a base, I don't _think_ I'm missing anything. Readme:               === WordQuest ===     Contributors: ianfhunter     Donate link: https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=94YBVKCNZRPSE     Tags: RPG, Role-Playing Game, Game, Incentive, Posts     Requires at least: 3.0.1     Tested up to: 3.9     Stable tag: 1.0     *   Stable tag should indicate the Subversion "tag" of the latest stable version, or "trunk," if you use `/trunk/` for     stable.          License: GPLv2 or later     License URI: http://www.gnu.org/licenses/gpl-2.0.html          What feature is WordPress severely lacking? Goblins. Dragons.      Earn experience as you blog. Watch your avatar slowly grow in power with every post.          == Description ==          What feature is WordPress severely lacking? Goblins. Dragons. This plugin is here to fix that.          Earn experience as you blog. Watch your avatar slowly grow in power with every post.          Complete quests to earn bonus experience by writing about selected categories.          See the visual changes to your avatar as you level up.          Your hero changes class according to your posting style!          OpenSource - Add your own activities for your hero. https://github.com/ianfhunter/WordQuest          == Installation ==          This section describes how to install the plugin and get it working.          e.g.          1. Upload `WordQuest/` to the `/wp-content/plugins/` directory     2. Activate the plugin through the 'Plugins' menu in WordPress     3. Enjoy :)          == Frequently Asked Questions ==          = What about Feature X? =          If you'd like a feature, put in on the issue tracker and I'll take a look at it. https://github.com/ianfhunter/WordQuest/issues          There are plenty of things you can implement yourself, without much tech knowledge, including additional idle messages and avatar animations. Feel free to email me suggestions if you don't know how to use Github.          = I don't want that category to come up in my quests! =          We'll hopefully address this issue in a later version. Noone gets excited about writing 'Uncategorized' Posts.          = What else are you planning? =          I'm thinking of adding in some graphs and stats to show how your hero has progressed. But we'll have to see how free I am, and how popular the plugin gets.          == Screenshots ==          1. Your hero adventures while you post     2. Status - Classes, Levels, Quests!          == Changelog ==          = 1.0 =     * First WordPress Release     * Quests!     * Character Classes!     * Visually levelling Heroes!     * Rotating Idle Messages          == Image Attributions ==          Hero Sprites: http://untamed.wild-refuge.net/rmxpresources.php?characters      My Plugin File:               <?php     /*     Plugin Name: WordQuest     Plugin URI:      Description: What feature is WordPress severely lacking? Goblins. Dragons. This plugin is here to fix that.     Author: Ian Hunter     Version: 0.0     Author URI: www.ianhunter.ie     */          /*         WordQuest         Copyright (C) 2014  Ian Hunter ianfhunter@gmail.com              This program is free software; you can redistribute it and/or modify         it under the terms of the GNU General Public License as published by         the Free Software Foundation; either version 2 of the License, or         (at your option) any later version.              This program is distributed in the hope that it will be useful,         but WITHOUT ANY WARRANTY; without even the implied warranty of         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the         GNU General Public License for more details.              You should have received a copy of the GNU General Public License along         with this program; if not, write to the Free Software Foundation, Inc.,         51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.     */          #Returns a user's active quest from file     function get_quest(){         $file = WP_CONTENT_DIR."/WordQuest/experience" . get_current_user_id() . ".rpg";          if (!file_exists($file)){             $quest = add_quest();         }else{             $json = file_get_contents ( $file );             $jsonD = json_decode($json);             $quest = $jsonD->{"quest"};         }         return $quest;     }               #The info display in the top right hand corner.     function admin_info_header() {              $file = WP_CONTENT_DIR."/WordQuest/experience".get_current_user_id().".rpg";          if (!file_exists($file)){             $quest = add_quest();             $experience = 0;             if (!file_exists(WP_CONTENT_DIR . "/WordQuest/")){                 mkdir(WP_CONTENT_DIR. "/WordQuest/");             }              }else{             $json = file_get_contents ( $file );             $jsonD = json_decode($json);             $experience = $jsonD->{"total_experience"};             $quest = $jsonD->{"quest"};         }              $stats = calc_level($experience);         # Classes Here - Templar, etc         echo '
⚔ Level ' . $stats[0] . " " . player_class() . ' - ' . $stats[1] . '/' . $stats[2] .' Exp - Quest: "'. $quest.'"
';     }          #Calculates what level a user is.     # @param - Total experience:     # @modifier: 1.6     # @Returns: Level, Remaining Exp, Next Level EXP     function calc_level($experience){         $level = 500;         $modifier = 1.6;         $count = 0;         while($experience - $level > 0){             $experience = $experience - $level;             $level = $level * $modifier;             $count = $count + 1;         }         return array($count,round($experience),round($level));     }          #Extracts the longest word from a string     function reduce($v, $p) {         return strlen($v) > strlen($p) ? $v : $p;     }          function player_class(){         $file = WP_CONTENT_DIR."/WordQuest/stats" . get_current_user_id() . ".rpg";          if (file_exists($file)){             $file = WP_CONTENT_DIR."/WordQuest/stats" . get_current_user_id() . ".rpg";              $json = file_get_contents ( $file );             $jsonD = json_decode($json,true);                  #Get the highest value from our stats             $value = max($jsonD);             $keys = array_keys($jsonD,$value);             #Combined classes?                  return ucfirst($keys[0]);              }else{             return "Wanderer";         }     }          function calculate_stats($input){         $file = WP_CONTENT_DIR."/WordQuest/stats" . get_current_user_id() . ".rpg";          if (!file_exists($file)){             $stats = array( "dwarf"       => 0,                              "giant"       => 0,                              "bard"        => 0,                              "illusionist" => 0,                              "oracle"      => 0,                              "wizard"      => 0,                              "assassin"    => 0,                              "priest"      => 0,                              );         }else{             #Read existing stats into the array                 $json = file_get_contents ( $file );             $stats = json_decode($json,true);         }                   #Based on post length:         if(str_word_count($input) < 200){             $stats["dwarf"]++;                 }else if(str_word_count($input) > 1000){             $stats["giant"]++;         }              #Based on content:         if (strpos($input , "la" ) !== False){             $stats["bard"]++;          }         if (strpos ( $input , "img" ) !== False){             $stats["illusionist"]++;         }         if (strpos ( $input , "youtube" ) !== False){             $stats["oracle"]++;         }         if (strpos ( $input , "svg" ) !== False){             $stats["wizard"]++;         }              $longest_word = array_reduce(str_word_count($input, 1), 'reduce');         if (strlen($longest_word) < 6){             $stats["assassin"]++;         }else if (strlen($longest_word) > 12){             $stats["priest"]++;         }         $json = json_encode($stats);         file_put_contents ( $file ,$json );     }          #Adds experience upon posting, currently based on character count     function add_experience() {         #Making sure that experience is only added on newly published items             if( ( $_POST['post_status'] == 'publish' ) && ( $_POST['original_post_status'] != 'publish' ) ) {             $file = WP_CONTENT_DIR."/WordQuest/experience" . get_current_user_id() . ".rpg";              if (!file_exists($file)){                 $experience = 0;                 $quest = add_quest();             }else{                 $json = file_get_contents ( $file );                 $jsonD = json_decode($json);                 $experience = $jsonD->{"total_experience"};                 $quest = $jsonD->{"quest"};                           #Check if our quest category matches a category we published this post under. +100xp Bonus                 $filed_under = ($_POST["post_category"]);                 $cat_list = get_categories();                 $filed_names = array();                      for($i = 0; $i != count($filed_under) - 1;$i = $i + 1){                     array_push($filed_names, $cat_list[$filed_under[$i]]->{"cat_name"});                 }                      #If quest fufilled, Give a bonus 100xp and allocate new quest. TODO: Notification?                 if (in_array($quest, $filed_names)){                     $experience = $experience + 100;                     $quest = add_quest();                 }             }                  $exp = strlen(str_word_count($_POST['content'])) + $experience; #going off of word count instead of characters             calculate_stats($_POST['content']);             $json = json_encode(array(                                         "total_experience" => $exp,                                         "quest" => $quest                                       ));             file_put_contents ( $file ,$json );         }     }          // function category_whitelist(){     //     #always returns get_categories for now.     //     $file = WP_CONTENT_DIR."/WordQuest/exclude" . get_current_user_id() . ".rpg";      //     if(!file_exists($file)){     //         return get_categories();    #all whitelisted     //     }else{     //         $contents = file_get_contents($file);     //         return get_categories("exclude=". rtrim(implode("&",explode(",", $contents)),"&") );    #replaces "," with "&" and removes trailing character     //     }     // }          #Activates a quest     function add_quest(){         $cat_list = get_categories();#categories_whitelist();         $quest = $cat_list[array_rand($cat_list)];         return $quest->{"cat_name"};     }          // #Not integrated yet.     // function exclude_cat($number){     //     $file = WP_CONTENT_DIR."/WordQuest/exclude" . get_current_user_id() . ".rpg";      //     $existing = "";     //     if(file_exists($file)){     //         $existing = file_get_contents ( $file );     //     }        //     file_put_contents($file, $existing . $number . ",");     // }     // function include_cat($name){     //     $file = WP_CONTENT_DIR."/WordQuest/exclude" . get_current_user_id() . ".rpg";      //     $existing = "";     //     if(!file_exists($file)){     //         return;    #nothing to un-exclude     //     }      //     $existing = file_get_contents ( $file );     //     $new = str_replace($name . ',', '', $existing);     //     file_put_contents($file, $new);     // }               function quest_metabox(){         add_meta_box("rpg-metabox", "WordQuest", 'draw_metabox', 'post', 'side', 'high');     }          function idle_messages(){         $file = WP_PLUGIN_DIR."/WordQuest/idle.rpg";          $contents = explode("\n",file_get_contents($file));         return $contents;     }          #     function get_heroavatar(){         $available_avatars = 7;    #TODO: generate this from the amount of files in the levels folder         #Get level         $file = content_url() . "/WordQuest/experience".get_current_user_id().".rpg";          if (!file_exists($file)){             $quest = add_quest();             $experience = 0;              }else{             $json = file_get_contents ( $file );             $jsonD = json_decode($json);             $experience = $jsonD->{"total_experience"};             $quest = $jsonD->{"quest"};             $quest = $quest;         }         $stats = calc_level($experience);         $level = $stats[0];              $n = 0;         $count = 1;         while($level > $n && $n != $available_avatars - 1){             $n = $n + ($n + 1);     #n = current Triangular Number                     $count = $count + 1;    #count = 'X'th triangular number         }         return $count;     #As files are indexed from 0          }          function draw_metabox(){         #Would be really nice to rotate through some phrases here.         #And also have avatars based on your character         #Credit: http://leon-murayami.deviantart.com/art/Illusion-of-Gaia-Will-XP-402827050              echo "
" . "Killing some slimes... " . "
" . "Current Quest: Write about '" . get_quest() . "'";         $params = array(           'messages' => idle_messages(),         );         wp_register_script('rotation_script',plugins_url().'/WordQuest/idle_messages.js');         wp_localize_script('rotation_script', 'object_name', $params );         wp_enqueue_script( 'rotation_script' );          }          add_action('admin_bar_menu', 'admin_info_header');     #add_action('admin_menu', 'rpg_menu' );     add_action('publish_post', 'add_experience' );      add_action('add_meta_boxes', 'quest_metabox' );           ?>      Update: on further inspection, this line seems to come from feedback that was emailed to me re: things to fix for submission. This doesn't explain why it would be in the search results though. Why is this happening and how can I fix it?


Rename page URL

I have the following URL structure:               http://localhost/wordpress/gallery?id=331      `id` specifies the `id` of the post. `gallery` is a normal page inside which I am accessing the `id` of the post and fetching the attachment images using `WP_Query()`. I want to replace the URL of this page to:               http://localhost/wordpress/topic/place/new-delhi/gallery?id=331      in which the parameters `place` and `new-delhi` may vary in multiple other options and `topic` is the keyword which remains the same. I have tried using some unfruitful `.htaccess` file code. Can anyone please help?


retrieve custom field "latitude, longitude" then add to google map

I need to call a custom field called 'latitude' and 'longitude' and then take those two values and pass them as a pinpoint in google maps. I searched and found this: Pass custom fields values to Google Maps but it didn't seem to help me. My professor added this.               var point = new GLatLng(latitude,longitude);     map.addOverlay(new GMarker(point));      yet I can't seem to get anything working. Here's the full code               <script type="text/javascript">                                       var point = new GLatLng(latitude,longitude);                             map.addOverlay(new GMarker(point));                                  function initialize() {                                 var latlng = new google.maps.LatLng(point);                                 var myOptions = {                                         zoom: 3,                                         center: point,                                         mapTypeIds: google.maps.MapTypeId.HYBRID                                 }                                  var map = new google.maps.Map(document.getElementById("map_canvas");                             }                                    google.maps.event.addDomListener(window, 'load', initialize);                                            </script>      I'm fairly certain he didn't use `wp_localize_script()` or `wp_register_script()` it was working at one point but after a WP update it was deleted. Any help would be greatly appreciated.


How will self-hosted WordPress work with Google Page Speed Service?

Google announced Page Speed Service, jumping on bandwagon of all-in-one site optimization and CDN.   * What are the potential issues, when configuring self-hosted WordPress for it?   * How will setting up reference domain work with WP? Considering that is required for Google to pull content, but public site URL will be different.   * Will it be possible to set it up with multisite?   * Should static caching plugins be left enabled or disabled for better compatibility?   * How will it work with wp-admin and Ajax? Should those be blacklisted in service settings? PS this is intended to be large reference question, so feel free to edit in your own questions on subject


How to install plugins in individual sites on a wordpress network?

I'm trying to install plugins in my wordpress subsites instead of network activate that plugin. But i'm not seeing any "add new" link in my subsite plugin area. How to install plugins in my individual sites. Am i missing something?. Thanks


What doctype is considered best practice to use for Wordpress?

I am finding a lot of validation errors courtesy of http://validator.w3.org/ in a clients website with the following HTML tag: `<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">` It appears this was also used in the original version of the theme as well. I'm just wondering if I should go for a certain Doctype always over another?


how to add custom fields into new & update post page?

I want to add new whole section of custom fields in admin UI of   * new post page   * edit post page Could somebody suggest any nice code example?


How to divide posts (custom post type) content on multiple pages?

I have a custom post type called _artist_ and each _artist_ have some custom fields such as extra text fields and images. I do not want to display all the info about each artist on the same page _single-artist.php_. So for an example if I want to have one page an artist biography another one artist gallery and another one artist contact. It would also be neccesery to have a navigation to those sub-pages of each artist. Here is an example of something that I am going after: http://i8.is/artist/birgir-andresson/ I believe there are more than one way to do this so how can something like this be achieved?


update_post_meta not working

Making a plugin to make my life easier at creating over 3000+ pages. Take a look at the code I have so far.               if (isset($_POST['action']))     {     $one = array(      'post_title' => $_POST['title'],      'post_date' => $_SESSION['cal_startdate'],      'post_content' => 'This is a post.',      'post_status' => 'publish',      'post_type' => 'page',      'post_parent' => $_POST['title']      );     $two = array(      'post_title' => $_POST['title'] . ' Air Conditioning',      'post_date' => $_SESSION['cal_startdate'],      'post_content' => 'This is a post.',      'post_status' => 'publish',      'post_type' => 'page',      'post_parent' => $_POST['title']      );          $post_id = wp_insert_post($one);     $post_id = wp_insert_post($two);          update_post_meta($post_id, "_wp_page_template", $_POST['title'] . '.php');     echo $_POST['title'] . '.php';     }     else {          }      For some reason, the _wp_page_template is NOT WORKING and it's quite frustrating. If I go to the pages this code generates.. it still says "default template" when it should be $_POST['title'].php If anyone can offer help on this, it would be much appreciated. Regards, Brandon


How to get a custom page through plugin?

I am developing a Wordpress plugin handling a calender in which it is possible to sign up for a given event. As part of this, I want to make a custom page for the signup-form and confirmation message to the client, however I have no idea how to do this. I have seen that there is a wp_insert_post() function to insert a new post, but I need a page with custom plgin content (signup form) instead. Is this even possible to do and how do I do this if it is? Thanks


How to store meta field values

I would like to store a few extra details for my custom post type, using meta boxes. Should I store all the values under one meta key in an array, or create several meta key and value pairs?


Preserving line breaks when saving and displaying custom fields data

I'm collecting data via a form plugin and save that data in form of a post with several custom fields. I then display the content of the post and the custom fields on my post template via `<?php if(get_post_meta($post->ID, '_aboutus', true)): echo '<div class="companyaboutus">'.get_post_meta($post->ID, '_aboutus', true).'</div>'; endif; ?>` The form field for the about us text is a text/paragraph field and most contributors add several lines of text into the field. Displaying the content/text via the code above doesn't show any line breaks though - any idea how to preserve the line breaks? Any help would be highly appreciated! Many thanks in advance, Thomas


Creating a archive for taxonomy terms, not the term results

So I am attempting to build the first page in my navigation hierarchy to choose product categories. I have a custom taxonomy called collections. I would like to create a page that loops through all terms in the collections taxonomy and displays the Term +link and description. Just about everything I have found besides the code below is creating a list of post from a particular taxonomy. That is not what I want yet. I want a master page that has each taxonomy term with a description that then links to the post that corresponds to that term. For example if my taxonomy was transportation, terms may be car, boat, plane which would have a description explaining what a car boat or plane is. Then each term would link to a list of specific cars or whatnot. I created a file called `taxonomy-collections.php` and put the following code in. But it is not doing the trick, can anyone suggest a solution to this problem?               <?php if ( have_posts() ) : while ( have_posts() ) : the_post();          $terms = get_terms( 'collections' );          echo '
';          foreach ( $terms as $term ) {          // The $term is an object, so we don't need to specify the $taxonomy.     $term_link = get_term_link( $term );          // If there was an error, continue to the next term.     if ( is_wp_error( $term_link ) ) {         continue;     }          // We successfully got a link. Print it out.     echo '
' . $term->name . '
';     echo  term_description($post->ID,$term);          }          echo '
';          ?>          <?php endwhile; else : ?>
<?php _e( 'Sorry, no posts matched your criteria.' ); ?>
     <?php endif; ?>      This is almost straight from the codex, so I'm guessing I am missing something. currently the code has each term displayed as a list, but I do want to change it to a grid format if someone could help with that too. So each term and description will be wrapped in a div and right aligned with the next.


Which is the neatest way to have homepage articles and a blog?

I have a homepage that should display a few different posts from different categories. I use the "Stick this post to the front page" option to this matter and each post permalink looks like `http://site.com/sample-post/`. Now this site should also feature a blog with articles (these are different than the homepage ones) at `/blog` with permalinks like `http://site.com/blog/sample-post/`. I thought on doing this through custom post types. That way I'd have "Homepage articles" and "Blog Posts", but I feel like I'm overcomplicating it. Is there a way of doing it on a simpler manner?


Display related custom taxonomy posts in sidebar

Can I use this snippet to retrieve posts from a custom taxonomy in a custom post type?               <?php $sermon_series = new WP_Query( array('series' => 'type')); ?>          <?php while ($sermon_series->have_posts()) : $sermon_series->the_post(); ?>
<a href="<?php the_permalink(); ?>"><?php the_title(); ?>
          <?php endwhile; ?>      It displays regular posts now, but I need it to display posts from a custom post type called "Sermons" in my wordpress.


Cleaning up WordPress to improve performance?

Looking over the current WordPress codebase it's clear that functions are over-used. My count is over 8,100 functions/methods are defined inside the WordPress codebase. That is terrible, and a terrible use of resources. **The problem with that many functions (or classes) is that means wordpress is not DRY (do not repeat yourself) and I'm sure many of these blocks could be combined or replaced with better patterns.** However, we need someway to buffer the current API (all those functions) so we can begin to combine the backend code without the "interface" (used loosely) changing. ### The solution? PHP 5 & 6 has SPL Autoloading of classes. It's a feature that allows PHP to wait until it needs a class before it load it. This prevents wasted resources as unused features/files are not loaded until they are needed. Unfortunately, WordPress can't use this because "autoloading" in PHP only works for classes.. and WordPress is a mountain of functions. I am looking at options and challenges to cleaning up the WordPress codebase and this seems to be the biggest one. Because WordPress has created so many functions (rather than exposing classes) for plugin/theme developers there seems to be no way to pull out of this deep hole without breaking thousands of themes & plugins. The only idea I was able to come up with is to write a script that would look over all functions and convert them to classes which could then be autoloaded. In their place shell functions would be left that called the class-i-fied version of the function. Something like this:               function wp_foo_bar() {         call_user_func_array(array('foo' => __FUNCTION__), func_get_args());     }      Has anyone else tried to cleanup the WordPress codebase? Are there other problems with this approach? ### Update to Clarify Converting the system to use autoloading is the first step that allows us to gain better control of how resources are loaded and put up facades as we migrate some of the core features into better designs. It's much harder to depreciate functions. Therefore, this question starts with the beginning re- write of the system. If we stopped here - then we might have a net loss in performance because we have the same number of functions - and now classes are also beginning autoloaded. Therefore, _this has nothing to do with procedural code vs OOP_. It's about the best way to buffer the API against changes to the system as a whole. The current wordpress dev team is already doing this at a very slow pace. There are already over 60 classes in the wordpress system.


Ajax request to admin-ajax.php and window.location.href

In relation to this question, I don't understand the meaning of: > Instead of sending the ajax request to the admin-ajax.php, send it to the > same url (using js window.location.href ) but including an endpoind that can > be 'mobile' or 'desktop'. An hook into template_include filter will do the > rest. Hope it's clear This is my call:               jQuery.ajax({             url: my_ajax_script.ajaxurl,             data: ({action : 'get_mobile_template'}),             success: function(data) {             document.write(data);             }         });      Is there anybody who understands this matter and is able to come up with an example?


Updating results from a SQL query in phpMyAdmin

I've been searching and searching but can't find out how to take my results from an SQL query and updating/editing them in a bulk fashion. I'm a newbie at working with databases directly. I'm using myPHPadmin 3.5.8. I'd like to remove the number '1' from the file name in all post attachments (media library) that have a letter right before them. I've successfully narrowed the hundreds of attachments that I need to change through this query:               SELECT *      FROM  `wp_posts`      WHERE  `post_type` LIKE  'attachment'     AND  `guid` REGEXP  '^.*[a-z]1.jpg$'      How can I now remove the 1 from the file name? Any pointers or links to documentation on how to do this is extremely helpful. Thanks!


Can you create your own widgets and use them for editable areas of client content?

I'm relatively new to WordPress. As a content management system I chose WordPress so that I could design a website for a friend in a way that would be easy for them to use when I had handed it over. Unfortunately I see that it is nether easy or in some cases logical. To combat this I am thinking about scrapping the the use of hard to adapt temperamental templates and put together a design/template myself. To make it easy for my friend I want to make their website structure largely untouchable (unless you were really looking for it, or at least separate) and have easy to use input boxes as editable areas for my friend to update, reword or change photos in, without having to go into any code. Very much like the use of phrase keys within HTML to call data from somewhere else. I dont 100% know how this exactly works but we use it at work with our own CMS system. Could this be done with widgets? If so how?


Add Custom postmeta Fields to Custom Post Type RSS in wordpress

function add_custom_fields_to_rss() {         if(get_post_type() == 'my_custom_post_type' && $my_meta_value = get_post_meta(get_the_ID(), 'my_meta_key', true)) {             ?>             <my_meta_value><?php echo $my_meta_value ?></my_meta_value>             <?php         }     }     add_action('rss2_item', 'add_custom_fields_to_rss');      i have see this code. Can you give me the page name where i implement this in wordprss.


How to carry over existing wp users to a new buddypress installation

I had made a community with a different plugin (I think it was mingle. I recently installed buddypress, removed mingle and changed the site to suite. Now the problem is the existing users are not listed as members in the members page, only me, the admin. I have looked for, but not found, a solution. i am know how to use Wordpress but this one has stumped me. This may be an easy question for all those experienced buddypress users out there, but I am just starting, so keep that in mind before you say how completely dumb I am :) Thanks for taking the time to read this.


Import existing image as a single post

I want to add a bunch of existing images on the server but I want each of them added as a separate post instead of all images into one post. How can I do this?


Is there a way I can return terms by name using a shortcode?

I want to create a shortcode to return a string of values, which are the term names. So I can use it to pass data inside a plugin. Anyone cracked this one before?               /**      * Custom shortcode to get terms for the Formidable plugin      */          function ALC_post_terms_by_id( $term, $atts ) {         global $post;              $alc_Terms = wp_get_post_terms( $post->ID, $term, 'orderby=name&hide_empty=0' );              $term_array = array();         foreach ($alc_Terms as $alc_Term) {             $term_array[] = $alc_Term->name;         }              // $atts = shortcode_atts( $term_array() ), $atts );              return $term_array();     }     add_shortcode( 'term_by_id', 'ALC_post_terms_by_id' );      * * * **New attempt** This is the shortcode I use:               [get_terms_by_taxonomy taxonomy="bouwjaar"]      This is the new function after suggestion in the comment by _TheDeadMedic_               /**      * Custom shortcode to get terms for the Formidable plugin      */          function ALC_post_terms_by_taxonomy( $atts ) {              // return $atts['taxonomy'];              $taxonomyTerms = wp_get_post_terms( $post->ID, $atts['taxonomy'], 'orderby=name&hide_empty=0' );              $term_array = array();         foreach ($taxonomyTerms as $taxonomyTerm) {             $term_array[] = $taxonomyTerm->name;         }              return $term_array; // returns "Array"              // return implode( ', ', $term_array );         // implode returns "nothing"     }     add_shortcode('get_terms_by_taxonomy', 'ALC_post_terms_by_taxonomy');


Add delete, approve, spam Links to Comments

Anyone know how to add quick comment moderation links for users who have permission to add/edit posts and comments? (Upprove / Unappove / Edit / Spam / Trash ). **Note:** in my comments.php I call the loop with `<?php wp_list_comments(); ?>`


How to separate each individual blog post?

Im trying to create a blog page that has each post separate with a border around each one. A good example I can think of would be http://blog.pagodabox.com/. How every post is divided into its own style box. I tried running the loop, but I end up getting the border around the entire posts.. the code that i have so far is..
                           <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<?php the_time('F jS') ?>

<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>
                  <?php the_excerpt(__('(more…)')); ?>                   <?php endwhile; ?>                                 <?php endif; ?>
      I was implementing the style with the #services. But once again getting the style to the entire list of the posts not individual...


Add existing user to blog Multisite when e-mail exists

I'm trying to add an existing user to a blog if he fills in an existing email. The registration fields are set up with Gravity Forms. I've tried the following:               add_filter('gform_email', 'emailexists', 10, 4);         function emailexists($email, $config, $form, $entry){         global $wpdb;                  $email = strtolower($entry["2"]);             $blogid = get_current_blog_id();             $role = 'subscriber';                  if(empty($email))                  return $email;                  if(!function_exists('email_exists'))                 require_once(ABSPATH . WPINC . "/registration.php");                  if(email_exists($email)) {                 $details['user_id'] = 27;                 $details['role'] = 'subscriber';                     add_existing_user_to_blog( $details );                          }                        return $email;              }      I've used a hardcoded user ID to make it somewhat easier. This userid exists of course. I'm not sure if I need to use add_user_to_blog or add_existing_user_to_blog and how to use it exactly. How to make this work? Thanks! See also: http://codex.wordpress.org/Function_Reference/add_existing_user_to_blog


How to call a plugin function from front end form

I have a page template having a form which further have 3 input fields and and a submit button. I have a written a function in a plugin which inserts the retrieved values in database. I am trying to figure out what to write in action attribute of the form, so that when user clicks the submit button, the function gets executed?


How do I make Wordpress "Page" link in the top nav bar go to an external URL?

I would like the Wordpress page link as shown here go to an external URL instead of going to page. What is the best way to set this up? I'm running Wordpress 3.1.3. Thank you.


Get custom value from external database

a non-coder here but fairly competent to put together blocks of code :) I´m trying to build a prototype using Wordpress and one need I have is to connect to one or more different databases to get a value from a Custom Field in Profiles. First, I´d like to display the external Custom Field at my site. Thats good. But how do I get that value and include it in a select User Profile in my primary site?


Embed PDF into wordpress

is there's a way to show a PDF file inside Post in wordpress ? i used tag but if someone have Internet Download Manager , Dialog will appear to Download the PDF file if visitor click cancel they will not be able to see it ONLY download it so is there's a way to Stop automatic download   there's many plugins for that but image quality is too bad please some one help me , thanks


pagination broken because wordpress is adding index.html

in my blog, for some reason the pagination links look like this: http://www.example.com/blog/page/2/index.html and that link does not work. However this link works: http://www.example.com/blog/page/2/ how do i fix this (either by changing the .html url or by making it work)? you can see a live example of this bug here: http://www.honordiaries.com/blog/


Add success message to category add screen

I have custom taxonomy named "Products", When i add new Product using "edit- tags.php", It is added using ajax. I want to show message after it is added, like "Product added successfully"! When we edit taxonomy, we get message "item updated." But here page refreshes. I want same indication/message for when adding product. is it even possible? I would also like any js solution, if i can get a hook in js which is called after adding custom taxonomy.


Should all references to a text domain be to my current theme?

I'm running Theme Check on a theme I've inherited and I've come across lots of recommendations like this one:               RECOMMENDED: Text domain problems in loop.php. The twentyten text domain is being used!      The site has no plans for being translated, so what's the best thing to do in this situation? Replace every reference to `twentyten` to my theme's text domain, or just remove all references of a text domain at all? The WordPress documentation is a little confusing :-/


How do I add a function on a specific post category?

I am using theme Twenty Eleven and am trying to add a vote up script in the content.php which only displays on a certain category.


After duplicating site to a sub folder, links send user to original site

I wanted to duplicate my WordPress site, and make just a few small changes to the duplicate. However, after duplicating the site, I have had problems with the links sending the user back to the original site. Both the original and duplicate site should function. Here are the steps I have taken:   1. I duplicated my entire site's WordPress files and placed them in a folder in the public_html directory, where the original site is located.   2. I made a dump of the original DB and changed all the table prefixes (that were `wp_`) to `newsite_`. I did a search-and-replace in the MySQL dump for `http://www.originalsite.com` to replace with `http://www.originalsite.com/newsite`. I then imported that edited DB dump into the same database where the original site's DB is.   3. I opened up wp_config.php and changed `$table_prefix = 'wp_'` to `$table_prefix = 'newsite_'`   4. Realising I couldn't log into the duplicated site, I followed the advice in this stack answer and changed the two key names in `newsite_usermeta` and `newsite_options`. I am able to visit the home page of the duplicated site and I am able to login to the backend. However, all links on the site take the user to the correct page, but on the original site. It is not just the clickable links that are not working correctly, when the desired subpage address is typed into the url bar, the user is again taken to that page on the original site. Currently the `.htaccess` file contains:               <IfModule mod_rewrite.c>     RewriteEngine On     RewriteBase /     RewriteRule ^index\.php$ - [L]     RewriteCond %{REQUEST_FILENAME} !-f     RewriteCond %{REQUEST_FILENAME} !-d     RewriteRule . /index.php [L]     </IfModule>      Do I need to edit this at all? What steps am I missing in the migration process?


How to specify a certain amount of images queried, not all?

I have a query for calling images from a post category. I am trying to control it to only query 6 images. I have tried using php count, but its not working as expected. Any ideas of what I could do differently to achieve this. This was also the only way "I" was able to also include a "rel" tag for lightbox. Please keep that in mind if you know of a better way to do this. Thanks - I tried using the code pre tags and it wasnt showing full code so here is a pastebin link http://pastebin.com/kjkJQPR7


wp_editor in text mode only(without TinyMCE)

Is there a way to call `wp_editor` for a meta box using just the text/HTML mode without TinyMCE. I think the deprecated function pre-3.3 did this but I'm not sure how its done now.


Can't assign another category other than Uncategorized int he following front end post submission form?

I'm using this front end post submission form that I took from this question:               <?php           $postTitle = $_POST['post_title'];     $post = $_POST['post'];     $submit = $_POST['submit'];     $category = $_POST['cat'];          if(isset($submit)){              global $user_ID;              $new_post = array(             'post_title' => $postTitle,             'post_content' => $post,             'post_status' => 'publish',             'post_date' => date('Y-m-d H:i:s'),             'post_author' => $user_ID,             'post_type' => 'post',             'post_category' => $category         );              wp_insert_post($new_post);          }          ?>     <!DOCTYPE HTML SYSTEM>               <meta content="text/html; charset=utf-8" http-equiv="Content-Type" />     <title>Untitled Document</title>
     <form action="" method="post">

         Post Title	         <input name="post_title" type="text" />

         Post	         <input name="post" type="text" />

         Category	         <?php wp_dropdown_categories('show_count=1&hierarchical=1&hide_empty=0'); ?>

          <input name="submit" type="submit" value="submit" />     </form>
                     Now, I'm trying to add the category field: Top of the file:               $category = $_POST['cat'];      The `$post` array:                'post_category' => $category      Form part:               <?php wp_dropdown_categories('show_count=1&hierarchical=1&hide_empty=0'); ?>      The HTML for the drop down menu displays but when I select another category say, Jobs, the post is published as Uncategorized. Any suggestions to fix this?


Plugin to send messages to members/lists but not full-blown newsletters

I'm looking for a plugin that would allow the owner of a school to send student members short email messages. We don't need a full-blown newsletter feature but it does need to be able to have multiple lists (kids classes, adult classes, etc). Users don't need to talk to each other, just get a message that, for instance, the 10am class is cancelled, etc. Something like mailchimp seems like overkill and too much work for the client. Ideas? Thanks!


How to add a button which saves the post then executes a function

Currently, I have a function called ' **pub_notification** ' in my functions.php file which sends an email when the post is published, using the following code:               add_action('publish_post', 'pub_notification');      I would like to separate these functions by adding another button called ' **Send Notification** ' below the default 'update/publish' button, which, when clicked, would save the post, including the custom field data, and then execuite my ' **pub_notification** ' function. Any help would be very much appreciated. Of course this means I do not want to tie the execution of my ' **pub_notification** ' function to either ' **save_post** ' or ' **publish_post** ' actions, but rather I want it tied to the click of the ' **Send Notification** ' button.


Last post ordered by publish date using WP_Query on front page

I'm joining together few websites into one and I created appropriate posts and changed their post_date (publish date) to the original time of post. However (even if I list more than 1 post) the result, I get, is the last post according to quite recent 'post_modified' (last update of the post). // EDIT - more detailed explanation of the problem My original post on the old website is from, let say, Jan 1 2001 (original date). Next, I create a post on the new website on Sep 22 2013 (today) and manually set the publish date in the Post Edit area to the original date. I can see in the $wpdb `post_date=2001-01-01` and `post_modified=2013-09-22`. The last post shortcode return the post with the latest `post-modified` date instead of the latest `post_date`. // EDIT - end I'm running a custom WP_Query within a plugin's slide, using a short tag to place it there. The problem is, that it takes the last modified post instead of last published post. My code for the shorttag:               //[latestpost]     function latestpost_func( $atts ){         global $post;         $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1;         $query = new WP_Query( array( 'paged' => $paged ) );         $latestpost_arg = array(                               'post_type' => 'post',                               'posts_per_page' => 1,                               'orderby' => 'date',                               'order' => 'DESC',                               'paged' => $paged,                               'ignore_sticky_posts' => 1,                               'category__in' => array( 127, 253 )                 );         $latestpost_query = null;         wp_reset_query();         $latestpost_query = new WP_Query($latestpost_arg);                    if ( $latestpost_query -> have_posts() ) :           while ($latestpost_query -> have_posts()) :                 $latestpost_query -> the_post();                 if (has_post_thumbnail()) {                     $large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'full');                     $latestpost_image_div = '

';                 }                      $latestpost_details_div = '

' . get_the_title() . '

' . get_the_excerpt() . '

';                      $latestpost_output = $latestpost_image_div . $latestpost_details_div;           endwhile;          else :             $latestpost_output = 'Sorry, no posts matched your criteria.';          endif;            return $latestpost_output;      }           add_shortcode( 'latestpost', 'latestpost_func' );


How do I print a notice only on certain admin pages?

I'm writing a plugin which would print a notice, but only on the media page. I found the `admin_notices` and `all_admin_notices` actions, but these are fired on all admin pages. Is there any way to find which admin page is the hook being called on from within the callback?


How to create Alphabetic pagination with range?

Currently, I am trying to create an alphabetic pagination with ranges for a custom post type on a custom field using this code from kathy is awesome. I have gotten everything working except for the range aspect of it. Such as A-E, F-H and so on. Any help would be great. Thanks.


External Link issue in Visual Form Builder Pro

I am building a form in VFBPro and I have a conditional field that loads depending on which radio button is checked. The conditional field has instructions that require the user to click an external link. I entered the link as a href="http://www.domain2.com". When I go to the form to test it, the browser is pointed to mydomain.com/"http://domain2.com". What am I doing wrong?


Subdomains pointing to a permalink URL

I have Wordpress (v3.2.1) set up at domain.org.nz/wordpress with a number of pages set up as domain.org.nz/wordpress/services/example. I want to set up a subdomain, example.domain.org.nz to point to domain.org.nz/wordpress/services/example. When the subdomain is entered into the address bar, it (preferably) should stay as the subdomain (not a redirect). If there are any child pages of /example, the URL needs to appear as example.domain.org.nz/child. I have access to all Wordpress files, .htaccess, DNS settings etc but as I'm on a shared server, I don't have access to the httpd.conf I know this is a similar question to Multiple Domain Names - One WP Install (non-Multisite) - Default Each Domain name to Category Archive Can I use the same method? If so what needs to be changed for that to work in my instance? After almost a week of butting my head against this problem, any help is very much appreciated!! Current .htaccess:                   # BEGIN WordPress           <IfModule mod_rewrite.c>         RewriteEngine On         RewriteBase /wordpress/         RewriteCond %{HTTP_HOST} ^([^.]+)\.domain\.org\.nz$         RewriteRule ^(.*) http://domain.org.nz/wordpress/services/%1         RewriteRule ^index\.php$ - [L]         RewriteCond %{REQUEST_FILENAME} !-f         RewriteCond %{REQUEST_FILENAME} !-d         RewriteRule . /wordpress/index.php [L]         </IfModule>              # END WordPress


get_posts only children from certain parents

I have parent posts (custom post type hierarch=true) with ID 1, 2, 3, 4. The parent posts with ID 2 and 4 have child pages. I need to retrieve only posts 2 and 4 and all of their child pages. Something like this               $argsch = array('orderby' => 'date','order' => 'DESC','post_type' => 'products', 'include' => '2, 4');     $childs = get_posts($argsch);      How can I edit this to return child pages of the included id's?


wp_usermeta wp_usersettings

I would like to know what does these meta_value means for wp_usersettings meta_key in wp_usermeta table?   * meta_key: wp_usersettings    * meta_value: m1=o&m3=o&m0=o&m2=o Thanks


Registration key

I want to get my single wordpress installation a closed community. Just people who know the registration key should be able to sign up. I already added some more fields to the registration form but I can't fin a simple solution for the registration form to check if the code is correct!? Looking forward for some ideas! Thank you! Here's what I do have until now:               // This function shows the form fiend on registration page     add_action('register_form','show_first_name_field');          // This is a check to see if you want to make a field required     add_action('register_post','check_fields',10,3);          // This inserts the data     add_action('user_register', 'register_extra_fields');          // This is the forms The Two forms that will be added to the wp register page     function show_first_name_field(){     ?>
     Vorname
     <input id="user_email" class="input" type="text" tabindex="20" size="25" value="<?php echo $_POST['first']; ?>" name="first"/>

     Nachname
     <input id="user_email" class="input" type="text" tabindex="20" size="25" value="<?php echo $_POST['last']; ?>" name="last"/>

     Hochschule
     <select name="hochschule" id="hochschule" class="input">     <option value="Uni Augsburg" <?php selected( 'Uni Augsburg', get_the_author_meta( 'hochschule', $user->ID ) ); ?>>Uni Augsburg</option>     <option value="Hochschule Augsburg" <?php selected( 'Hochschule Augsburg', get_the_author_meta( 'hochschule', $user->ID ) ); ?>>Hochschule Augsburg</option>     </select>

     Studiengang
     <input type="text" class="input" name="studiengang" id="studiengang" value="<?php echo esc_attr( get_the_author_meta( 'studiengang', $user->ID ) ); ?>" class="regular-text" />

     Geschlecht
     <select name="geschlecht" id="geschlecht" class="input">     <option value="männlich" <?php selected( 'männlich', get_the_author_meta( 'geschlecht', $user->ID ) ); ?>>männlich</option>     <option value="weiblich" <?php selected( 'weiblich', get_the_author_meta( 'geschlecht', $user->ID ) ); ?>>weiblich</option>
          <?php     }          // This function checks to see if they didn't enter them     // If no first name or last name display Error     function check_fields($login, $email, $errors) {         global $firstname, $lastname;         if ($_POST['first'] == '') {             $errors->add('empty_realname', "Fehler: Bitte gib deinen Vornamen ein.");         } else {             $firstname = $_POST['first'];         }         if ($_POST['last'] == '') {             $errors->add('empty_realname', "Fehler: Bitte gib deinen Nachnamen ein.");         } else {             $firstname = $_POST['last'];         }             global $hochschule;         if ( $_POST['hochschule'] == '' ) {             $errors->add( 'empty_realname', "Fehler: Bitte gib deine Hochschule an." );         } else  {             $hochschule = $_POST['hochschule'];         }             global $studiengang;         if ( $_POST['studiengang'] == '' ) {             $errors->add( 'empty_realname', "Fehler: Bitte gib deinen Studiengang ein." );         } else  {             $studiengang = $_POST['studiengang'];         }             global $geschlecht;         if ( $_POST['geschlecht'] == '' ) {             $errors->add( 'empty_realname', "Fehler: Bitte gib dein Geschlecht an." );         } else  {             $geschlecht = $_POST['geschlecht'];         }          }          // This is where the magiv happens     function register_extra_fields($user_id, $password="", $meta=array())  {          // Gotta put all the info into an array     $userdata = array();     $userdata['ID'] = $user_id;          // First name     $userdata['first_name'] = $_POST['first'];          // Last Name     $userdata['last_name'] = $_POST['last'];          // Enters into DB     wp_update_user($userdata);     update_usermeta( $user_id, ‘geschlecht’, $_POST['geschlecht'] );     update_usermeta( $user_id, ‘hochschule’, $_POST['hochschule'] );     update_usermeta( $user_id, ‘studiengang’, $_POST['studiengang'] );               }


Problem with WP_query

I have a very annoying issue with 2 wp_query.   1. Showing 1 post - feature post               <?php       $do_not_duplicate = array();                      $args = array (     'post_type'  => 'post',     'posts_per_page'  => '1',          );          $my_query = new WP_Query( $args );     if ($my_query->have_posts()) :     while($my_query->have_posts()) :     $my_query->the_post();     $do_not_duplicate[] = $post->ID;      get_template_part( 'content-feat',get_post_format() );      endwhile;     endif;     wp_reset_postdata();           ?>        2. The rest of the posts              <?php                        // the query to set the posts per page to 6         query_posts($args);         $args = array(             'posts_per_page' => 6,              'paged' => $paged,                  );                   $my_query = new WP_Query( $args );         if ($my_query->have_posts()) :         while($my_query->have_posts()) :         $my_query->the_post();             if ( !in_array( $post->ID, $do_not_duplicate ) ) { // check IDs                               get_template_part( 'content', get_post_format() );             }                  endwhile;             endif;               ?>      **The problem:** Second loop is removing the post from first query (like its suppose to do) and should show 6 posts. The problem is that is showing on first page 5 posts and on second 6 posts. I don't know where is the problem, can u guys help me? I'm kinda stuck with this issue. Thx


TinyMCE tablecontrols missing after 3.9 upgrade - TinyMCE4

I wrote a simple Tables plugin for TinyMCE 4 (WP 3.9) and can't seem to find a way to enable table controls for TinyMCE.               function table_plugin_button($buttons) {        array_push($buttons, "table", "tablecontrol");        return $buttons;     }      I can see the Table icon and insert a new table just fine. However, I am missing the option to enable 'tablecontrols' that allows deleTable, split, merge, etc. In editor_plugin.js, I do seee:                   // Expose to public         tinymce.extend(this, {             deleteTable : deleteTable,             split : split,             merge : merge,             insertRow : insertRow,             insertCol : insertCol,             deleteCols : deleteCols,             deleteRows : deleteRows,             cutRows : cutRows,             copyRows : copyRows,             pasteRows : pasteRows,             getPos : getPos,             setStartCell : setStartCell,             setEndCell : setEndCell         }      How can I enable these buttons?


Add meta data to the menu

I encountered this problem what i thought to be one of the worlds simpliest things, I wanted to add a subtitle to the menu somethin alike this http://img4.imageshack.us/img4/7816/unled10b.png . Then i came to realise that the menu doesn't have its own custom template file, so my plan on loading the page's meta data namned menudesc didn't go as planed. I read around alittle and found out that the menu code is found in post-template.php a copied that over to my function file but that didn't work out either. when i paste wp_page_menu the site goes blanc no errors no nothing, and besides i don't get how i'm to get the ip for the page inside this function so i can use get_post_meta($page->ID, 'menudesc', true);                   function wp_page_menu( $args = array() ) {         $defaults = array('sort_column' => 'menu_order, post_title', 'menu_class' => 'menu', 'echo' => true, 'link_before' => '', 'link_after' => '');         $args = wp_parse_args( $args, $defaults );         $args = apply_filters( 'wp_page_menu_args', $args );              $menu = '';              $list_args = $args;              // Show Home in the menu         if ( ! empty($args['show_home']) ) {             if ( true === $args['show_home'] || '1' === $args['show_home'] || 1 === $args['show_home'] )                 $text = __('Home');             else                 $text = $args['show_home'];             $class = '';             if ( is_front_page() && !is_paged() )                 $class = 'class="current_page_item"';             $menu .= '
' . $args['link_before'] . $text . $args['link_after'] . '
';             // If the front page is a page, add it to the exclude list             if (get_option('show_on_front') == 'page') {                 if ( !empty( $list_args['exclude'] ) ) {                     $list_args['exclude'] .= ',';                 } else {                     $list_args['exclude'] = '';                 }                 $list_args['exclude'] .= get_option('page_on_front');             }         }              $list_args['echo'] = false;         $list_args['title_li'] = '';         $menu .= str_replace( array( "\r", "\n", "\t" ), '', wp_list_pages($list_args) );              if ( $menu )             $menu = '
' . $menu . '
';              $menu = '
' . $menu . "
\n";         $menu = apply_filters( 'wp_page_menu', $menu, $args );         if ( $args['echo'] )             echo $menu;         else             return $menu;     }      that's the code for the menu


Emoticons not working on my site

I've always understood WP to have built-in emoticon support. I have them enabled in the settings, but they just don't do anything. Here is an example post that contains one at the end of the post, a wink... Is there a theme issue here? It's the Bushwick theme.


All In One Event Calendar: how to fetch events using ai1ec global variable.?

Am trying to display 'Upcoming Events' in my custom template. With normal WP_Query I doesn't returns other information like 'Event Venue', etc. I also tried to echo global variable like global $ai1ec_calendar_helper, $ai1ec_events_helper; tried to dump the variables but found all empty. I found some clue from [http://pastebin.com/SNp4TJij][1] [1]: http://pastebin.com/SNp4TJij but still no luck. My Code:                global $ai1ec_events_helper;          if($query->have_posts()){                                           while($query->have_posts()) {                                             $query->the_post();                                                  $event = Ai1ec_Events_Helper::get_event($post->ID);                                                    the_title();                                                   echo esc_html( $event->start_time );                                               echo $event->venue;                                                     }  wp_reset_query();                                                             }      So output would be like: ABC Concert at TX   Venue: Texas   Start Date: May 24th,2014   End Date: May 25th,2014 Anybody please help me. Thanks a lot in advance.


Return all roles, including custom roles

Rewritten: Hopefully this helps others. The question wasn't a duplicate question. **The custom roles and subscriber account were not being written.** It turns out that the if statement after the internal foreach was stopping the writing of the custom roles. Once removed then the loop worked properly. It's very important for novices to be provided explanations. In this case, **I would like to know why the if statement blocked the writing of the custom roles.** `if ( $wp_roles->get_role( $role_name )->has_cap( $new_cap ) )` * * * Original statements (bold unique parts to question): This is frustrating me. After months of trying different ways to think about retrieving all of the default and custom roles, I believed the following code would work. However, it is **only returning 4 of the 5 default roles and none of the custom roles**. This code works to return administrator, editor, author, and contributor but not subscriber. I can write an elseif statement after the inner foreach loop and force subscriber to be written as well as an elseif statement to force a known custom role .. but that defeats the purpose of a foreach to return all roles. Sorry but I'm a complete novice trying to read and understand as much as possible. This means I'm not asking you to write the code but maybe point me in the direction as well as provide an explanation.                       global $current_user, $wp_roles;              $all_roles = $wp_roles->roles;              $editable_roles = apply_filters( 'editable_roles', $all_roles );              foreach ( $editable_roles as $role_name => $role_info ) {                  /** If you have changed the wp_ prefix then you must modify this line to match the new prefix */             if ( is_object( $current_user ) && isset( $current_user->data->wp_capabilities[ $role_name ] ) ) {                      foreach ( $new_caps as $new_cap ) {                     if ( $wp_roles->get_role( $role_name )->has_cap( $new_cap ) ) {                         $capabilities[ $new_cap ] = true;                         $current_user->add_role( $role_name );                          }                 }                  }              }


How to query with get_posts() for posts with any tag

I need to do a simple post query that will get any post that has at least one tag. This is my current code that gets the posts with tag ID 27 or 36, but I need to modify it to get all posts with at least one tag.               $args = array(         'numberposts' => 5,         'tag__in' => array(27,36)     );     $myposts = get_posts( $args );


Create a custom post type for a photo post

I am looking for a way to create a Photo Post type. Basically a post that is a title and a single image. Where I am getting stuck is the actual attaching an image to a post. I would like to have an image upload field in a metabox. I followed this guide. I am able to see the WP upload box and I upload an image from my machine and click "Insert into Post". Then I publish the post. I don't know if the image is actually attached to that post though. I see the post in the database as well as the image as an "attachment" post_type. Is this a good direction to go in if all I want is a simple attach a single image to a post along with a title? Also, is there any way to simplify the media upload lightbox just for a certain post type? (Making it so the user doesn't need to know to click "Insert into Post" instead of "Save All Changes"?


Where and how to put inline js in pages

On the internet there are thousand of articles on how to insert external scripts using wp_enqueue_script(). Anyway i didn't find anything explanatory on how to add inline, `<script>` enclosed, scripts. I use to add them in the middle of the page code but i suppose it's not the most elegant way and there should be a better way, so that the script code is automatically moved in the head or the footer. Any ideas? Edit: I forgot the ' around `<script>` so it got cancelled. Now my question should be clearer


placeholder text in category form label

Is there a way to put a placeholder text in the category form label? Right now the label is empty and has a dropdown menu filled with categories. I want to make a dummy placeholder text which will be something to : CHOOSE THE CATEGORY!               <option value="<option value="<?php wp_dropdown_categories('exclude=34, selected=0'); ?>         </option>      Thanks in advance!


Hiding a php element from mobile browsers

I've stuck a static width content slider on my Wordpress sites front page. I'm using the Twenty Eleven theme with a small piece of code included into index.php to display the slider. Unfortunately because of how the theme handles mobile browsers, it causes the slider to push across the screen without the rest of the theme following it. So I was wondering if there was a way to hide the slider from mobile browsers? The code inserted into the theme is as follows:               <?php if (function_exists('rps_show')) echo rps_show(); ?>      And in context:                 <?php           get_header(); ?>

Todays' featured posts
       <?php if (function_exists('rps_show')) echo rps_show(); ?>

                  <?php if ( have_posts() ) : ?>                      <?php twentyeleven_content_nav( 'nav-above' ); ?>                      <?php /* Start the Loop */ ?>                 <?php while ( have_posts() ) : the_post(); ?>                          <?php get_template_part( 'content', get_post_format() ); ?>                      <?php endwhile; ?>      Any ideas?


How to update Wordpress custom SQL Select query for custom taxonomies so that syntax is correct?

I have a Wordpress website that written by third party web developer for version 2.9 before custom taxonomies were fully implemented. We have since upgraded to latest wordpress version 3.5.x. There is a SQL Select query that is generating a bunch of errors in the Wordpress error.log file. In this template, we have a few custom taxonomies in use. The one I am concerned about is listed below: (wp_term_taxonomy.taxonomy) jobs A key point here is that **not all Wordpress posts are using the taxonomy field`jobs`**. Therefore some post will not have any 'jobs' terms associated with it. Here is the error I see repeated most often               WordPress database error You have an error in your SQL syntax; check the manual that     corresponds to your MySQL server version for the right syntax to use near '))' at      line 9 for query             SELECT DISTINCT p.* FROM wp_posts p, wp_terms t, wp_term_taxonomy tt,       wp_term_relationships tr, wp_terms t2, wp_term_taxonomy tt2, wp_term_relationships tr2         WHERE p.id = tr.object_id           AND t.term_id = tt.term_id           AND tr.term_taxonomy_id = tt.term_taxonomy_id           AND p.id = tr2.object_id           AND t2.term_id = tt2.term_id           AND tr2.term_taxonomy_id = tt2.term_taxonomy_id           AND (tt.taxonomy = 'category' AND tt.term_id = t.term_id AND t.term_id = '22')           AND (tt2.taxonomy = 'jobs' AND tt2.term_id = t2.term_id AND t2.name IN ())          made by require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'),     include('/themes/generic/page.php')      Here is the code snippet from the PHP template file.               <?     else :     $playlist = 0; $jobs = null; $job = null; $terms = null;     $jobs = wp_get_object_terms( $post->ID, 'jobs', array('fields'=>'names'));     $term_count = 0;     foreach($jobs as $job) :         if ($term_count > 0) :             $terms .= ", '".$job."'";         else :               $terms .= "'".$job."'" ;         endif;         $term_count++;     endforeach;     $sql =  "             SELECT DISTINCT p.* FROM $wpdb->posts p, $wpdb->terms t, $wpdb->term_taxonomy tt, $wpdb->term_relationships tr, $wpdb->terms t2, $wpdb->term_taxonomy tt2, $wpdb->term_relationships tr2             WHERE p.id = tr.object_id             AND t.term_id = tt.term_id             AND tr.term_taxonomy_id = tt.term_taxonomy_id             AND p.id = tr2.object_id             AND t2.term_id = tt2.term_id             AND tr2.term_taxonomy_id = tt2.term_taxonomy_id             AND (tt.taxonomy = 'category' AND tt.term_id = t.term_id AND t.term_id = '22')             AND (tt2.taxonomy = 'jobs' AND tt2.term_id = t2.term_id AND t2.name IN ($terms))             ";     if (! $results = $wpdb->get_results($sql)) :     ?>       From what I can deduce from the logic in the PHP file, I see the variable `$terms` is created with a `NULL` value. A `foreach` loop is used to find any `jobs` terms and append them to the variable `$terms`. Next, the SQL Select query uses this variable in the last AND condition. If there are values in the `$terms` variable, then the SQL evaulates w/o any problems. But what happens if there are no values in the `$terms` variable? It is `NULL`. then the SQL generates a syntax error. How can this be rewritten to handle `NULL` values for the `$terms` variable when the SQL query is run? I hope I was complete enough in asking this question. Thanks ahead of time for any input.