Display custom field only if it has a value

this is the correct solution               <?php $meta_cat_name = get_post_meta( $post->ID, 'related blog articles', true ); if( !empty( $meta_cat_name ) ): $my_query = new WP_Query( array( 'category_name' => $meta_cat_name, 'posts_per_page' => 5, ) ); if ( $my_query->have_posts() ): while ( $my_query->have_posts() ) : $my_query->the_post(); ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?> <?php endwhile; endif; endif; wp_reset_query(); ?>      ----- original request and old code below ----- As I have yet to find a tutorial that does what I need I am using the More Fields plugin so that I can add partially filled custom fields/meta boxes on the edit posts page. These have the key already set so that the user only needs to enter a value - in this case a category name which will then display 5 posts from that cat. This works fine unless the post is published without a value being entered. This causes the published post to also list the 5 most recent posts. I assume its because it has been instructed that something is going there but only has half the info. So how do I make the chunk of code below only appear if a value has been entered? thanks James               <?php $my_query = new WP_Query(array(     'category_name'  => get_post_meta($post->ID, 'related blog articles', true),     'posts_per_page' => 5,     )); if ($my_query->have_posts()):  ?>          <?php while ($my_query->have_posts()) : $my_query->the_post(); ?>        <a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title(); ?>"><?php the_title(); ?>          <?php endwhile; ?>     <?php endif; ?>     <?php wp_reset_query(); ?>


Blocking Administrative Access to Authors and Subcribers?

I would like to turn off admin panel for authors and subscribers. Is there any secure way to keep them away from admin panel?


Placing the two most voted posts at the top (in a Wordpress site that uses the Vote it up plugin)?

I'm using the Vote it up plugin. Is there a way of placing the two most voted posts at the top? (Like in Youtube)? I'm not very sure if this is hard or easy to accomplish. **EDIT:** Someone posted a method in the Wordpress forums here, but Mike Schindel said: > This example is absolutely AWFUL. It may work but it's far more code than > you needs and may break on a future version of WordPress. I've been playing with Wordpress for a while but Im still a PHP beginner. Is there a way of fixing that code posted in the Wordpress forums? Or a better method?


Refactoring Wordpress to improve memory performance

I had a close look at Wordpress memory consumption. On my site, it seems that for each page hit 20MB of RAM gets allocated, just to prepare comfy environment for all the plugins to run in. I plotted it thusly: ![](http://zenka.net/roman/wordpress_memory_consumption.gif) There is no single spot to optimize, no single bad guy who eats most of the memory. Consumption is all spread over many many many php modules. How can we make Wordpress initialize its environment in memory only once, and then reuse it many times for each hit? I do not want to have slow PHP eat 20 MB at each user click - even on a server with lots of memory, it takes seconds to get all that work done. You would basically need read-only chunks of memory that can be reused. Also... why 20MB? Can anyone provide insights into this? Edit: Here is WinCacheGrind output on the Wordpress running on my development machine (vastly faster than the shared hosting). As you can see, it takes over a second of crunching just to produce the main page's HTML. Slow that down by shared hosting and you have a recipe for trouble. I picked the method that takes most of the time. How would you go about optimizing this? ![](http://zenka.net/roman/wordpress_cpu_usage.gif) Edit: Here are query statistics from this fantastic functions.php profiling tool.               Load: 12 queries - 532ms - 19.1MB - 43 cache hits / 53     Query: 15 queries - 563ms - 19.0MB - 72 cache hits / 86     Display: 21 queries - 705ms - 19.2MB - 234 cache hits / 257      Edit: Do you want to see something guaranteed to freak you out? Insert these lines at the end of index.php:               echo "<pre>\n";     print_r(get_defined_vars());     echo "</pre>\n";      I tried to count how many times is the current post's body stored in the memory. I counted 20 instances. Then I realized that PHP has reference counting, so the amount of copies reduced to just three: two seem to be in WP_Query, one in the object cache. I am investigating further. This is why I think WordPress is in need of refactoring targeting the memory issues. You can no longer blame its memory consumption on sheer complexity of what it does. It simply does a bunch of things _wrong_. Edit: After a day of trying to figure this out, here are my findings: 1) 88% of all memory comes from require or include or include_once type of calls: ![](http://zenka.net/roman/wordpress_memory_requires.gif) 2) The php file includes happen mostly during the first part of serving a request (not surprisingly), which is also where all the memory is eaten up: ![](http://zenka.net/roman/wordpress_includes.gif) 3) It is quite interesting to plot all the functions that are being executed during making a request. There are over 12000 calls total. I jittered them to make it more visible (the Level axis is basically depth of stack): ![](http://zenka.net/roman/wordpress_functions.gif) 4) The only way forward that I can think of is minimizing the amount of .php files included. If I split the functions per file they came from, you can see that many files are hit once or twice at most. We need a way how to skip those when they are not needed. For instance my remote database backup plugin gets loaded and registered, just to be never used at all. Here is the above plot split by file name: ![](http://zenka.net/roman/wordpress_functions_files.gif) I am offering a bounty worth all my reputation :) for refactorings that would lead to cutting my blogs memory footprint by 30% or more. Edit: I installed WP 3.1, here is comparison with the old version. ![](http://zenka.net/roman/wordpress_memory_usage_comparison.png) Blue is WP 3.1, red is 3.0.4. The new WP is faster, but also eats more memory. Here is a list by include file. ![](http://zenka.net/roman/wordpress_3.1_vs_3.0.4_mem_by_file.png) This let me realize just how much memory is eaten by "All In One SEO pack" - one avenue would be to use only a fraction of the plugin's functionality to get what I want. Also, my own plugins seem to be pretty bad. I would like to try conditional loading on e.g. comment.php (I disallow comments on my blog) and several others. I deleted all the deprecated code. I trimmed down kses.php to only load its global tables on demand. I simplified l10n (I do no localization), making its functions return the strings right away, without lookups. I am still far from the 30% mark I arbitrarily set up. Edit: I downloaded and enabled APC with default settings (32MB of opcode cache). Here is the comparison: ![](http://zenka.net/roman/3.1_without_with_apc.png) You can see that the code loading accelerated massively, and the code also takes less space in memory (probably because we deal just with opcodes, not the original source). The memory consumption is however still quite high.


Optimal code for two add_rewrite_rule's

I have two custom rewrite rules; after reading allot of great posts here I found a way to make them work. The question is this: **Is there a way to merge this code? I'm not sure that the way I wrote it is optimal:** In my functions.php I have the code of the 1st rule:               add_action('init', 'rewrite_cat'); // Rewrite Category         add_action('query_vars', 'rewrite_query_vars_cat');          add_filter('template_include', 'rewrite_template_include_cat');          function rewrite_cat(){              add_rewrite_rule( '([^/]+)/([0-9]+)/?', 'index.php?catname=$matches[1]&currentpage=$matches[2]', 'top' );         }         function rewrite_query_vars_cat($query_vars){                 $query_vars[] = 'currentpage';              $query_vars[] = 'catname';              return $query_vars;              }          function rewrite_template_include_cat($template){                  if (get_query_var('currentpage') || get_query_var('catname')){                         $template = locate_template(array('category.php'));             }                      return $template;              }      After, this is the code of the 2nd rule:               add_action('init', 'rewrite_perf'); // Rewrite Perf         add_action('query_vars', 'rewrite_query_vars_perf');          add_filter('template_include', 'rewrite_template_include_perf');          function rewrite_perf(){              add_rewrite_rule('cam/([^/]+)/([^/]+)/?', 'index.php?name=cam&sgcatname=$matches[1]&perf=$matches[2]', 'top');         }         function rewrite_query_vars_perf($query_vars){               $query_vars[] = 'sgcatname';              $query_vars[] = 'perf';              return $query_vars;              }          function rewrite_template_include_perf($template){                  if (get_query_var('sgcatname') || get_query_var('perf')){                         $template_perf = locate_template(array('single.php'));             }                      return $template;              }


User agent stylesheet distorting site

I am creating my first wordpress site from its html version. My html site is quite simple and seems to be looking correct in popular browsers. You can see it now at k-gayduk.ru. In my every day life I use Mozilla so I used it in this work too. Everything was fine: my wp site was looking exactly as its html copy. However, when I checked other browsers I found that user agent stylesheet distorted it in Google Chrome and in IE8 to very high extent as well. This means that wp influenced css styles in this specific way. I googled the problem, but found nothing except reset.css suggestion which was useless in the case. However I think I am not the first one facing the problem. Appreciate any help on the matter. I should say sorry as not able to show wordpress site because it is still on localhost.


qtranslate and content

I have the nostalgia theme from themeforest. I am trying to convert it to multilingual using qtranslate, which it does translate the links and the page names, but for some reason it brings me back the default content when I call the page. On function: `theme_get_content()` I have the following line:               $result["html"] = do_shortcode(get_the_content());      Which returns the default content. The page is called a little bit unorthodox though in the theme:               post_name) . '" class="nostalgia-menu-item nostalgia-menu-item-' . $post->post_name . '">' . get_the_title() . '';      that results in:                query_posts("name=" . $_GET["name"] . "&post_type=page");      How do I get qtranslate to work with the $result["html"] line? Any help?


Using preg_replace to separate gallery from the_content?

In a Wordpress theme, I need to separate a gallery from the rest of `the_content.` I think one could do that with get_the_content and preg_replace but it's a little beyond my skill level how to actually implement the solution. Here are the specifics. There's a gallery that looks like this:

              some <figures>

       the rest of the content      Is there some way I could get that gallery into a variable and put all the rest of the content in another variable. Then I could just echo the variables wherever I wanted, right?


Wordpress 3.8 - Dashboard 1 Column Screen Options

With the new Wordpress 3.8 under Screen Options they seem to have misplaced the "Columns" feature where you could put your widgets into 1 Column, 2 Columns, 3 Columns, or 4 Columns. My question is how to I force my Dashboard Widgets to only be 1 column, or in other words, take up the whole width of the screen versus just a portion of the screen?


In what order does WordPress load plugin files?

In what order are plugins loaded in WordPress? And within a particular plugin's folder, what order is followed for loading?


Access Serialized Post Meta Values

I am using the Humanmade fork of a custom meta box class, they give the ability to set up groups of repeatable fields, as such I have a post saved with post_meta as follows ... 6 meta_id entries in the post_meta table with the same key "course-dates", each of these keys has sub keys and values as serialized data if you will, example as follows ... a:2:{s:18:"course-dates-start";s:10:"11/25/2013";s:16:"course-dates- end";s:10:"12/20/2013";} How do I access these individual values or pull them all in and loop over them? Thank you _**_*EDIT* _*_ *** Managed the below to get all combinations echoing out, still unsure how to go about accessing specific values ....                           <?php                  $dates = get_post_custom ( $post->ID );                  $date = $dates['course-dates'];                 foreach ( $date as $d ) {                 $rpt = unserialize( $d );                 echo $rpt['course-dates-start'].' - '.$rpt['course-dates-end'];                 echo '<br/>';                 }                 ?>


Themes with variable width or single columns? I want to display source code

I've just set up a new wordpress blog, and as a developer I want to post some source code as well. Now I found the suitable plug-ins I need, and also a sleek theme, or so I thought. The problem is the width, it's just way too small. Even if I pick the option this theme has to only use a single column, it's still not wide enough. I guess my choices as a programmer wanting a theme to display my code correctly will be rather shallow, but there must be something I can do? Here's the first post I made on this blog: http://www.froginvasion.be/blog/?p=11


My plugin won't create table in wordpress 3.5

Hi I have this function to install the plugin and create database table:                   function sortresult_install()     {         //install sort_search_result options to the database         global $wpdb;         $sortsearchtitle_db_version = '1.0';         $table = $wpdb->prefix."sortsearchresult";         $structure = "CREATE TABLE IF NOT EXISTS $table (id INT(9) NOT NULL AUTO_INCREMENT,order_valuex VARCHAR(5) NOT NULL,UNIQUE KEY id (id));";         require_once(ABSPATH . 'wp-admin/includes/upgrade.php');         dbDelta($structure);         //Save database version         update_option("sortsearchtitle_db_version", $sortsearchtitle_db_version);         // Insert default sorting setting that is ascending         $wpdb->query("INSERT IGNORE INTO $table(order_valuex) VALUES('ASC')");     }         And this is the construct function:               function __construct()     {              //Register activation hook         register_activation_hook(__FILE__,array(&$this,'sortresult_install'));              //Add menu hook         add_action( 'admin_menu', array(&$this,'sort_searchresults_menu'));              //Update function hook         add_action('plugins_loaded', array(&$this,'sortsearchtitle_update_db_check'));              //Run the search function         add_action('pre_get_posts',array(&$this,'sort_searchresult_by_title'));          }      Any ideas why the above functions won't create the database table? I am updating this plugin for Wordpress 3.5.Thanks.


Exclude an array

I'm moving edit post dashboard to front end. So here is a case, I have to queries, one for product attachments and other for ALL. Now, I want to exclude product attachments from ALL attachments query here is an example how to exclude post thumbnail from WordPress Codex:               <?php          $args = array(         'post_type'   => 'attachment',         'numberposts' => -1,         'post_status' => null,         'post_parent' => $post->ID,         'exclude'     => get_post_thumbnail_id()         );          $attachments = get_posts( $args );          if ( $attachments ) {         foreach ( $attachments as $attachment ) {             echo apply_filters( 'the_title', $attachment->post_title );             the_attachment_link( $attachment->ID, false );         }     }          ?>      before that, I have a query of all products, so can `exclude` take array argument? For example with my code               $mediaArgs = array(         'post_type'         => 'attachment',         'post_mime_type'    => 'image',         'numberposts'       => -1,         'post_status'       => null,         'post_parent'       => $current_post,     );     $MediaAttachments = get_posts($mediaArgs);      Can I then foreach this and save MediaAttachment->ID inside some array and exclude put it next tu `exclude`? In my theory it should work as usual, but no matter how I tried, it does not work.


different levels of nested comments per page

I am working on a wordpress site that usually allows three levels of nested comments. But I would like for (at least) one specific page to allow only one level of comments => no nesting. How can I do that? edit: requested clarification: I can identify this page by the used page- template.


?login=failed only attached to URL under certain circumstances

I am using this snippet to redirect failed logins to my custom page...               add_action( 'wp_login_failed', 'my_front_end_login_fail' );  // hook failed login          function my_front_end_login_fail( $username ) {        $referrer = $_SERVER['HTTP_REFERER'];  // where did the post submission come from?        // if there's a valid referrer, and it's not the default log-in screen        if ( !empty($referrer) && !strstr($referrer,'wp-login') && !strstr($referrer,'wp-admin') ) {           $pos = strpos($referrer, '?login=failed');             if($pos === false) {                 // add the failed                 wp_redirect( $referrer . '?login=failed' );  // let's append some     information (login=failed) to the URL for the theme to use             }             else {                 // already has the failed don't appened it again                 wp_redirect( $referrer );  // already appeneded redirect back             }              exit;        }     }      This works brilliantly but only if the users actually fails the login process ie; they enter an incorrect username or password. If the user does any of the following then it doesn't work....   * Enters no username   * Enters no password   * Enters nothing in either field The URL returned does not have ?login=failed attatched to it which I guess is the reason the snippet isn't catching it. Anyone any ideas?


Custom SQL query ORDER BY term_order

I have custom taxonomy that list terms under "series" that contain posts that are also present in terms under "media_type" and where media_type is term_id 16. I want to order the list by the term_order column in the terms table but it is not working. What am I doing wrong? Thanks!                   $q_result = $wpdb->get_col("SELECT DISTINCT {$wpdb->terms}.name FROM {$wpdb->terms}                 INNER JOIN {$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_id = {$wpdb->terms}.term_id                 INNER JOIN {$wpdb->term_relationships} ON {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id                 WHERE {$wpdb->term_taxonomy}.taxonomy = 'series' AND {$wpdb->term_relationships}.object_id IN (                 SELECT object_id FROM {$wpdb->term_relationships}                 INNER JOIN {$wpdb->term_taxonomy} ON {$wpdb->term_taxonomy}.term_taxonomy_id = {$wpdb->term_relationships}.term_taxonomy_id                 WHERE {$wpdb->term_taxonomy}.taxonomy = 'media_type' AND {$wpdb->term_taxonomy}.term_id = '16'                 ORDER BY {$wpdb->terms}.term_order     );");


What is the fastest way to generate a unique id number when registering a user

I have a client who wants to register users and give them a unique ID number when they complete registration. (Kind of a member number sort of thing) Can I just setup the WP member table to start id numbers in the high 10 digit range? User experience would be:   1. user would visit the site    2. user would register    3. WP would issue an 10 digit id number


Rewrite rules goes away

I have a strange issue. The custom rewrite rules are registered correctly in my plugin activation hook. But, if I go to the permalinks settings page and clic on "Save changes" I lost the rewrite rules registered by my plugin. I have to deactivate and reactivate my plugin to get the custom rewrite rules back again. Here my activation and deactivation hook               register_activation_hook( __FILE__ , 'properties_plugin_activation' );     function properties_plugin_activation(){         create_property_post_type();         create_properties_taxonomies();         //add custom rewrite rules and custom vars before flush_rewrite_rules()         properties_add_rewrite_rules();         flush_rewrite_rules();     }          register_deactivation_hook( __FILE__ , 'properties_plugin_deactivation' );     function properties_plugin_deactivation(){         flush_rewrite_rules();     }      Here my rewrite rules:               // Register a new vars to be used in the rewrite rules     function properties_add_query_vars( $vars) {       $vars[] = "action"; // name of the var as seen in the URL       return $vars;     }     add_filter('query_vars', 'properties_add_query_vars');          // Add the new rewrite rules     function properties_add_rewrite_rules() {     add_rewrite_rule( 'properties/search/?$' , 'index.php?post_type=properties&action=search' , 'top' );     $config = new PConfig();     foreach($config->taxonomies as $taxonomy){       add_rewrite_rule( 'properties/'.$taxonomy["slug"].'/(.+)/?$' , 'index.php?post_type=properties&'.$taxonomy["slug"].'=$matches[1]' , 'top' );     }     }


Pop-up successful message in Fancybox?

I have a very long page and CF7 at the bottom. The problem is that when/if the user completes the fields and press Submit, the error or successful messages appear near the Submit button, but at the bottom, whilst the page scrolls up because of the refresh. Is there a way I can show this message in a Fancybox pop-up/modal window, that would be closed after the user will click on it or outside?


Any available action to add content before and after sidebar ?

Hiz As the title says, i am looking for inserting a function's output before sidebar's first widget, and one in the end after teh last widget, is it possible?   thanks in advance.


How to change amount of categories listed on dashboard?

I have 100+ categories & sub-categories for a site I'm working on.   How can i change the amount displayed in the list of categories (default 20 per page) on the dashboard?


How does wordpress multisite manage subdomains?

I have a Wordpress multisite installed, and would like to understand how the subdomains actually are managed, ie how does my wordpress multisite knows where to find the files/data when a browser request URL `user1.domain.com` ? I checked the DNS A record and see only the wild card. I checked the .htaccess, and it looks as follows:               RewriteEngine On     RewriteBase /          # Protect the htaccess file     <Files .htaccess>     Order Allow,Deny     Deny from all     </Files>          # Protect wpconfig.php     <Files wp-config.php>     Order Allow,Deny     Deny from all     </Files>          # Disable directory browsing     Options All -Indexes          RewriteRule ^index\.php$ - [L]          # uploaded files     RewriteRule ^files/(.+) wp-includes/ms-files.php?file=$1 [L]          RewriteCond %{REQUEST_FILENAME} -f [OR]     RewriteCond %{REQUEST_FILENAME} -d     RewriteRule ^ - [L]     RewriteRule . index.php [L]      so I think the .htaccess does not manage the subdomain, or does it? so then, how does my wordpress multisite knows where to find the files/data when a browser request URL user1.domain.com ?


Rewrite category list as an if / else statement

I have written this script to list the neighborhood associated with a post:
What's Happening in:<?php     foreach((get_the_category()) as $childcat) {       if (cat_is_ancestor_of(12, $childcat)) {         echo 'cat_ID).'">';         echo $childcat->cat_name . '';     }}     ?>
      It works great. But I need to rewrite this to be an if / else statement, in the event that there is no neighborhood assigned to a post that the "What's Happening In" part would not appear. My PHP isn't super strong, and I'm not sure how to restructure the code so that it is an effective if / else. Any help is appreciated.


How do you create an attachment ID with Ajax submit? No page refresh

I know I have done this before, with a frontend post form anyways that used Ajax to send the form data to a php script that used wp_insert_post() then redirected to that post after a success message displayed, but I can't figure out how to do it with attachments. What I am trying to do is a bit hard to explain. Let me try. I have a metabox, that you can add/remove attachments using jquery to add another set of inputs, or remove them, and inturn delete that file from your site. That stuff works. What I would like to do is, when you add a new set of inputs, fill in the info, select the image file to upload, then click Save for that set of inputs (each set has it's own save button) the save button has an Ajax script that sends the data to post.php or whatever happens when you click the Publish button. If i fill in a couple attachments fields and click Publish, my action for 'save_post' is used to save that data. I want to create a function that uses admin-ajax.php and a custom hook. Currently i have a delete function that uses admin-ajax.php to delete the attachment file from the post and the media library. How can I create a function that adds the file. I'm so confused lol.


InDesign to WordPress workflow

I'm working on a project for a monthly InDesign-based magazine that enables them to put their content online via WordPress. The current workflow is either:   1. Copy/pasting from InDesign to a Word document (by the magazine staff with access to InDesign) and then copy/pasting from Word to the various fields in WP (by an intern without access to InDesign but access to Word)   2. Create a CSV that contains all of the post data and use CSV Importer to import to WordPress. **Thus, I have two questions:**   1. Is there a better InDesign => WordPress workflow than the ones I discuss above?   2. If not, what a good way of pasting a large amount of multi-line HTML data into a spreadsheet? Massive gratitude to anyone who can help with this. Edit: The solution I'm looking for involves **as little InDesign-side work as possible**. I'll spend a month writing an XMLRPC plugin for InDesign from scratch or something similarly stupid if it means not having to retag page elements for a decade worth of issues -- so long as that really is the best possible route.


WordPress (TinyMCE) not removing script tags

We have an installation of WordPress (3.9) where TinyMCE is _not_ removing script tags (in posts etc). This isn't correct, I believe?! I think a developer that worked on the project possibly changed something when trying to sort something out, but I can't see where at the moment - what are the obvious places to look? Thanks, Toby **Update** : This seems to happen on a fresh WP3.9 install. In the text tab of the post editor I can enter script tags, which persist _unless_ I switch to the visual editor and save. I don't think that this is correct, I think that WP is supposed to strip script tags out...or did I miss something?


merging terms programmatically while maintaining the count

This question is all about finding out the best way to handle merging similar terms. Let's say you have 10 posts tagged as `Barack Obama` and 20 posts tagged as `Obama`. and you want to group them all under `Barack Obama` and get 30 posts for it and get rid of the tag `Obama`. Surely, there will be some changes to the wp_terms, wp_term_taxonomy, wp_term_relationships. But in doing so, which APIs should be used and under which order so that while one tag is being gotten rid of, all the posts associated with it will be tagged as the other one.


If statement to check if post has image

I have the following code. When There is only one image in the backend, the second image shows up with a little question mark instead of nothing. I am looking for a way to check if the image exists first and if so run the code and if not don't.               <?php $image = wp_get_attachment_image_src(get_field('post_image1'), 'thumbnail'); ?>             <img src="<?php echo $image[0]; ?>" alt="<?php get_the_title(get_field('post_image1')) ?>" />             <?php $image = wp_get_attachment_image_src(get_field('post_image2'), 'thumbnail'); ?>             <img src="<?php echo $image[0]; ?>" alt="<?php get_the_title(get_field('post_image2')) ?>" />


Overide Gallery Default Link to Settings

Is there way to control the gallery default “Link to” setting? Using the `image_default_link_type` filter within a `functions.php` file works on inserting single images into posts but it doesn't seem to have any effect on galleries...


Can you link custom post types to pages?

The reason i ask is because when i create pages they don't insert the usual name of the post type like CPT's do. For example if i create a page called `toyota` the URL would be `http://domain.com/toyota`, but if i created a custom post type to Enter all the makes one page with custom links to specific pages within my site and say that CPT was called `Cars` then the URL would look like this `http://domain.com/cars/toyota` and therefore wouldn't properly link to the page. Is there any way to work around this?


Display only the most recent sticky post, display other posts in chronological order

I want to display only the most recent sticky post at the top of the TwentyEleven page, and display the rest of the posts in chronological order, no matter whether they are sticky or not. I tried to find. solution here: http://codex.wordpress.org/Sticky_Posts But it doesn't seem to have what I need. Could someone please help to formulate the correct statement? Thank you!


How to properly prefix blog post URL's

I want to prefix my blog posts with `/news/` and changing my Permalinks to `/news/%postname%` seems to do the trick. However, I also have a few custom post types and for some reason those URL's are now also prefixed with `/news/`. Of course this is not what I want. How can I make sure that only the out-of-the-box Wordpress post type is prefixed with `/news/`?


@font-face Paths Don't Seem to be working properly

I'm having issues with my @font-face code in my style.css file for a theme. I've already tested the theme as an HTML site, and the paths are the same. The style.css file uses a relative path to a fonts folder like so: `@font-face{               font-family:'Fertigo_PRO-webfont';              src:url('./fonts/Fertigo_PRO-webfont.eot');               src:url('./fonts/Fertigo_PRO-webfont.eot?iefix') format('eot'),                   url('./fonts/Fertigo_PRO-webfont.woff') format('woff'),                   url('./fonts/Fertigo_PRO-webfont.ttf') format('truetype'),                   url('./fonts/Fertigo_PRO-webfont.svg#webfont') format('svg');          }      And I call it in the stylesheet for an id:               #masthead{              background-image:url('mastgrad.png');              background-repeat: repeat-x;              height: 250px;              width:100%;              padding:20px 0 0 0;              margin:0;              }      The font isn't displaying where it's supposed to, even though I never had an issue with this before I put this on my LAMPP server for development. It seems to replicate in Firefox and Chrome, though I haven't tested it elsewhere.


Media uploader & manager: add/remove class on image with checkbox

This seems like it should be fairly simple, but I'm drawing a blank on it: Have a checkbox in the media uploader and media manager that, when checked, adds a CSS class name to the image. It should stay checked. The kicker is I can't use post meta to store the checked or not checked status. It's a long story, but basically the requirements of the project I'm working on say that setting a global meta key/value on the image is not OK. I figured out how to add the checkbox and set/unset post meta with it:               /**      * Add a checkbox to media uploader & manager to mark an image as a Profile Image      *      */          function my_select_profile_image( $form_fields, $post ) {        $is_profile_image = (bool) get_post_meta($post->ID, '_is_profile_image', true);        $checked = ($is_profile_image) ? 'checked' : '';              $form_fields['is_profile_image'] = array(         'label' => 'Profile Image?',         'input' => 'html',         'html' => "<input type='checkbox' name='attachments[{$post->ID}][is_profile_image]' id='attachments[{$post->ID}][is_profile_image]' {$checked} />",        'value' => $is_profile_image,         'helps' => 'Checking this box will add profile image styling to the image & caption.'         );     return $form_fields;     }     add_filter( 'attachment_fields_to_edit', 'my_select_profile_image', null, 2 );          /**      * Update image meta based on Profile Image checkbox status      *      *      */     function my_save_profile_image($post, $attachment) {         if( isset( $attachment['is_profile_image'] ) )             update_post_meta( $post['ID'], '_is_profile_image', true );              if( !isset( $attachment['is_profile_image'] ) )             update_post_meta( $post['ID'], '_is_profile_image', false );         return $post;     }     add_filter( 'attachment_fields_to_save', 'my_save_profile_image', null, 2 )      But with post meta off the table, I'm at a loss on how to do this.


Loop.php vs looping inside template file

What is best practice for WP with regard to using loop.php (loop-single.php, etc) versus looping inside the template file? Does it matter with regard to efficiency or ?


How to perform unit testing on proposed patches in Trac?

I was looking for some insight and good resources on how to correctly perform unit testing on proposed WordPress patches in the Trac and how to accurately report the results from the testing. I'm new to this and have read through the resources located in this WPSE question. I myself would really like to learn how to do this and do so with a real-world bug, like this Trac ticket #5809. I guess after reading through the resources in the previously mentioned WPSE question my short coming is that I do not understand how I would setup the proposed testing for the proposed patch. **Update:** I'm still searching for resources and currently watching this video on WordPress unit-testing.


Add post thumbnail from external image with plugin

I'm currently writing a plugin modifying the post content with the wp_insert_post_data filter. While doing that I would also like to add a post thumbnail using an external image url. It doesn't really matter if the image is hotlinked or copied to my wordpress installation. Anyone knows how to go about that?


Wordpress Post HTML after Posting

I am writing a plugin for WordPress, one of the tasks I need to-do is send the HTML content of a new post to an e-mail address at the time of posting, I know I can use certain hooks to fire after the post has been saved, but is there a way to get the full HTML content of the new page/post with the theme applied? I have custom fields within the post so ideally I would like to get the whole post from the URL rather then reconstructing all the fields to then send in HTML. Any help would be appreciated! Thanks


Page appearing two times in the frontpage? How do I completely remove that page from the frontpage?

I have this Wordpress website I'm working on as third party. I have to give this Wordpress its final touch. There is a Page named _Impressum_ and it's appearing two times in the frontpage, I need to remove it completely from the frontpage and let only the products and the slideshow appear. Any help would be appreciated. This is the website. When you scroll down you can notice the double _Impressum_


PHP memory friendly alternative to get_posts()

I was running into memory issues with this: `get_posts( array( 'posts_per_page' => '-1', 'post_type' => array( 'product', 'product_variation' ) )` (there are thousands of results) just trying to get a list of all post IDs. The below code grabs 10 products at a time, to hopefully avoid any memory limits. It seems to work OK but there is probably a more elegant solution. https://gist.github.com/dtbaker/acd15e542d98bff68034               $product_page = 1;     $product_per_page = 10;     $product_query = new WP_Query( array(         'posts_per_page' => $product_per_page,         'paged'          => $product_page,         'post_type'      => array( 'product', 'product_variation' ),     ) );     $product_ids = array();     while($product_query->have_posts() ) {         $product_result = $product_query->next_post();         if(!$product_result){             // get the next lot of results.             $product_page++;             $product_query = new WP_Query( array(                 'posts_per_page' => $product_per_page,                 'paged'          => $product_page,                 'post_type'      => array( 'product', 'product_variation' ),             ) );         }else{             $product_ids[] = $product_result->ID;         }     }     print_r($product_ids);      I would love to know if there's a better way to do this "10 products at a time" query. Thanks!


How to uniquely identify queries?

Today I was thinking about how to differentiate queries, mainly to create an unique identifier. In the process I played around a bit, see below code. The main idea is to do it depending on the `$query` or `$query_vars` property of `WP_Query`. There is actually already a property `query_vars_hash`, but it's created fairly early with a subset of the vars and isn't of help to distinguish queries that happen on the same request. The following is what I have so far:               add_action( 'pre_get_posts', 'unique_query' );     /**      * unique_query      *      * Create unique identifier      *      */     function unique_query( $query ) {         global $wp_query;         $query_hashes = array();              if ( is_admin() ) return;              /**          * Skip additional cases          */         /**         if ( ! isset( $query->query['post_type'] )             || empty( $query->query['post_type'] )             || $query->query['post_type'] == 'nav_menu_item'             || $query->is_main_query()         ) {             return;         }         /**/              /**          * Debug stuff          */         /**         echo '
';             print_r( $query );             print_r( $wp_query );             print_r( $query->query );             print_r( $wp_query->query );             print_r( $query->query_vars );             print_r( $wp_query->query_vars );         echo '
';         /**/              /**          * Setup query hashes array          */         $query_hashes[ '$wp_query->query_vars_hash' ]  = $wp_query->query_vars_hash;         $query_hashes[ 'uhash_$wp_query->query_vars' ] = md5( serialize( $wp_query->query_vars ) );         $query_hashes[ '$query->query_vars_hash' ]     = $query->query_vars_hash;         $query_hashes[ 'uhash_$query->query_vars' ]    = md5( serialize( $query->query_vars ) );         $query_hashes[ 'uhash_$query->query' ]         = md5( serialize( $query->query ) );         $query_hashes[ 'uhash_$wp_query->query' ]      = md5( serialize( $wp_query->query ) );              /**          * Print query hashes array          */         echo '
';             print_r( $query_hashes );         echo '
';          }         Which produces the following exemplary output:               /* Main query */     [$wp_query->query_vars_hash]  => ffb3c63f9b858ab4882d8e9ed20fce67     [uhash_$wp_query->query_vars] => ffb3c63f9b858ab4882d8e9ed20fce67     [$query->query_vars_hash]     => ffb3c63f9b858ab4882d8e9ed20fce67     [uhash_$query->query_vars]    => ffb3c63f9b858ab4882d8e9ed20fce67     [uhash_$query->query]         => 40cd750bba9870f18aada2478b24840a     [uhash_$wp_query->query]      => 40cd750bba9870f18aada2478b24840a          /* Query of wp_nav_menu */     [$wp_query->query_vars_hash]  => ffb3c63f9b858ab4882d8e9ed20fce67     [uhash_$wp_query->query_vars] => 59e1dad0ba690eed5e758fbf15cda702     [$query->query_vars_hash]     => c5a049c558df9cf4cfd14dad179a97e8     [uhash_$query->query_vars]    => c5a049c558df9cf4cfd14dad179a97e8     [uhash_$query->query]         => d4226d11be5a53e8b44d5b85db43e8b0     [uhash_$wp_query->query]      => 40cd750bba9870f18aada2478b24840a          /* Front/home query */     [$wp_query->query_vars_hash]  => ffb3c63f9b858ab4882d8e9ed20fce67     [uhash_$wp_query->query_vars] => 59e1dad0ba690eed5e758fbf15cda702     [$query->query_vars_hash]     => 712b303f79eef3c8b5928d4ed8acfe2f     [uhash_$query->query_vars]    => 712b303f79eef3c8b5928d4ed8acfe2f     [uhash_$query->query]         => b7ac5bdfe084209f0142d7ab3aa0683e     [uhash_$wp_query->query]      => 40cd750bba9870f18aada2478b24840a         As you can see the only candidates for a distinct determination are `$query->query_vars_hash`/`uhash_$query->query_vars` or `uhash_$query->query`. Of course in this example the first and second one are the same, but in the future there might be the need to do things not covered by the existing `query_vars_hash` property. Besides you have to do it yourself to be sure. So the question would be, firstly, _is this a reasonable approach to uniquely identify queries?_ Or am I missing something, especially, is there maybe a better one, so, secondly, if someone has input, I'm interested. * * * **Edit:** @G.M. is pretty much right about everything that was implied with the problem raised. I actually had in mind to add this information, just hadn't enough time at the time posting, now it would just be redundant, but I wanted to confirm the fact.


Taxonomy Terms - Orderby Custom Value

I have a custom value which is being stored as `term_group` but in the admin panel I would like to order them by that term group. I'm able to sorta do this through this function, but there's a problem:               function change_term_order( $args, $taxonomies ) {         if ( is_admin() && 'tax_products' !== $taxonomies[0] )             return $args;              $args['orderby'] = 'term_group';         $args['order'] = 'ASC';              return $args;     }     add_filter( 'get_terms_args', 'change_term_order', 10, 2 );      This only works if the user sorts on one of the columns, not on initial page load. I tried to modify the filter to be `get_terms` but it just errored out half way down the page. Does anybody know the correct filter to change ordering categories and taxonomy?


Print child category slug nicename

I want to print (display) the child category slug, so I can use it in a dynamic url, on categories pages. So If I am on the category www.example.com/category/main-category/child-category Example: www.example.com/category/games/board-games In the sidebar I will have a link Updates from Board Games so I need the code to simply display child-category slug, in this case is "board-games", and child category name, in this case is "Board Games" on post pages it's simple, I have this code and it's working (maybe someone will find it useful)               <?php $cat_slug = get_the_category(); ?><a href="<?php echo get_bloginfo('url') . "/updates-from-" . $cat_slug[0]->category_nicename; ?>" > Updates from '<?php echo $cat_slug[0]->cat_name . "";?>'      thank you for your help!


How do I add customize_register action AFTER adding a custom taxonomy

customize_register only works with the customize_register hook, and regardless of what hook I use to add the custom taxonomy, it always happens after customize_register. (I want to loop through the list of terms from my custom taxonomy to create categories and custom options for each term) EDIT: This is the watered-down code in question of my template functions file:               register_taxonomy( 'brand', $object_types, $args );     add_action( 'muplugins_loaded', 'brand', 0 );     // ????? What Hook can I use here^ that will run before the 'customize_register' hook ????? //          function iartz_customize_register( $wp_customize ) {         $brands = get_terms('brand');         foreach($brands AS $brand){             //Add color options for each term of taxtonomy 'brand'         }     }     add_action( 'customize_register', 'iartz_customize_register' );


Stylesheet from wp_enqueue_style is overwritten by plugin

I am using Font Awesome on my theme.               wp_enqueue_style('fontawesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css');      I am using another plugin that uses Font Awesome, but its using an old version.               wp_enqueue_style( 'fontawesome', '//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.min.css', array(), MSI_VERSION, 'all' );      The two methods are using the same handle so only one gets rendered in the HTML... and that is the plugin's old version. I could change my handle but then two Font Awesomes would be loading. I could hack the plugin, but, EWWW! How do I get my version of Font Awesome to take priority and load?


wp_dropdown_categories not returning value

Update _*_ After enabling Debug, I receive the following error:               Notice: Undefined property: stdClass::$id in /home/buffalot/public_html/beta/wp-includes/category-template.php on line 1096      I have the following code to generate a category dropdown. For some reason, no value is being returned for the category and I'm not sure what might be causing this (theme conflict maybe?)               <form action="<?php bloginfo('url'); ?>/" method="get" style="display:inline;">         <?php             $select = wp_dropdown_categories('show_option_all=All Activities&show_count=1&orderby=name&echo=0&taxonomy=category');             $select = preg_replace("#<select([^>]*)>#", "<select$1 onchange='return this.form.submit()'>", $select);             echo $select;         ?>     </form>      The output (using chrome inspect element) shows the following..               <select name="cat" id="cat" class="postform" onchange="return this.form.submit()">         <option value="0" selected="selected">All Activities</option>         <option class="level-0" value="">Running  (5)</option>         <option class="level-0" value="">Uncategorized  (2)</option>     </select>


WP query taxonomies not the same as output

I'm trying to build a custom query and I need to include the current category ID. I previously had the WP_Query args as:               Array     (         [post_status] => publish         [posts_per_page] => -1         [post_type] => courses         [cat] => 70      When I output SQL result behind this argument query using `$query->request;` the taxonomies read as 95 and 203, instead of 70?               SELECT wp_posts.* FROM wp_posts                  INNER JOIN wp_term_relationships ON (wp_posts.ID = wp_term_relationships.object_id)                  INNER JOIN wp_postmeta ON (wp_posts.ID = wp_postmeta.post_id)                  INNER JOIN wp_postmeta AS mt1 ON (wp_posts.ID = mt1.post_id)                  INNER JOIN wp_postmeta AS mt2 ON (wp_posts.ID = mt2.post_id)                  INNER JOIN wp_postmeta AS mt3 ON (wp_posts.ID = mt3.post_id) WHERE 1=1                  AND ( wp_term_relationships.term_taxonomy_id IN (95,203)      Can anyone tell me how/why this is happening and what I need to do to find 95,203 from this initial 70 so that I can also build this query manually? Many thanks


https redirect hell (adding www)

I migrated my multisite wordpress website (www.example.com) to a subdomain (dev.example.com) to work on some big changes. Of course, I changed _siteurl_ and _home_ in the DB for all sites. The problem is whenever I go to https://dev.example.com I get redirected to a non existing https://www.dev.example.com I can't figure out where this www is coming from (and it is not .htaccess). This is driving me nuts. After hours of google, I finally decided to reach out for help. Thanks!


Admin and Toolbar on the bottom, how to dropup menus?

I placed my adminbar in the dashboard and front end on the bottom, and I am having trouble on figuring out how to make the dropdown menus dropup. Also when the site is viewed in landscape on mobile the adminbar stays on the bottom and on top of the content which is great. But when I flip the phone normal the admin bar stays in 1 spot when I scroll down. It doesnt stay on the bottom and on top of the content. I'm trying to fix these annoyances.


How to create custom 401, 403 and 500 error pages?

When a 404 error is encountered, a 404.php template file can be used to render a custom error message. This is documented in the Template Hierarchy article. My aim is to create custom error pages for 401, 403 and 500 errors. I've tried creating 401.php, 403.php and 500.php files in my theme's directory but this doesn't work. How can I create custom 401, 403 and 500 error pages in WordPress?


Create new Wordpress post [wp_insert_post] based on results of a WP_Query

I have a a page where users can filter a list of custom post-type posts based on the "Ultimate WP Query Search Filter" plugin. Results are passed to a div on the page using AJAX from there users can enter a quantity into each of the results. What I need to happen is that once a user has entered a quantity into the quantity field all the information from that post, plus the quantity need to be used to create a new post in a different custom post type. [Currently this is done a result by result basis, but if its possible to have 1 "add" button at the end that loops through each result and creates a post for each that would be first prize - but we are ok with an "Add" button per result] I am using the following code to create the new posts:               <?php           $order_productcode = get_field('product_code', $query->ID);         $order_productdesc = get_field('product_description', $query->ID);         $order_productcost = get_field('selling_price', $query->ID);      ?>                <?php      if(isset($_POST['new_post']) == '1') {     $post_title = $_POST['post_title'];          $new_post = array(           'post_type'       => 'order-items',           'ID'              => '',           'post_author'     => $user->ID,            'post_title'      => $post_title,           'post_status'     => 'publish'         );          $post_id = wp_insert_post($new_post);          add_post_meta($post_id, 'linked_order_id', 379, true);     add_post_meta($post_id, 'product_code', $order_productcode, true);     add_post_meta($post_id, 'product_description', $order_productdesc, true);     add_post_meta($post_id, 'quantity', '1', true);     add_post_meta($post_id, 'unit_price', $order_productcost, true);          $post = get_post($post_id);     wp_redirect($post->guid);} ?>            And then the following code to trigger the form:               <form method="post" action="">      <input type="text" class="orderresult_qty" name="post_title" size="45" id="input-title"/>     <input type="hidden" name="new_post" value="1"/>      <input class="subput round" type="submit" name="submit" value="Add"/>      On a single page or hard-coded page example this works perfectly, but when the code is placed inside of the Wordpress loop, nothing happens when the item is submitted. No error is displayed and the item is not created. I am having problems pasting the full code, so here is a link to a GIST where you can see the full code inside the loop (generated inside the function.php file) https://gist.github.com/stankobrin/bb0b7d38dbbe1fd3b83e **This is quite urgent so any assistance in getting this working will be appreciated!**


get_posts works but new wp_query doesn't

I was told that `get_posts` is a very bad function to use that that making a `new WP_query` is absolutely better. My problem is that my `get_posts` code works but when I tried turning it into a `WP_query`, it returns blank results. Assistance please? :( I'd really love to get this to work because I suspect that the get_posts that I have on index.php / category-9.php are interfering with the normal loop on category.php Get_posts version:               <?php if ( have_posts() ) : while ( (have_posts() ) ) : the_post(); ?>

<a href="<?php the_permalink();?>"><?php the_title(''); ?>
              <?php         $args = array(             'post_type' => 'attachment',             'post_mime_type' => 'image',             'numberposts' => 4,             'post_status' => null,             'post_parent' => $post->ID,             'orderby' => name,             'order' => ASC         );         $attachments = get_posts($args);         if ($attachments) {           foreach ($attachments as $post) {             setup_postdata($post); ?>               <a class="postpreview" href="<?php echo get_permalink($post->post_parent) ?>"><?php echo wp_get_attachment_image($post->ID, thumbnail) ?>           <?php };          }; ?>

     <?php endwhile; endif; wp_reset_query(); ?>      WP_query version:               <?php if ( have_posts() ) : while ( (have_posts() ) ) : the_post(); ?>

<a href="<?php the_permalink();?>"><?php the_title(''); ?>
              <?php         $args = array(             'post_type' => 'attachment',             'post_mime_type' => 'image',             'numberposts' => 4,             'post_status' => null,             'post_parent' => $post->ID,             'orderby' => name,             'order' => ASC         );         $attachments = new WP_Query($args);           while ($attachments->have_posts()) : ?>               <a class="postpreview" href="<?php echo get_permalink($post->post_parent) ?>"><?php echo wp_get_attachment_image($post->ID, thumbnail) ?>           <?php endwhile; wp_reset_postdata(); ?>

     <?php endwhile; endif; ?>


Disabled visual editor and Wordpress keeps adding line-breaks to my code

I've disabled visual editor, so this can't be an issue with switching between the two different editors as I've seen in many questions related to this same issue. I'm pasting code into the page like:
Something

Something

Something

Something
      When I save it, this is how it appears in the editor. When I view the page, line breaks. I've confirmed by viewing the source that it's rendering:
Something

Something

Something

Something
      When I go back into the editor, it still appears on a single line, but somewhere WordPress is messing with my code (probably around the same time it's removing my `<p>` tags) and it's very frustrating. How can I get it to stop doing this? I'm using twentyfourteen as my base theme so maybe there's something in the theme causing this behavior. This is only my second week using WordPress so I don't have an answer for that one. **Edit:** So I've been trying different methods of altering the html to get rid of inline-block white-space bug and just came across another WordPress curiosity. When trying something like:
Something

Something

Something

Something
      Which is another way to get rid of this error. Wordpress renders:
Something

Something

Something

Something
      Did Wordpress just have some kind of mental breakdown? Surely it can't be so stupid that it doesn't even realize that a) it would be ridiculous to alter the code to that and b) you can't even have `<p>` as direct children of `<ul>` elements. It's hard to imagine such common knowledge slipped past the WordPress developers' minds when they came up with the fantastic idea they should be altering people's code. They should have at least made sure they're altering the code to something valid.


Issue on CPT Custom Menu Position in WP

I have Two CPT as "Dress" and "Casual" and I would like to position them close to each other exactly after the "Dashboard" in the Menu. I have this code in my custom post type for both:               'menu_position'       => 2      how ever the result is displaying as: ![enter image description here](http://i.stack.imgur.com/6LX3D.png) the "Post" positions after the "Dress"! can you please let me know why this is happening and how I can keep all CPT after each other before the "Post".(I have 5 Custom Post Type) Thanks


Create a 'single' page for a Custom Post Type

Ok, I installed the Custom Post Type UI plugin and create one. I then added a new post to it. In my theme, i have a piece of code like this:               <?php          $loop = new WP_Query( array(              'post_type' => 'case studies',   /* edit this line */             'posts_per_page' => 15 ) );     ?>          <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>                <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" >             <?php the_post_thumbnail('thumbnail'); ?>         </a>          <?php endwhile; ?>       Now, firstly if i click the thumbnail, i get an error in the browser saying it's in a redirect loop, but secondly I'd like to know exactly what files i need to create to view a single post of this custom post type. And what to put in that file.


Adding Permalink to Slides with 'Simple Nivo Slider' plugin?

_Update April 27 10:57 AM -- Fail Log_ To **clarify** , I've only customized and adjusted the CSS. The first slide works correctly with linking through, but _ONLY_ on the first cycle / initial page load. Then the next time it slides through, it stops linking. _**??_** -- **Orginal Q:** So, I guess out of the box. The **_Simple Nivo_** Slider plugin, ( _though it's supposed too?_ ), doesn't have the permalink enabled to click through on slides to the actual corresponding recent posts. **So I need to do this manually as I've already customized the slider enough where it would hurt to start all over.** So, I've used this plugin: **http://wordpress.org/extend/plugins/simple-nivo- slider/** Before I'd use the php snippet below; but I'm wondering where I could add it within the plugin files?               <?php the_permalink() ?>      Does anyone have any suggestions or experience with this? AH!? **--- FULL 'simple-nivo-slider.php' below:**               <?php     /*     Plugin Name: Simple Nivo Slider     Plugin URI: http://wordpress.org/extend/plugins/simple-nivo-slider/     Description: Gilbert Pellegrom's excellent Nivo Slider, made easily available for WordPress     Version: 0.5.6     Author: Thomas M Steenholdt     Author URI: http://www.tmus.dk/     License: GLP2     */          /*  Copyright 2011  Thomas Munck Steenholdt  (email : tmus@tmus.dk)              This program is free software; you can redistribute it and/or modify         it under the terms of the GNU General Public License, version 2, as          published by the Free Software Foundation.              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 St, Fifth Floor, Boston, MA  02110-1301  USA     */          /* plugin database version - used to identify the need to "upgrade" database */     define('SNIVO_DB_VERSION', 5);          /* supported effects */     define('SNIVO_EFFECTS', 'fold fade sliceDownRight sliceDownLeft sliceUpRight sliceUpLeft sliceUpDown sliceUpDownLeft slideInRight slideInLeft boxRandom boxRain boxRainReverse boxRainGrow boxRainGrowReverse');               /*      * define default values for all plugin options      * the function can return the entire array or the value of a single option if opt_name is specified      */     function snivo_defaults($opt_name=null) {              $defaults = Array(             'snivo_category' => 1,             'snivo_imagesize' => 'full',             'snivo_shuffle' => 0,             'snivo_nivo_effects' => explode(' ', constant('SNIVO_EFFECTS')),             'snivo_nivo_slices' => 15,             'snivo_nivo_boxcols' => 8,             'snivo_nivo_boxrows' => 4,             'snivo_nivo_animspeed' => 500,             'snivo_nivo_pausetime' => 3000,             'snivo_nivo_directionnav' => 1,             'snivo_nivo_directionnavhide' => 1,             'snivo_nivo_controlnav' => 1,             'snivo_nivo_keyboardnav' => 1,             'snivo_nivo_pauseonhover' => 1,             'snivo_nivo_captionopacity' => 80         );              /* return entire array if $opt_name is empty */         if (empty($opt_name))             return $defaults;              /* otherwise return the value of the specified option from the array */         return $defaults[$opt_name];          };               /*      * plugin activation hook      */     function snivo_activate() {              /* add/update all plugin options */         update_option('snivo_db_version', constant('SNIVO_DB_VERSION'));         foreach (snivo_defaults() as $opt_name => $default_value) {             add_option($opt_name, $default_value);         }          }               /*      * plugin deactivation hook      */     function snivo_deactivate() {              /* remove deprecated options from the database on deactivation */          delete_option('snivo_nivo_testtest');          }               /*      * plugin uninstallation hook      */     function snivo_uninstall() {              /* delete all plugin options */         delete_option('snivo_db_version');         foreach (snivo_defaults() as $opt_name => $default_value) {             delete_option($opt_name);         }          }               /*      * display an administrative notice when database is updated      */     function snivo_update_notice() {         ?>

                 Simple Nivo Slider: database was updated.

         <?php     }               /*      * handle plugin updates      */     function snivo_update_helper() {              /*          * if current database 'snivo_db_version' is lower that the plugin database version,          * update the plugin database by calling the deactivate() and activate() functions          */         if (intval(get_option('snivo_db_version')) < constant('SNIVO_DB_VERSION')) {             /* deactivate, activate will handle addition of new options to the database              * and update the db_version too */             snivo_deactivate();             snivo_activate();                  /* notify administrator of the update */             add_action('admin_notices', 'snivo_update_notice');         }          }               /*      * plugin admin_init action function      */     function snivo_admin_init() {              register_setting('snivo-settings', 'snivo_category', 'intval');         register_setting('snivo-settings', 'snivo_imagesize');         register_setting('snivo-settings', 'snivo_shuffle', 'intval');         register_setting('snivo-settings', 'snivo_nivo_effects');         register_setting('snivo-settings', 'snivo_nivo_slices', 'intval');         register_setting('snivo-settings', 'snivo_nivo_boxcols', 'intval');         register_setting('snivo-settings', 'snivo_nivo_boxrows', 'intval');         register_setting('snivo-settings', 'snivo_nivo_animspeed', 'intval');         register_setting('snivo-settings', 'snivo_nivo_pausetime', 'intval');         register_setting('snivo-settings', 'snivo_nivo_directionnav', 'intval');         register_setting('snivo-settings', 'snivo_nivo_directionnavhide', 'intval');         register_setting('snivo-settings', 'snivo_nivo_controlnav', 'intval');         register_setting('snivo-settings', 'snivo_nivo_keyboardnav', 'intval');         register_setting('snivo-settings', 'snivo_nivo_pauseonhover', 'intval');         register_setting('snivo-settings', 'snivo_nivo_captionopacity', 'intval');              snivo_update_helper();          }               /*      * plugin admin_menu action function      */     function snivo_admin_menu() {              if (function_exists('add_submenu_page'))                 add_submenu_page('plugins.php','Simple Nivo Slider configuration', 'Simple Nivo Slider', 'manage_options', 'snivo_menu', 'snivo_admin_options');          }               /*      * this is the function that actually provides the slider (called from theme)      */     function simple_nivo_slider($id='slider', $category='') {              # make sure the theme has post-thumbnail support         if (!current_theme_supports('post-thumbnails'))             add_theme_support('post-thumbnails');              ?>                          <div id="<?php echo $id?>">         <?php              # build the post query string, then perform the query (default category is specified in plugin settings)         $query = 'posts_per_page=-1&';         if (empty($category))             $query .= 'cat='.get_option('snivo_category');         else             $query .= 'category_name='.$category;              # perform the query, shuffle if shuffle enabled         if (get_option('snivo_shuffle', snivo_defaults('snivo_shuffle')))             shuffle(query_posts($query));         else             query_posts($query);              # process the results         while (have_posts()) {                  the_post();                  if(!has_post_thumbnail())                 break;                  # determine link             $link = trim(get_post_meta(get_the_id(), 'simple_nivo_link', true));             if (empty($link))                 $link = get_permalink();                  # build 'a' opening and closing tags, if wanted             $linkhead = $linktail = '';             if (strtolower($link) != 'none') {                 $linkhead = "";                 $linktail = "";             }                  list($imgsrc) = wp_get_attachment_image_src(get_post_thumbnail_id(), get_option('snivo_imagesize', snivo_defaults('snivo_imagesize')));                  $caption = get_post_meta(get_the_id(), 'simple_nivo_caption', true);                  ?>             <?php echo $linkhead ?><img src="<?php echo $imgsrc ?>" alt="" title="<?php echo $caption ?>" /><?php echo $linktail."\n" ?>             <?php              }              wp_reset_query();              ?>
         <?php     }                /*      * handle snivo shortcode tags      */     function snivo_shortcode($atts) {              extract(shortcode_atts(array(             'id' => 'slider',             'category' => '',         ), $atts));              # place call to main plugin function using specified options         simple_nivo_slider($id, $category);          }               /*      * plugin administrative options page      */     function snivo_admin_options() {              if (!current_user_can('manage_options'))  {             wp_die( __('You do not have sufficient permissions to access this page.') );         }              ?>

Simple Nivo Slider configuration
             <form method="post" action="options.php" id="simple-nivo-slider-conf">                 <?php settings_fields('snivo-settings'); ?>

Post category	                 <select name="snivo_category">                     <option value="1">Select a category</option>                  <?php                      $category = get_option('snivo_category');                     $categories=  get_categories();                      foreach ($categories as $cat) {                         $option = '<option value="'.$cat->term_id.'"';                         if ($cat->term_id == $category)                             $option .= ' selected="selected"';                         $option .= '>';                         $option .= $cat->cat_name.'('.$cat->category_count.')';                         $option .= '</option>';                         echo $option;                     }                 ?>                 </select>

Image Size	                 <select name="snivo_imagesize">                 <?php                      $imagesize = get_option('snivo_imagesize');                     $imagesizes = get_intermediate_image_sizes();                     $imagesizes[] = 'full';                     foreach (array_reverse($imagesizes) as $tmpsize) {                         $option = '<option value="'.$tmpsize.'"';                         if ($tmpsize == $imagesize)                             $option .= ' selected="selected"';                         $option .= '>';                         $option .= $tmpsize;                         if ($tmpsize == snivo_defaults('snivo_imagesize'))                             $option .= ' (default)';                         $option .= '</option>';                         echo $option;                     }                 ?>                 </select>

Enabled effects	                 <?php                     $all_effects = explode(' ', constant('SNIVO_EFFECTS'));                     $enabled_effects = get_option('snivo_nivo_effects');                     foreach ($all_effects as $effect) {                         ?>                         <input type="checkbox" name="snivo_nivo_effects[]" value="<?php echo $effect ?>"<?php if (in_array($effect, $enabled_effects)) echo ' checked="checked"'?>><?php echo $effect ?>
                         <?php                     }                 ?>

Number of slices	                 <input type="text" name="snivo_nivo_slices" size="3" value="<?php echo get_option('snivo_nivo_slices') ?>">

Number of box columns	                 <input type="text" name="snivo_nivo_boxcols" size="3" value="<?php echo get_option('snivo_nivo_boxcols') ?>">

Number of box rows	                 <input type="text" name="snivo_nivo_boxrows" size="3" value="<?php echo get_option('snivo_nivo_boxrows') ?>">

Transition speed	                 <input type="text" name="snivo_nivo_animspeed" size="5" value="<?php echo get_option('snivo_nivo_animspeed') ?>"> ms

Delay between transitions	                 <input type="text" name="snivo_nivo_pausetime" size="5" value="<?php echo get_option('snivo_nivo_pausetime') ?>"> ms

Caption opacity	                 <input type="text" name="snivo_nivo_captionopacity" size="3" value="<?php echo get_option('snivo_nivo_captionopacity') ?>"> %

Options	                 <input type="checkbox" name="snivo_shuffle" value="1"<?php if (get_option('snivo_shuffle') == 1) echo ' checked="checked"'?>>Shuffle image order
                 <input type="checkbox" name="snivo_nivo_directionnav" value="1"<?php if (get_option('snivo_nivo_directionnav') == 1) echo ' checked="checked"'?>>Show directional navigation links
                 <input type="checkbox" name="snivo_nivo_directionnavhide" value="1"<?php if (get_option('snivo_nivo_directionnavhide') == 1) echo ' checked="checked"'?>>Show directional navigation links only on hover
                 <input type="checkbox" name="snivo_nivo_controlnav" value="1"<?php if (get_option('snivo_nivo_controlnav') == 1) echo ' checked="checked"'?>>Enable control navigation
                 <input type="checkbox" name="snivo_nivo_keyboardnav" value="1"<?php if (get_option('snivo_nivo_keyboardnav') == 1) echo ' checked="checked"'?>>Enable keyboard navigation
                 <input type="checkbox" name="snivo_nivo_pauseonhover" value="1"<?php if (get_option('snivo_nivo_pauseonhover') == 1) echo ' checked="checked"'?>>Pause slider on hover

                 <input type="submit" class="button-primary" value="<?php _e('Save Changes') ?>" />
                  </form>
         <?php     }          /* install/uninstall */     register_activation_hook( __FILE__, 'snivo_activate' );     register_deactivation_hook( __FILE__, 'snivo_deactivate' );     register_uninstall_hook( __FILE__, 'snivo_uninstall' );          /* actions */     add_action('admin_init', 'snivo_admin_init' );     add_action('admin_menu', 'snivo_admin_menu');          /* shortcodes */     add_shortcode('snivo', 'snivo_shortcode');          /* stylesheets */     wp_enqueue_style('nivo-slider', plugins_url('/nivo-slider/nivo-slider.css', __FILE__));     wp_enqueue_style('simple-nivo-slider', plugins_url('/styles.css', __FILE__));          /* scripts */     wp_enqueue_script('nivo-slider', plugins_url('/nivo-slider/jquery.nivo.slider.pack.js', __FILE__), array('jquery'));          ?>


how to translate countries output from wp database?

i have a list of countries in french stored in my database (wp_country). i use the code above to retrieve all the countries witth this ecohing `echo '"' . $country['name_country'] . '",';` it outputs countries in this format `"France",` `"Afrique du sud",` `"italie",` and so. the reason i output countries between brackets followed by comma, is that i want theme inpusted in a javascript autocomplete variable : `var availableCountries = [//countries list from wp_country ?> ]`. My probleme is how to translate the outputed countries with the translate functions `__()` or `_e()`               <?php          global $wpdb;                $sql_countries = $wpdb->prepare("SELECT id, name_country  FROM country ORDER            BY name_country ASC");         $result_countries = mysql_query($sql_countries);               while($country = mysql_fetch_array($result_countries)) {                   echo '"' . $country['name_country'] . '",';          }                            ?>      thank you


Uploading Multiple Attachments From Front-End With A Description

I am working on a Wordpress site that has a custom front-end submission form for adding in a post of content type, 'sketchpad'. The form has a section that allows you to upload multiple images with a description field which is going to be used as an alt tag. What is an easy way for me to upload multiple attachments with accompanying descriptions from the front-end? The code that currently catches the uploaded files is here:               // Make sure a user can edit posts (contributor level)     if (current_user_can('edit_posts'))     {         global $post;              // If we have files         if ( $_FILES )         {             // Get the upload attachment files             $files = $_FILES['upload_attachment'];                  foreach ($files['name'] as $key => $value)             {                 if ($files['name'][$key])                 {                     $file = array(                         'name' => $files['name'][$key],                         'type' => $files['type'][$key],                         'tmp_name' => $files['tmp_name'][$key],                         'error' => $files['error'][$key],                         'size' => $files['size'][$key]                     );                          $_FILES = array("upload_attachment" => $file);                          foreach ($_FILES as $file => $array)                     {                         $newupload = insert_attachment($file,$post->ID);                     }                 }             }         }     }      This is the 'insert attachment' function that actually handles the uploaded files and inserts them:               function insert_attachment($file_handler, $post_id)     {         // check to make sure its a successful upload         if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();              require_once(ABSPATH . "wp-admin" . '/includes/image.php');         require_once(ABSPATH . "wp-admin" . '/includes/file.php');         require_once(ABSPATH . "wp-admin" . '/includes/media.php');              $attach_id = media_handle_upload( $file_handler, $post_id );              return $attach_id;     }


Calling WP Gallery Uploader/Selector From Metabox

When I click the Add Media button on a Post/Page, I have the option to Add Media. After selecting media, I click Insert Into Post, and the images are inserted. However, there is another option, which is on the left sidebar. I can click Create Gallery. The image selecting process is the same, but when I click Create New Gallery, it goes to a new frame which allows me to edit the order of the images. This second window is what I am after. I am calling the frame from a metabox, and I have gotten it successfully to allow me to grab single or multiple images and save the ID's as a string, as well as insert thumbnails live into a preview box. I cannot find anything about calling the Gallery frame. My current code is as follows:               jQuery('#fg_select').on('click', function(event){              event.preventDefault();              // If the media frame already exists, reopen it.         if ( file_frame ) {             file_frame.open();             return;         }              // Create the media frame.         file_frame = wp.media.frame = wp.media({             title: "Select Images For Gallery",             button: {text: "Select",},             library : { type : 'image'},             multiple: true // Set to true to allow multiple files to be selected         });              file_frame.on('open', function() {             var selection = file_frame.state().get('selection');             ids = jQuery('#fg_metadata').val().split(',');             ids.forEach(function(id) {                 attachment = wp.media.attachment(id);                 attachment.fetch();                 selection.add( attachment ? [ attachment ] : [] );             });         });              file_frame.on('ready', function() {             // Here we can add a custom class to our media modal.             // .media-modal doesn't exists before the frame is             // completly initialised.             $( '.media-modal' ).addClass( 'no-sidebar' );         });              // When an image is selected, run a callback.         file_frame.on('select', function() {             var imageIDArray = [];             var imageHTML = '';             var metadataString = '';             images = file_frame.state().get('selection');             images.each(function(image) {                 imageIDArray.push(image.attributes.id);                 imageHTML += '
<button></button>
';             });             metadataString = imageIDArray.join(",");             if(metadataString){                 jQuery("#fg_metadata").val(metadataString);                 jQuery("#featuredgallerydiv ul").html(imageHTML);                 jQuery('#fg_select').text('Edit Selection');                 jQuery('#fg_removeall').addClass('visible');             }         });              // Finally, open the modal         file_frame.open();          });      Any ideas?


How can I store data from custom fields to custom tables?

I know how to make custom fields for my custom post types. I also know there is the `Advanced Custom Fields`plugin. But I need to know how I can store my custom fields in my custom post type to my custom DB tables. I've been looking for tutorials, but I only find how to create SQL tables in plugins. How can I fetch "my data" (and save it in my own tables) and at the same time save the other data for the page the normal way?


Generating embed code for users to share

Recently I was stuck by an idea to let users and other bloggers to embed the entire page on of my blog on to their blogs. The problem is I have to change the URL every time in code and the codes populate the result on my page itself. Is there any way by which the script could automatically fetch the URL of the viewing page and update it codes for users without generating the content on my page? This is what I was trying.                   <object data=http://domain.tld/Requested_page width="100%" height="500">              <embed src=http://domain.tld/Requested_page width="100%" height="500"></embed> Error: Embedded data could not be displayed. Visit              Visit         </object>


Recover from failed multisite conversion

I'm normally quite the techie (look at my SF account!) but it turns out I know nothing about Wordpress and in doing so have sabotaged my wife's blog. As a family we have a hosting package through Namecheap who also manage my domains, I'm fine with the whole DNS thing. They provide web hosting via /public_html and using their cpanel I installed Wordpress in single site mode into a /public_html/ _wife's name_ This all went great for months until my daughter asked for a site, I then followed the instructions to convert it to a multisite but something went wrong, after a bit of faffing about with .htaccess I managed to get it working again - except it won't allow for photo upgrades and I still have a more- moody-than-normal teen on my hands. What I'd really like to do is somehow backup all of my wife's posts, config, photos etc. including the DB, wipe the whole installation, reinstall as multisite and restore it all. What's the chances of that working and if so what would be my first steps. Again sorry that this seems so amateur, it's really not the kind of thing I normally do.


Best Roles and Capability on a site with review features using a front end custom post

I'm working on a Movie Blog site, I'll be having a movie review for site members and planning to create/install plugin that can create a front-end post/edit using a custom post type for that reviews. I'm also planning on creating custom **roles and capabilities** for my members that will register on my site. My question is what's the best Role and Capabilities to use for this kind of membership? He's the list of what I'm planning for the users.   * Can edit their profile.   * Can write/edit their own review(via custom post type) Thanks!


Safely store code(html/js..) into database

So I'm working on a small plugin, and this plugin allows users to save data to my db. This data is mostly plain text but 3 fields are will have tags inside them. 1 field can be used to save all kind of code(js/php/html....) into my db, and 2 fields can only accept JS code. My question how should I save this kind of data into the DB to prevent injections and such. _I am still new to the whole validation stuff so any tips and help would be nice (dont put the links to the wordpress docs in the comments below, I already read those)_ _My code until now_                 $wpdb->insert($table,           array(               'field-no-tags'       => sanitize_text_field($_POST['field-no-tags']),               'field-have-all-tags' => $_POST['field-have-all-tags'],               'field-have-js-tags'  => $_POST['field-have-js-tags']           )           ,array(               's%',               's%',           )       );                 <form>                No code allowed                <textarea name="field-no-tags"></textarea>                     All code allowed                <textarea name="field-have-all-tags"></textarea>                     Only JS allowed                <textarea name="field-have-js-tags"></textarea>                <button type="submit">Save</button>            </form>


Add async script

I am working on a plugin that has to inject a script on pages (something like RefTagger), which would be easy using `wp_enqueue_script`, but there are two reasons I cannot do that: the script tag has to have an ID and it should be executed asynchronously. I found three possible solutions but I don't really like any of them:   1. **Just echo the script in`wp_footer`** This is the easiest one and I have complete control over the script tag, but it is probably frowned upon (I intend to submit my plugin to the Plugin Repository so any advice regarding official guidelines is welcome).   2. **Use the standard functions and use filters to modify the script tag.** The answers for this question detail the process, my problem is that it is very hacky (and probably could break in the future) and adding logic to `clean_url` has a performance cost - for one single script tag.   3. **Create a snippet that dynamically injects the script, save it as a file and use the standard methods.** This is a very clean way but there is one more script to download, meaning slower page loads. Is there any other way to do this, or is any of my solutions acceptable?


PHP Widget and do_shortcode

I'm using PHP Widget which allows PHP code to execute from a widget. I tried using this code to execute do_shortcode but it's not rendering               <?php      $lat = get_field('woo_maps_lat');     $long = get_field('woo_maps_long');     echo do_shortcode('[forecast location="' . $lat .','.$long. '" measurement=\'C\']');             ?>      If I echo a variable with simply `echo $lat;' it works. So the PHP Widget is working fine. The problem is echoing the shortcode in the widget. I can add shortcoded just fine to a widget but I need to be able to add the php variables where they are. I tried adding `add_filter('widget_text', 'do_shortcode');` to my functions.php but it's still not rendering properly. Any suggestions? Thanks


Cannot filter categories by parent category

I'm trying to get all direct child categories in category hierarchy. What I've tried:               $args = array(             'child_of' => get_query_var("cat")             );     $categories = get_categories($args);     foreach($categories as $category) {         $catID = $category->cat_ID;         $test = "cat_ID: " . $category->cat_ID . " " . "parent: " . $category->parent . ", ";          echo $test;     }      In case`get_query_var("cat") == 14` I get the following result: > cat_ID: 35 parent: 14, cat_ID: 34 parent: 14, cat_ID: 36 parent: 34, cat_ID: > 37 parent: 34, which is not what I want because this displays child's child categories. So I tried               $args = array(             'parent' => strval(get_query_var("cat"))             );      which results in > cat_ID: 35 parent: 14, instead of what I expected > cat_ID: 35 parent: 14, cat_ID: 34 parent: 14, So what's going wrong?


Edit the_content function

I want to edit the default function `the_content()`. I know i can `add_filter('the_content', 'with_my_function')` but im having trouble outputting the old content with mine. Heres an example of what im doing.               add_filter('the_content', 'my_function');     function my_function()     {         $write = 'hello world';         $content = apply_filters('the_content', get_the_content());         echo $write.$content;     }      How can i get this to work?


check if comment submitted was successful

I want to use php to understand if comment submission was successful. Is there any `get/post` data I can use to make `if` function for this?


do_shortcodes() isn't working

I'm making a homepage template for my theme and I want to call a plugin, namely royalslider. Surely               do_shortcode('[gallery id= "1"]');      Should do the trick?


Change image link: wp_get_attachment_link

Can anyone help me filter wp_get_attachment_link so that a particular occurence of it links to the 'medium' or other size image rather than the full size. I have the following in a page template:               $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID );      $attachments = get_posts($args);     if ($attachments) {         foreach ( $attachments as $attachment ) {         echo wp_get_attachment_link( $attachment->ID , array(150,150) );          }     }      I can add a filter to add class or rel but I can't find anyway to alter the default (as originally uploaded) full size image linked to in the template .... The above works fine with colorbox (not plugin) to create a lightbox, but if a user uploads a very large image (ie: 4000x4000+ pixels), the link will load too slowly and I don't want the public to be able to download a print quality image from the lightbox..


How do I add a widget programmatically to a newly created site (WPMU) within a plugin?

I'm making a plugin that creates new sites (WPMU), and also has its own widget that needs to be placed onto the new sites it creates. The issue I'm having is that I can't get the plugin to insert (preferable I'd like it to replace all widgets with just mine) to the newly created site. It half does it, in the sense that it puts the plugin into an "inactive" state, instead of in the sidebar. Here is the code I have:               function se160609($blog_id, $user_id, $domain, $path, $site_id, $meta) {         switch_to_blog($blog_id);              switch_theme("twentytwelve");              register_sidebar(             array (                   'name'          => 'Main Sidebar',                 'id'            => 'sidebar-1',                 'before_widget' => '',                 'after_widget'  => '',                 'before_title'  => '',                 'after_title'   => '',             )         );              update_option('widget_mywidget',             array(                 'title' => 'Policies'             )         );              update_option('sidebars_widgets',             array(                  'sidebar-1' => array('mywidget')             )         );              restore_current_blog();     }          add_action('wpmu_new_blog', 'se160609');      I also have this to register (and deregister) widgets:               function se160609_load_widget() {         register_widget( 'MyWidget' );              unregister_widget( 'WP_Widget_Archives' );         unregister_widget( 'WP_Widget_Calendar' );         unregister_widget( 'WP_Widget_Categories' );         unregister_widget( 'WP_Widget_Links' );         unregister_widget( 'WP_Widget_Meta' );         unregister_widget( 'WP_Widget_Pages' );         unregister_widget( 'WP_Widget_Recent_Comments' );         unregister_widget( 'WP_Widget_Recent_Posts' );         unregister_widget( 'WP_Widget_RSS' );         unregister_widget( 'WP_Widget_Search' );         unregister_widget( 'WP_Widget_Tag_Cloud' );         unregister_widget( 'WP_Widget_Text' );     }     add_action( 'widgets_init', 'se160609_load_widget' );


How to empty wordpress custom post Database table

I have around 2000 custom posts. And 7 regular wp pages. I want to delete all those custom post without effecting the pages. I thought the easiest way would be to empty the custom post table but I dont know how to do it. I am familiar with DB operations but I dont know the schema of wp posts, so have no idea where these custom posts are located. I don't mind using a plugin to do it. Inshort:- Just want to delete all the custom posts and their data.


Where is the /blog/ url set from?

I'm having a weird issue while setting up a site. It almost seems as though the /blog/ url is reserved or already in use, only it isn't as far as I can tell. I setup a new page called 'Blog' and set the permalink to '/blog/'. Then under 'Settings' => 'Reading' I set the Posts page to be 'Blog'. Then I went one step further and setup a new template called 'tpl-blog.php' and assigned it to the 'Blog' page. After all that I entered some content in and it and tested and it didn't look right, none of my text was in there and a lowercase 'blog' was showing up for the title. I tested a bit more and found it was using the page.php file instead of my custom tpl-blog.php. Thanks for any help!   Levi


How do I call wp_get_current_user() in a plugin when plugins are loaded before pluggable.php?

The current result is "PHP Fatal error: Call to undefined function wp_get_current_user()" which makes sense, but doesn't help. I need to use $current_user. Here is the code I'm currently using:               $wp->init();      do_action( 'init' ); // Check site status      $file='http://xxxxxxxx.com/wp-admin/wp_includes/pluggable.php';      if ( is_multisite() ) {          if ( true !== ( $file = ms_site_check() ) ) {              require( $file );             die();          }          unset($file);      }          // Get the current user's info      $current_user = wp_get_current_user();           if ( !($current_user instanceof WP_User) )          return;           echo $current_user->user_login;           function paf_uname(){          return $current_user->user_login;      }


get_pages() as per custom menu order

I'm working on Single Page WordPress Theme where I want to get_pages() as per custom menu order. I have gone through the reference for get_pages() which only allows for default menu :               get_pages('sort_order=asc&sort_column=menu_order');      Is there any way to get_pages() as per **custom menu order** ?


I want to display custom text widgets for each post in the sidebar?

Ideally I am looking for two text boxes added to the 'Add new post' admin page, and the data from those two boxes be displayed in the sidebar when viewing the post page. So the sidebar displays the data belong to the post.... Two widgets for each post. Possible? Thanks a ton in advance!


Displaying oEmbed errors?

Sometimes embedding an item via oEmbed is not possible, for example when a YouTube video has embedding disabled. The oEmbed service will return a `401 Unauthorized`, and the code will not be converted. Is there a way to notify the user of this? The current workflow is non- intuitive (at least to me), and I would prefer a message on the WordPress page, or even better, in the editor, saying that the object could not be embedded.


Markup of oEmbed codes in the editor?

Is there a way to give oEmbed codes a special markup in the visual editor? In my dream implementation you paste an oEmbed-enabled url in the editor, which will then automatically replace it with a thumbnail of the media object you want to insert. A basic implementation would at least highlight the URL so the user knows "something special" could happen there (if no errors occur). Is there a plugin that does this? I could create something like this myself, but I would need some pointers on how to hook into the TinyMCE editor in the most WordPress-stylish way.


How can I remove a RSS feed that a WordPress plugin adds to `wp_head()`?

I'm using a plugin that adds an RSS feed to WordPress. I don't want it there. There is no option in the plugin's settings to disable it. How can I unhook it from `wp_head()`, _or_ , where do you register `head` element things in a WordPress plugin so I can manually remove it? Thanks


Creating a table in the admin-style?

What is the recommended way of creating a page with a table, in the style of the tables showing posts or users in the admin area? I am expanding the Cache Images plugin, and it contains a table with domains and a number of images from that domain. So there is no equivalent existing table that I can build upon (in the first version of this question, I asked about a table with posts, but there I could (maybe) expand the existing post table). Should I just base myself on the post overview page, and start with a `<table class="widefat">`, or are there better functions that handle this now? Do you know a clean, empty example of a table with paging that I could base my work on?


Calling a Function After New Post Creation for a WordPress Custom Post Type?

Assume I created a new post type `'product'`. Is there a way to perform a function (user created) when this new `'product'` post has been created?


Correct Search & Replace Queries for Changing URLs in a WordPress Database?

Have developed a site on the production box using a temporary address (http://IP-adddress). Now it's time to go live. Once, ages ago, I successfully used phpMyAdmin and did a search/replace, but am wondering if it's still _"the best"_ way to go. Will these work okay, still? The site is in WordPress 3.0.1.               update wp_options set option_value=replace(option_value,'OLD URL','NEW URL') where option_value like "%OLD URL%";         update wp_posts SET guid=replace(guid, 'OLD URL','NEW URL');     update wp_posts SET post_excerpt=replace(post_excerpt, 'OLD URL','NEW URL');     update wp_posts SET post_content=replace(post_content, 'OLD URL','NEW URL');         update wp_postmeta SET meta_value=replace(meta_value, 'OLD URL','NEW URL');      I've read a number of related posts here, but none with the actual queries. I thought this **search and replace plugin** sounded promising, but the only documentation I found was in German, which I can't read, so I'm too cautious to try it. And this thread about **moving from development to production** has lots of information in it, but:   1. much of it is over my head, and    2. no queries listed. TYIA, Mike


add_filter ( 'media_send_to_editor', ...) does not work on wp 3.5

I have a problem with this -probably- abandoned plugin:                   <?php     /*     Plugin Name: RV Embed PDF     Description: When you upload PDF and insert a link to it with the Add Media button, it     will be automatically embedded in the page using Google Docs Viewer.     Author: Rong Vang Media     Author URI: http://www.rongvang.cz     Version: 1.0     */     function rv_embedpdf($in){     $out = "";     if(preg_match("/href='(.*?\\.pdf)'/", $in, $matches)){         $out .= '<iframe src="http://docs.google.com/gview?url='.$matches[1].'&embedded=true" style="width:100%; height:500px;" frameborder="0"></iframe>';     }          $out .= $in;          return $out;     }     add_filter ( 'media_send_to_editor', 'rv_embedpdf' );      can anybody help me to make it compatible with wp 3.5?


How to no follow the paginated comments

I am trying to find a way to add `rel="nofollow"` to my comments pagination links.   Can anyone provide me with a hook or way to do so?


Allowing more elements in comments via functions.php

I would like to allow certain HTML elements in my comments and have edited `kses.php` directly in the past. However, I have been hacked recently and replaced all the core Wordpress files and feel I would like to avoid editing those files. Is it possible to allow more elements via the `functions.php` file?