question
stringlengths
0
34.8k
answer
stringlengths
0
28.3k
title
stringlengths
7
150
forum_tag
stringclasses
12 values
Is there any way to add %post_type% and %taxonomy% to permalinks? I want to have links from one custom post type have one taxonomy's terms in its permalink, and another post type to use another taxonomy's terms.
I will try to answer the question in detailed but keeping it as short as possible considering you have achieved the basics. Suppose our custom post type one is to be connected to taxonomy one. Let's call them 'console'(custom post type) and 'brands'(taxonomy). You want to achieve: http://example.com/console/brands/sony/ Steps: Register the taxonomy first and attach it to custom post type console. <code> $labels = array( 'name' =&gt; 'Brands', 'singular_name' =&gt; 'Brand', 'search_items' =&gt; 'Search Brands', 'popular_items' =&gt; 'Popular Brands', 'all_items' =&gt; 'All Brands', 'parent_item' =&gt; 'Parent Brand', 'edit_item' =&gt; 'Edit Brand', 'update_item' =&gt; 'Update Brand', 'add_new_item' =&gt; 'Add New Brand', 'new_item_name' =&gt; 'New Brand', 'separate_items_with_commas' =&gt; 'Separate Brands with commas', 'add_or_remove_items' =&gt; 'Add or remove Brands', 'choose_from_most_used' =&gt; 'Choose from most used Brands' ); $args = array( 'label' =&gt; 'Brands', 'labels' =&gt; $labels, 'public' =&gt; true, 'hierarchical' =&gt; true, 'show_ui' =&gt; true, 'show_in_nav_menus' =&gt; true, 'args' =&gt; array( 'orderby' =&gt; 'term_order' ), 'rewrite' =&gt; array( 'slug' =&gt; 'consoles/brands', 'with_front' =&gt; false ), 'query_var' =&gt; true ); register_taxonomy( 'brands', 'consoles', $args ); </code> Note here that the rewrite key in our $args array. That value is telling WordPress the slug to use in our Custom Taxonomy. We don’t want it prepended with the WordPress permalink front base, which defaults to true, and we want the slug to include our Custom Post Type rewrite slug. Step Two: Now create the custom post type.I'm not writing the whole code but remember the important parameter here is the 'rewrite' <code> 'rewrite' =&gt; array( 'slug' =&gt; 'consoles', 'with_front' =&gt; false ), </code> visit your Settings > Permalinks options screen in the WordPress admin to ensure your new permalinks are picked up Repeat the steps for second custom post type and taxonomy 2.:)cheers.. PS:You need to define has_archive key to have archive page.
Use different taxonomies in different custom post types' permalinks?
wordpress
This might be an annoying question, since there are stackexchange-url ("some pretty good answers") to this question, but they are 9 months old, so please but bare with me. I would like to have some input to point me to the right direction. I'm looking to integrate a simple forum for a Wordpress project. The forum must haves: Simple threads, similar to the WP threaded comments system. Ability to display only the forum login page as forum front page. Ability to show only the forum the user is registered to, or the forum the admin assigns the user to. In a way the flow is: Click on forums page > Login > Browse only one specific forum. Ability to show some info about each of the users: phone, email, etc. Ability to register without going to wp-admin What I need is way less then what vBulletin or phpBB or even SimplePress provide, i just need a place for users to chat on specific topics and get in touch. I've tried to use bbPress, as it is as close as it gets to what I wanted, but they don't have the ability to close forums for specific groups of users, so maybe one can point me to the right software of combination of plugins. Thanks in advance.
Have you beta-tested the bbPress Plugin? It should meet most of these needs.
Wordpress and simple forums
wordpress
I'm currently in the process of redeveloping my website. I've decided to use WordPress as its CMS, rather than coding everything from scratch. It's a fishkeeping website, consisting of species profiles; plant profiles; fossil species profiles; articles; news posts and blog posts. My original idea was to create plugins for each of those (excluding articles/news posts/blog posts as I can just add post categories), with each plugin creating a new database table and adding the relevant admin menus (create, view/amend). I've stumbled across custom post types today, and I'm now wondering if they'll do the job for me? It would be ideal if they could - save me a lot of time and offer some reasonably useful functionality that I probably won't bother to code if I do it the other way (time constraints). The species profile is the most complex aspect of the site. It will have ~20 fields. A few of the fields will need to be lookup fields, i.e. category which will allow the user to select from a list. A few of the fields will need to be array values, i.e. one textbox called "ph_min" and one called "ph_max" which are stored in the DB as a serialized array. Fields following these array fields will require a custom TinyMCE button to insert BBCode such as [ph_min] (this will allow us to write: "keep these fish at [temp_min] if possible, but don't use water above [temp_max]" whilst having a conversion button at the top of each profile). Are Custom Post Types flexible enough to do all of the above for me, or should I just take it back to basics and write my own admin pages and database tables?
Custom post types are an excellent way for this kind of a job. I'd suggest reading the following info: Custom Post Types (1) (2) Taxonomies (1) (2) Custom Meta Boxes (1) - I use this class all the time, or (2) If you are new to Custom post types, an easy way to start would be playing around with Custom Post Types UI plugin and work your way up.
Custom Post Types, or completely custom?
wordpress
If you have created shortcodes in Wordpress, you may have noticed that when you get the content of your shortcode, it's wrapped in html paragraph tags. I don't know why the progammers did that. It seems like a very bad idea to me to add formatting to the actual content. I've found a post that presents this solution : http://donalmacarthur.com/articles/cleaning-up-wordpress-shortcode-formatting/ But i'm wondering : Is there a solution proposed by the wordpress API itself, or something that i am missing here ?
The shortcodes, since they are inserted in the editor, comply to editor rules. Hitting the return in editor will generate a paragraph tag, just like any other text. It's one of the TinyMCE features. To read more about TinyMCE check out their forum and especially this thread
How can i remove the paragraph from shortcodes content?
wordpress
I Want to Add My Latest 5 Post Title with Corresponding Link in My Header Position.What was the Actual Php code?Am Newbie ....
This sounds like an additional Loop on that page, right? You might want to use: <code> &lt;ul&gt; &lt;?php $posts_query = new WP_Query('posts_per_page=5'); while ($posts_query-&gt;have_posts()) : $posts_query-&gt;the_post(); ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endwhile; wp_reset_query(); ?&gt; &lt;/ul&gt; </code> Also read more here: http://codex.wordpress.org/The_Loop#Multiple_Loops_in_Action
How Can i Get 5 Recent Post Title With Corresponding Link?
wordpress
I am wondering from the syntax <code> $sql = $wpdb-&gt;prepare( 'query' [, value_parameter, value_parameter ... ] ) </code> It appears (from the syntax - values within prepare) that it simple escapes values not craete a prepared statement giving me performance benefits when I execute it multiple times will different params? On 2nd look, since values are optional, I can set them after preparing? How do I do that?
<code> $wpdb-prepare </code> works like <code> sprintf </code> and <code> vsprintf </code> . The first argument will always be a format string. The only acceptable format specifiers are <code> %s </code> and <code> %d </code> . Others I have never tested but may result in parse error as per the Codex. You must escape literal % in your query with % , e.g: <code> %% </code> If you use it like <code> sprintf </code> which is only possible if you know the number of arguments before runtime then you can the number of arguments should match the number of format specifiers in your format string. E.g: <code> $wpdb-&gt;prepare( "SELECT * FROM {$wpdb-&gt;prefix}_votes WHERE post_id = %d AND username = %s", $post_id, $username ); </code> If you don't know the number of arguments till the runtime then you must use it like <code> vsprintf </code> . In this case the first argument will be format specifier but the second argument will be an array. E.g: <code> $wpdb-&gt;prepare( "SELECT * FROM {$wpdb-&gt;prefix}_votes WHERE post_id = %d AND username = %s", array( $post_id, $username ) ); </code> <code> $wpdb-&gt;prepare </code> will return a SQL QUERY string which you can execute as many times as you like. For the above examples the resulted query will be: <code> SELECT * FROM wp_votes WHERE post_id = 747 AND username = 'cooluser' </code>
Does $wpdb-> prepare not create a prepared statement that I can execute multiple times?
wordpress
Suppose I have a post meta like "Region" it will contain values like "Region 1", "Region 2" etc. But it should only contain ONE value. Also I would like it to have an archive page. If I use custom taxonomy, users can select more than 1 value. Is it possible to have a drop down type selection instead?
For mutually exclusive values use post meta. It is faster to read than assigned taxonomies too. It is possible to create your own interface: Set the parameter <code> show_ui </code> to <code> false </code> when you register the taxonomy. Register a meta box where you print out all existing taxons with radio boxes. Add a save action to assign the value to the taxonomy. But in most cases you’re doing something wrong and misuse the taxonomy. ;)
Single reusable value for post meta: Custom Taxonomy or Post Meta?
wordpress
I've got several questions regarding WP multisite, hoping someone who's used it extensively can help: Is it possible to manage several WP sites over several different domains? How can plugins be managed, some I'd like to use across all the sites but others I'd only like to use on certain sites. Also what happens to each of the plugin settings, are they rolled out across the board? Updating - how can this be managed per site for both the plugins and WP itself.
Yes. Use the Domain Mapping Plugin. Plugins can be enabled network-wide, or on a per-site basis. You can choose whether or not to give site admins the capability to activate/deactivate Plugins. Plugin settings are on a per-site basis. The Network Administration handles updates to core, Plugins, and Themes, and automates updating the database tables for each network site, when applicable.
Multisite questions
wordpress
I have the default setting (IIRC) of 10 comments per page, and max nesting of 5 deep. The problem (or at least, minor annoyance) is that replies to comments are not counted towards that maximum of ten per page. I can understand that you do not want to break a thread, and that should be avoided, but in my test case I have: <code> test10 - test10 2 - test10 3 - - test10 4 - - - test10 5 - - test10 6 - test10 7 - test10 8 - test10 9 test9 test8 (should be on a new page?) test7 test6 test5 test4 test3 test2 test1 </code> They all show on the same page. But in reality I want to break that after the test9 comment. I have a funny feeling it's not going to be easy. Hopefully there will be a method just within the theme framework, but I'm not afraid to modify wordpress if needs be.
Since I decided this would actually be pretty damn useful for myself too, I pushed on and wrote a custom walker, <code> Walker_Paged_Threaded </code> . I've tried to comment to the best of my ability, and admittedly it's a little thrown together, but I'm happy with the result. How To Use It The class is written with the same abstract approach as the original <code> Walker </code> , so as not to limit it to just comments. However, to keep things simple, we'll rename it* ; <code> Walker_Comment_Paged_Threaded extends Walker_Comment </code> Now in your theme's <code> comments.php </code> ; <code> wp_list_comments( array( 'walker' =&gt; new Walker_Comment_Paged_Threaded ) ); </code> Wahey! Paged comments that account for threading. Known Side Affects Since we've changed the way pages are calculated, functions like <code> get_comment_pages_count </code> will start to behave abnormally when passed parameters like <code> $per_page </code> or <code> $threaded </code> . Out-of-the-box though, this is not the case. However , <code> get_comment_pages_count </code> will still fallback on <code> Walker_Comment </code> if <code> $wp_query::max_num_comment_pages </code> is empty. But providing you call <code> wp_list_comments </code> first, it'll run the walker and set the property automatically. If you are displaying comment pagination or page links before your comments , you'll need to do something like so; <code> &lt;?php /** * Capture comments in an output buffer. The function needs to run before * displaying page links, as it runs the walker and then sets the * 'max_num_comment_pages' property on $wp_query. */ ob_start(); wp_list_comments( array( 'walker' =&gt; new Walker_Comment_Paged_Threaded ) ); $comments_list = ob_get_clean(); ?&gt; &lt;?php paginate_comments_links(); ?&gt; &lt;?php echo $comments_list; ?&gt; </code> This is actually the neatest way to get around it, trust me! *If you want to keep it abstract, without multiple copies for each intent, you could fake 'multiple inheritance', which stackexchange-url ("is a little ugly"). N.B. I thought best to add this as a separate answer, as it's actually an answer!
Nested comments ignored for max per page in wordpress
wordpress
In WordPress localization files (.po), does php map files by the line number eg. <code> comments.php:60 </code> or msgid <code> msgid "&lt;span class=\"meta-nav\"&gt;&amp;larr;&lt;/span&gt; Older Comments" </code> . So basically, if I have said string in comments.php in line 60, and move it to line 74, does it still get localized by the msgid?
if I have said string in comments.php in line 60, and move it to line 74, does it still get localized by the msgid? Yes it does. Localization does not depend on line numbers of strings.
WordPress localization
wordpress
I'm making a theme for a client (first time using Wordpress), and the client would like to have multiple site "descriptions" to be available. The first one as the main description, and the second one as another block of text in the header which can be changed. Is there any way to add such functionality to a theme? I can instruct the client to manually edit the <code> .php </code> files, but I'd like to do something a bit more elegant, like adding an option to the Dashboard. Thanks!
not 100% sure what you're after but this may help ... i did a site one time and one special set of "pages" on the site were sort of sectionalised ( eg each page consisted of a title and about 4 other "fields" ) .... the way i did it in the back end was to do like dzogchen suggested use custom fields ... so i used the title from the wordpress system and then i set up 4 custom fields and then to make it look good for the user what i did was to go to the "screen options" at the top and turn off the visual editor ..... ### actually sorry scratch all that (i've left it in because it may actually work for you) #### ... i think how i achieved this was that i used a custom post type and did all of what i just said in the programming because the template tags allow you to turn on and off what is seen in the editor .... yes it's coming back to me now ( sorry but it's a while back ) .... what you'd need to do that is a combination of custom post types and the settings api ... this makes it very slick but warning the settings api is very good, very powerful but takes a bit of working out ( also tip if you are going this way there are two ways of doing settings in wp the new way and the old .... dont get mixed up )
Adding an editable field to template?
wordpress
How can I force WP to always check the child theme folder first when running <code> get_template_part </code> ? Example: child theme loads <code> get_template_part('content', 'inventory') </code> in <code> single.php </code> . Because all child themes (and there are a lot) share the same common inventory template base, the file <code> content-inventory.php </code> is in the parent theme. So far so good. I would like to add a small section to said inventory template that will be unique to each child theme. Adding <code> get_template_part('content', 'inventory-special') </code> into <code> content-inventory.php </code> will not check the child theme directory first.
It does, by default. The <code> get_template_part() </code> function uses <code> locate_template() </code> which cascades through the template files in in order of specificity and stylesheetpath/templatepath. So, if your Child Theme includes a <code> content-inventory.php </code> , then <code> get_template_part() </code> will include it; if not, then it will look for <code> content-inventory.php </code> in the parent Theme. If it doesn't find it, it will then look for <code> content.php </code> first in the child, then in the parent. EDIT: Taking a stab at understanding what you mean; please clarify if I'm misunderstanding... You want to include a new template part file within a Parent-Theme template file called <code> content-inventory.php </code> , right? The only way, AFAIK, that you can do that is to copy <code> content-inventory.php </code> into your Child Theme , and then add the new <code> get_template_part() </code> call where needed. If a file named <code> content-inventory.php </code> is included in both the Parent and the Child Theme, then WordPress will always use the Child Theme version, if included using <code> get_template_part() </code> .
How to make get_template_part always check child theme first?
wordpress
I'm missing something here: <code> function page_help($contextual_help, $screen_id, $screen) { if ($screen_id == 'page') { $contextual_help = ' &lt;h5&gt;Shortcodes&lt;/h5&gt; &lt;p&gt;Shortcodes help&lt;/p&gt; '.$contextual_help; return $contextual_help; } elseif ($screen_id == 'post') { $contextual_help = ' &lt;h5&gt;Post help&lt;/h5&gt; &lt;p&gt;Help is on its way!&lt;/p&gt; '.$contextual_help; return $contextual_help; } } add_filter('contextual_help', 'page_help', 10, 3); </code> The code is inserting into the correct screens but I am having two issues: The code is inserting at the top, I'd like it at the bottom. The code is deleting the help from all other screens except those mentioned above. Thanks in advance for your tips! Niels
In order to not delete help from all other screens, you need to always return the contextual help text, otherwise your filter doesn't return anything for non-page/post screens and so nothing will show up. Move the return to the bottom of the function, outside of your if/else. Also, the original contextual help is being concatenated to the end of your custom message, so move it to the front to have your text put at the bottom. Thus: <code> function myprefix_page_help($contextual_help, $screen_id, $screen) { if ($screen_id == 'page') { $contextual_help = $contextual_help.' &lt;h5&gt;Shortcodes&lt;/h5&gt; &lt;p&gt;Shortcodes help&lt;/p&gt;'; } elseif ($screen_id == 'post') { $contextual_help = $contextual_help.' &lt;h5&gt;Post help&lt;/h5&gt; &lt;p&gt;Help is on its way!&lt;/p&gt;'; } return $contextual_help; } add_filter('contextual_help', 'myprefix_page_help', 10, 3); </code>
Issue with contextual help overwriting existing content
wordpress
I am looking for a plugin or a code that will allow admin to select an author and "ban" him from logging in the system and also to unpublish his posted content until the admin decide to allow the entrance again. This should include posts, author page and comments if it is possible. Thank you for your replies.
You could try the User Control Plugin
Plugin to restrict login and unpublish content from an author
wordpress
I was wondering if there is a way or a plugin to post something like twitter update messages instead of a post. Something like http://p2demo.wordpress.com/ but better, where a user will post update messages not an entire post (in database matters). That means you will save space, make it quicker and fewer database resources. I am looking for a way to post lite messages, that database will only save the must, like IDs, title, post and a thumb, through php maybe. No taxonomies and and and. I hope you understand what I am trying to say (sorry for any bad English) Thank you. Updated : I found this code, should I use this as a twitter posting feature? (As I said I need fewer db resources) <code> // Create post object $my_post = array(); $my_post['post_title'] = 'My post'; $my_post['post_content'] = 'This is my post.'; $my_post['post_status'] = 'publish'; $my_post['post_author'] = 1; $my_post['post_category'] = array(0); // Insert the post into the database wp_insert_post( $my_post );" </code>
The code you posted is about the same one WordPress uses to insert posts in to the database so it's not really saving anything. But i would suggest you use Custom Post type and only allow a few or as much as needed objects to it : 'title' 'author' 'excerpt' 'custom-fields' 'comments' (assuming you want to allow comments.) This will not save you any extra unneeded fields (not more the the minimum needed by WordPress). And if that is still not good enough the your best bet would be to create your own database table and only store what you need in it.
Instead of submiting an entire post, is there any way to submit a lite-post or a simple message?
wordpress
I cannot figure out how to make next_posts_link() work within my custom WP_Query. Here is the function: <code> function artists() { echo '&lt;div id="artists"&gt;'; $args = array( 'post_type' =&gt; 'artist', 'posts_per_page' =&gt; 3, 'paged' =&gt; get_query_var( 'page' )); $loop = new WP_Query( $args ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); echo '&lt;a class="artist" href="'.get_post_permalink().'"&gt;'; echo '&lt;h3 class="artist-name"&gt;'.get_the_title().'&lt;/h3&gt;'; $attachments = attachments_get_attachments(); $total_attachments = count( $attachments ); for( $i=0; $i&lt;$total_attachments; $i++ ) { $thumb = wp_get_attachment_image_src( $attachments[$i]['id'], 'thumbnail' ); echo '&lt;span class="thumb"&gt;&lt;img src="'.$thumb[0].'" /&gt;&lt;/span&gt;'; } echo '&lt;/a&gt;'; endwhile; echo '&lt;/div&gt;'; next_posts_link(); } </code> Can anyone tell me what I am doing wrong? Thanks
try passing max_num_pages to the function: <code> next_posts_link('Older Entries »', $loop-&gt;max_num_pages); </code>
WP_Query and next_posts_link
wordpress
I'm trying to have sort of a functionality that will let me find all internal links on my site that are pointing to a page. i.e - I want to know all pages on my site that are linking to (any) page in my site. I tried to find sort of a ready made plugin for that, but didn't seem to find. I can develop one by myself, but I wonder what will be the best way to have such functionality. Any ideas will be very welcomed . Thanks
Post Search Approach Pull out all of your posts and pages from the database Iterate through all pages / posts and do a string search on the content - <code> substr_count( 'http://www.yourdomain.com', $page-&gt;content ); </code> Sum up the counts from all the posts / pages This will of course miss allot of links made by plugins, navigation etc - hence "half-ass". Site Scraping Approach Collect all the URLs you want to count links from Iterate through the URL list and use <code> file_get_contents( $the_url ) </code> to get the page / post as a string Perform the string search described above and sum them all up This approach will double count the links persistent through many pages (navigation and sidebars). There is, I'm sure a much better way to do this - but that's all I could come up with off the top of my head. I'm sure you could tweak either approach to suit the degree of coverage you want.
How to find all links between pages
wordpress
I was thinking of adding the following lines of code to my <code> functions.php </code> file: <code> /** * Change the default list of allowed html tags */ add_action('init', 'edittag', 10); function edittag() { define('CUSTOM_TAGS', true); global $allowedposttags, $allowedtags; $allowedposttags = array( 'strong' =&gt; array(), 'em' =&gt; array(), 'ol' =&gt; array(), 'li' =&gt; array(), 'u' =&gt; array(), 'ul' =&gt; array(), 'blockquote' =&gt; array(), 'code' =&gt; array(), 'pre' =&gt; array(), 'a' =&gt; array( 'href' =&gt; array (), 'title' =&gt; array ()), 'img' =&gt; array( 'src' =&gt; array ()), ); $allowedtags = array( 'strong' =&gt; array(), 'em' =&gt; array(), 'ol' =&gt; array(), 'li' =&gt; array(), 'u' =&gt; array(), 'ul' =&gt; array(), 'blockquote' =&gt; array(), 'code' =&gt; array(), 'pre' =&gt; array(), 'a' =&gt; array( 'href' =&gt; array (), 'title' =&gt; array ()), 'img' =&gt; array( 'src' =&gt; array ()), ); } </code> The user will be able to add stuff using the CLEditor (WYSIWYG editor, so the user can't see the code), and the form belongs to the bbPress plugin: I was wondering if my site will become vulnerable to spam, hackers, cracker, etc? If that's the case, what's an easy way of making this stuff more secure? EDIT: If I use Firebug I can see the actual HTML code: For instance, this is what you see if you inspect a bold text (in Firefox): <code> &lt;b _moz_dirty=""&gt;sd&lt;/b&gt; </code> (Not sure if this is dangerous).
Read here about <code> _moz_dirty </code> (Using Google would have given you the same answer - 2nd Result for "_moz_dirty"). Regarding html-stuff: You're offering the ability to add links...
Will my Wordpress site become vulnerable after adding this functions which allows more HTML tags for subscribers?
wordpress
I currently have a new custom post type-- "Books." I have a custom rewrite url that I set when registering my post type: <code> 'rewrite' =&gt; array( 'slug' =&gt; 'books', 'with_front' =&gt; false ) </code> It works great when I visit a specific post, but how do I take control of the /books url for displaying a list of ALL of the books by date posted?
Once way of doing it - I am sure there are other ways too - is to make a page template for books: books.php You can make a copy of page.php and rename it. In the top of the file you place the usual Page Template code as in: <code> &lt;?php /* Template Name: Books */ get_header(); ?&gt; </code> Below the normal loop, you then place the code for a new loop: <code> &lt;?php $loop = new WP_Query( array( 'post_type' =&gt; 'books') ); ?&gt; &lt;?php while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; </code> Don't forget to close it with the call for <code> &lt;?php endwhile; ?&gt; </code> at the end. With this method you can within WordPress add a Page called Books and assign this particular Template to it. This way you can still add general text to the page too and below display the list of all books.
Displaying Posts of a Custom Type
wordpress
I got error of "Call a member function embed() on a non-object", but I can see the result of var_dump is an object. Please help evaluate the following code: This is the Class to create a picture: <code> Class Picture{ //.... function embed() {...} //.... } </code> This is the Class for template: <code> Class Picture_Template{ $obj_id = $post-&gt;ID; $pic = New Picture( $obj_id ); $this-&gt;obj = $pic; } </code> This is a function to test the code: <code> function test_picture(){ global $pic_template; $pic_template = new Picture_Template(); $obj =$pic_template-&gt;obj; $obj_func =$obj-&gt;embed(); echo '&lt;pre&gt;'; var_dump( $obj ); // I can see it is an object var_dump( $obj_func ); // I can see the embed() function output correct result } </code> This is the function that get the error message: <code> function play_button(){ echo get_play_button(); } function get_play_button(){ global $pic_template; if (!$obj ) $obj =&amp; $pic_template-&gt;obj; if ( $obj-&gt;embed(){ //do something } } </code>
To me it seems <code> Picture_Template </code> is worthless - it's not even correctly formed (you need to place run-time code in a constructor ). Plus you also seem to lack the basic understanding of variable scope (like accessing <code> $post </code> and <code> $obj </code> within functions and classes, without globalising them first). Here is what I think you're trying to do; <code> function test_picture() { $picture = new Picture( get_the_ID() ); $picture_result = $picture-&gt;embed(); /* debugging */ echo '&lt;pre&gt;'; var_dump( $picture ); var_dump( $picture_result ); echo '&lt;/pre&gt;'; } function play_button() { echo get_play_button(); } function get_play_button() { $picture = new Picture( get_the_ID() ); if ( $embed = $picture-&gt;embed() ) { // do something &amp; return something } return null; // return nothing if embed failed } </code>
Error of "Call a member function on non object" while var_dump get correct result
wordpress
For some reason, one of my top posts as reported by WordPress Stats is actually non-existent... What I see is: #2147483647 (loading title) and it links to "...?p=2147483647" which returns a 404. Now a bit of background info: I'm actually using the following permalink settings: /%category%/%postname%/ Stats for other posts seem to be fine I migrated from tumblr to WordPress The odd thing is looking into the database where the posts are stored I can not find any reference to that particular ID. Also, I appear to have several 'duplicates' of posts in the database - the difference being in a couple of fields (I'm guessing versioning or something?) I've googled a bit, and the closest I've seem to come is: http://wordpress.org/support/topic/solution-for-id-loading-title-coming-back-from-stats_get_csv-function However, that seems to assume that the ID actually exists, but WordPress/WordPressStats is just for some reason unable to get the title. So does anyone know why WordPress Stats is listing this non-existent page? (It comes #2 in all time top posts!) Thanks!
Turns out WordPress doesn't deal well with post IDs > 2^31. http://core.trac.wordpress.org/ticket/16445 Tumblr in particular has post IDs greater than this, so it's not recommended to keep old post IDs from Tumblr on an import.
WordPress Stats keeps showing non-existent post as a top post?
wordpress
Is there a way (a common one) to duplicate and change a theme widget ? I'm asking this because, I have this widget that displays the recent news and if we click, it will display ALL news, but I wish to create a new widget that lists the latest articles (posts with a category "articles"), and if we click, that lists ALL articles. Is there any widget like this that someone knows about ? If not, where should I look at in order to duplicate and change a theme widget ? Thanks a lot
Widgets extend the Widget Class , search in the theme code for a class that <code> extends WP_Widget </code> . Copy/Paste it, rename it, and change what you'd like. You can also look in the file <code> wp-includes/default-widgets.php </code> and use one of those as a starting point.
Duplicate and change a Theme Widget
wordpress
Ok. Going to try and explain this as best as I can, so bare with me. Anyway, I'm trying to include the default media uploader as a part of my plugin. Currently, I've successfully managed to use the filter <code> attachment_fields_to_edit </code> to hide most of the input fields, leaving only the title &amp; alternate text fields, alongside a custom submit button. When clicked, this button gets the images URL and places it into a <code> div </code> on the parent page. Anyway, so here is my problem. Everything regarding the uploader itself is functioning how I want it to, but currently the filter is applying itself to the media uploader in posts, pages, the media library, etc. I only want the alternative fields &amp; custom button to show within my plugin, but not elsewhere. I've tried everything, but I cannot get it to work. I managed to apply my own query to the media-upload.php URL, and that way I could make the alternative fields only show within my plugin on the thickbox 'library' tab, but when uploading a new image the default fields were showing because Wordpress uses an alternative file to upload the image; async-upload.php. Here is the entire function: http://pastebin.com/5vpecMvL Just some information on the various functions: <code> riva_slider_pro_info() </code> is a function that returns an array of values. <code> riva_slider_pro_uri( $search ) </code> gets $_SERVER[ 'REQUEST_URI' ] and stores it in a variable, search its for the $search parameter and return true or false. In the 'libary' tab within the media uploader thickbox, it is returning <code> true </code> because I have passed a additional query onto the media-upload.php URL (for example, 'media-upload.php?post_id=0$slideshow=true&amp;type=image&amp;TB_iframe=1'). BUT, it is returning <code> false </code> after the user has just uploaded a new image within the same thickbox, because it uses the async-upload.php file instead. Not sure how I could pass the query onto this URL, if it would be possible to make it work that way. I realise this may be hard to follow, but I've tried my best to explain it. I'm literally pulling my hair out over this one and spent a ridiculous amount of time trying to figure it out. Appreciate any comments or suggestions, or ideally a solution! Thanks in advance.
what i ended up doing was launching the thickbox uploaded manually via a jquery click event. then with setInterval i was able to hide the pieces i wanted. jQuery(document).ready(function($) { <code> $('.specialclass').click(function() { //get post id from somewhere (for me this was the row column string = $(this).parents('tr.type-portfolio').attr('id'); if(/post-(\d+)/.exec(string)[1]) post_id = parseInt(/post-(\d+)/.exec(string)[1], 10); tbframe_interval = setInterval(function() { //remove url, alignment and size fields- auto set to null, none and full respectively $('#TB_iframeContent').contents().find('.url').hide().find('input').val(''); $('#TB_iframeContent').contents().find('.align').hide().find('input:radio').filter('[value="none"]').attr('checked', true); $('#TB_iframeContent').contents().find('.image-size').hide().find('input:radio').filter('[value="full"]').attr('checked', true); }, 2000); if(post_id) tb_show('', 'media-upload.php?post_id='+post_id+'&amp;type=image&amp;tab=library&amp;TB_iframe=true'); //tab sets the opened TB window to show library by default return false; }); }); </code>
Manipulating Media uploader
wordpress
am trying out a bit of ajax ( via jquery ) in wordpresss. ... i have everything working correctly but for some reason i have to have the full url to the php handler file even though it's located in the same directory as the script here's the code $.post('http://full/url/to/file.php', $("#form").serialize(), function(data){ do stuff ... }); why cant i just put "file.php" into that - why does it need the full url .... or more importantly what can i put in there that would work on any site without the end user having to put in the full url every time ps i have read the problem with ajax and the path to the php page but i just got a bit more mixed up - i have also read the ajax in plugins page on the wp codex but i couldnt see a relevant example in there .... i'm suspect this mught have something to do with wp_localise_script but im not sure thanks
it needs a full URL because even though it may be the right location relatively on the back end, it's not on the same on the front end, at the URL where your page is ultimately served. you're on the right path with <code> wp_localize_script </code> . you want to enqueue your ajax script, then pass the admin ajax url to <code> wp_localize_script </code> : <code> function my_init_method(){ wp_enqueue_script( 'my-ajax-request', plugin_dir_url( __FILE__ ) . 'js/my_ajax_script.js', array( 'jquery' ) ); wp_localize_script( 'my-ajax-request', 'MyAjax', array( 'ajaxurl' =&gt; admin_url( 'admin-ajax.php' ) ) ); } add_action('init', 'my_init_method'); </code> now within your ajax script you can refer to <code> MyAjax.ajaxurl </code> for the URL. Check this post for a great writeup on properly using ajax in plugins and themes, this is what the WP Codex links to as an example.
ajax in wordpress - path issue
wordpress
I've been stumbling around trying to figure out how to get a specific taxonomy term of the current page so that I can subsequently populate queries on the page for other post types that share the same term. Basically: Page 1 has taxonomy term - education policy page.php has four parts: standard loop that outputs the page, but then has three subsequent queries loop for events that have taxonomy term - education policy loop for reports that have taxonomy term - education policy loop for people that have taxonomy term - education policy I did page specific templates where I could just hardcode the term into the extra loops, but I need to figure out how to do it dynamically (what was originally supposed to be four or five pages is now forty or fifty). I've found a few similar questions, but none that I could really find my way through implementing. stackexchange-url ("Get current page&#39;s taxonomy") which was a little confusing to follow in terms of what was actually being asked. stackexchange-url ("Get the term id belonging to custom taxonomy on a custom single-post-type.php template page.") I hope this makes sense and many thanks.
Hm, if you registered a taxonomy for the "page" object type correctly and then assigned a term of that taxonomy to a page... I believe you can then access the taxonomy and term slugs in the following way: <code> get_query_var( 'taxonomy' ) get_query_var( 'term' ) </code> If you <code> print_r($wp_query) </code> you will see all the parameters that are there when generating a current page that's displayed. With code above you're accessing those parameters from <code> $wp_query </code> . Then to get the term object with full info you can use get_term_by function, like so <code> $term = get_term_by( 'slug', get_query_var('term'), get_query_var('taxonomy') ); echo $term-&gt;name; </code> This will print the "nice" name of the term. I believe if you use <code> get_query_var('term') </code> or <code> $term-&gt;slug </code> (after getting the term object) you can use that slug in all of other queries. Hope that helps. I never used taxonomy for pages. Let me know how you get on.
How to get taxonomy term of the current page and populate queries in the template
wordpress
There must be a solution for this. I am using this solution for chooosing images from media library. http://www.webmaster-source.com/2010/01/08/using-the-wordpress-uploader-in-your-plugin-or-theme/ THE PROBLEM: I am using two meta boxes for custom post type “products”. First consists of two metafields what is for adding two addition product pictures The second one is for creating a simple gallery for this product. Each of them has their own tb_show and window.send_to_editor stuff. The thing is that everything works fine when there are registered only one metabox – the first or the second. If there are registered both of them, the last registered via add_meta_box , brings the error in firebug “ too much recursion” when pressing “Insert into post” button. How to solve this? This is very mission critical, to have two of the metaboxes in post, to add different type of images? Also, the default Insert image in to post should work. Maybe someone has a class for this because I see, the problem is if there are two original_send_to_editor functions registered in one post page.
I think you're running into a problem people mentioned in the comments to that story. Someone else posted about it here: http://www.theenglishguy.co.uk/2010/01/24/multiple-media-uploads-in-wordpress-functions-php/ Basically, the JavaScript from that site should be modified to be more like this: <code> jQuery(document).ready(function() { var formlabel = 0; var old_send_to_editor = window.send_to_editor; var old_tb_remove = window.tb_remove; jQuery('.upload_image_button').click(function(){ formlabel = jQuery(this).parent(); tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true'); return false; }); window.tb_remove = function() { formlabel = 0; old_tb_remove(); } window.send_to_editor = function(html) { if(formlabel){ imgurl = jQuery('img',html).attr('src'); formlabel.find('input[type="text"]').value(imgurl); tb_remove(); } else { old_send_to_editor(); } } }); </code> From there, all you need to do is make sure all the buttons have the class <code> 'upload_image_button' </code> , and make sure the button is a sibling to its corresponding text box and there are no other upload forms in the same parent element.
Too much recursion error when chosing image from image library for two different meta boxes in one post
wordpress
I had an issue with a server that was serious enough to have to take it completely offline and then rebuild the os. I have gotten to the point where the new server is up and running. I have managed to get all the wordpress files and database files transfered over to the new server. The Problem For some reason wordpress is not finding any of the images stored in the wp-content/blogs.dir/... folder. One thing I did notice is that the htaccess file was not copied over, so my best guess is because wordpress reroutes via /folders/ etc that this may be the problem. I did take the distrubtion .htaccess file that I was able to find and added that into the site, but it is not working. Is htaccess the problem? If so how do I regenerate one that will work for the multisite subdomain setup? thanks
Here is the default .htaccess generated by Wordpress for Subdomain Multisite setup: <code> # BEGIN WordPress RewriteEngine On RewriteBase / 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] # END WordPress </code> Let me know If this one doesn't work for you.
Server crashed trying to restore wordpress multisite, images are not found pls help
wordpress
Is there any way to filter all post queries and add a specific taxonomy? Case in point, I have a taxonomy object of "Region" with terms like "Global", "Americas", "Europe", etc. (Users designate their region in their user profile through custom fields which is stored as a usermeta value and added the user cache object.) The idea being that as the signed-in user navigates the site, they'd only see content designated within their region. Obviously I could write a custom query per page to include their region, but I was wondering if there was a way to tap into the query object and add the taxonomy requirement regardless of what the query was for (e.g, post, custom post type, archive page, etc.). Any help would be much appreciated! Thanks.
Below code is an example that does what you want. See tax_query for more information. <code> function my_get_posts( $query ) { // we only need to modify the query for logged in users if ( !is_user_logged_in() ) return $query; $current_user = wp_get_current_user(); // assuming that user's region is stored as user_region meta key $user_region = get_user_meta( $current_user-&gt;ID, 'user_region', true ); $query-&gt;set( 'tax_query', array( array( 'taxonomy' =&gt; 'region', 'field' =&gt; 'slug', 'terms' =&gt; $user_region ) )); return $query; } add_filter( 'pre_get_posts', 'my_get_posts' ); </code>
Filter all queries with a specific taxonomy
wordpress
first of all sorry for my bad english. Let me explain what I`m trying to do: I have a column inside a SQL table with a string using the following format: yy-mm-dd The thing is, it doesn`t use a dateformat type. So, I have my query, where I need to capture all fields with the following specification: value &lt;= '{$thisyear}-{$thismonth}-{$last_day}' any way that I can do that withoung having to change the field format? As long as the tables are generated by the plugin. Any help will be really appreciated, thank you guys!
<code> $yesterday = array ( 'year' =&gt; date('y'), 'month' =&gt; date('m'), 'day' =&gt; date('d')-1 ); $rows = $wpdb-&gt;query($wpdb-&gt;prepare(*emphasized text* "SELECT id, yymmdd FROM plugin_data WHERE yymmdd LIKE '%d-%d-%d", $yesterday['year'], $yesterday['month'], $yesterday['day'] )); foreach ( $rows as $r ) { $id_for_yesterday_rows[]= $r-&gt;id; } </code> Now you have all ids or rows that were submitted yesterday in an array.
Help with wordpress custom query and advanced custom fields plugin
wordpress
I have a family website, private, requires a WordPress account, in WordPress. Some of my family members would like to get the option for notifications of new posts by email or text message. Email seems easy enough, there are plugins and services for that. But I'm concerned about text messages because we are geographically spread out, and I would like the option to queue the messages so that they are sent to users only within hours they choose. External services or services based off RSS are not a great fit because the RSS feeds are not public and I'd like to keep it that way. Is there a plugin suited to these specific requirements?
I'd say there's three specific requirements here; Allow users to choose notification times, timezone aware Hook into <code> transition_post_status </code> to listen up for new posts, and then take action Find a decent SMS API For 1), hook into <code> show_user_profile </code> to output your time picker field(s), and <code> personal_options_update </code> to save them. You could detect the user's timezone automatically, either via IP address or JavaScript, but I'd recommend just a <code> &lt;select /&gt; </code> that allows them to pick their locale manually (see <code> wp-admin/options-general.php </code> , lines <code> 138 </code> to <code> 250 </code> for how WordPress generates a timezone select). As for 2), check out my other answer on stackexchange-url ("new post notification"). You'll obviously want to modify this to notify all your users (as opposed to just the admin), but it should start you off nicely. Finally 3), unless you can find an stackexchange-url ("SMS API") where you can specify the time the message gets sent, you'll have to take advantage of WP Cron . Rather than setting an event for each user, I'd advise setting up an hourly one, that simply looks for any users who should now be notified &amp; fires an SMS request.
Mechanism to send to users of secured WordPress install new notifications by SMS or email?
wordpress
http://adambrown.info/p/wp_hooks/hook/plugin_action_links_%7B$plugin_file%7D Says the hook is deprecated. However, the {$prefix}plugin_action_hook_{$plugin_file} is not. I poked around the <code> wp-admin/includes/class-wp-plugins-list-table.php </code> file for the hook, and found this: <code> $actions = apply_filters( $prefix . "plugin_action_links_$plugin_file", $actions, $plugin_file, $plugin_data, $context ); </code> <code> $prefix </code> is defined a few lines above: <code> $prefix = $screen-&gt;is_network ? 'network_admin_' : ''; </code> Since I was able to get my add_filter call to <code> plugin_actions_row_{$plugin_file} </code> to work, I'm assuming the filter hook is still there. Well, sort of: the filter is still available as it's not a network admin screen. Correct? And one could use... <code> add_filter( 'network_admin_plugin_action_links_{$plugin_file}', 'do_something' ) </code> ...to put a link into the network's plugin screen?
Yes, both should work as expected: <code> "plugin_action_links_{$plugin_file}" </code> <code> "network_admin_plugin_action_links_{$plugin_file}" </code> Note that I'm using <code> " </code> instead of <code> ' </code> . PS: The term is deprecated , not depreciated.
plugin_action_links Filter Hook Deprecated?
wordpress
I'm using Posts 2 Posts plugin. I've got 2 custom types : movies and actors. I created a movie => actor connection so that for each movie I can see which actors play in. But as far as I understand, in order to find out all the movies a particular actor has played in, you must create an actor => movie connection AS WELL. So if create a The Dark Knight => Christian Bale connection, I MUST create a Christian Bale => The Dark Knight as well. Because otherwise I won't be able to know that Christian Bale played in that movie based on a "Christian Bale" search. Is that correct ? If so, is there any way to make it less burdensome ?
To see connections on both edit screens, set <code> reciprocal </code> to <code> true </code> , but note this is for the UI only, it doesn't affect connections otherwise. <code> function my_connection_types() { if ( !function_exists( 'p2p_register_connection_type' ) ) return; p2p_register_connection_type( array( 'from' =&gt; 'movies', 'to' =&gt; 'actors', 'reciprocal' =&gt; true ) ); } add_action( 'init', 'my_connection_types', 100 ); </code>
[Plugin: Posts 2 Posts] reciprocal connections
wordpress
I'm doing up a blog at the moment where each post is accompanied by the name of a song. Adding the songs to the posts is fairly easily done via custom fields. However, I also need to have a page which lists all the songs in one place. Can this be done without using a plugin? If so, how? (And if not, then what's the best plugin to use to do it?) Thanks.
I suggest using shortcode, as this'll easily allow you embed the song list anywhere in your content, in any page or post. UPDATE: I got a little carried away, and ended up with this! <code> function song_list_shortcode( $attrs ) { $r = ( object )wp_parse_args( $attrs, array( 'format' =&gt; '%post_title - %link', 'link' =&gt; '%song_key_name', 'key' =&gt; 'song_key_name' ) ); $query = new WP_Query( array( 'meta_query' =&gt; array( array( 'key' =&gt; $r-&gt;key ) ), 'nopaging' =&gt; true, 'update_post_term_cache' =&gt; false ) ); if ( !$query-&gt;have_posts() ) return ''; $meta_keys = array(); foreach ( array( 'format', 'link' ) as $type ) { // find meta keys if ( !preg_match_all( '#%([a-z0-9_-]+)#', $r-&gt;$type, $_keys ) ) continue; $_keys = array_flip( $_keys[1] ); unset( $_keys['post_title'], $_keys['link'] ); // don't want these, not meta keys $meta_keys = $meta_keys + $_keys; // add new keys on to meta key stack } if ( !empty( $meta_keys ) ) $meta_keys = array_keys( $meta_keys ); $output = '&lt;ul class="songs"&gt;'; while ( $query-&gt;have_posts() ) { $query-&gt;the_post(); $format = $r-&gt;format; $link = $r-&gt;link; if ( !empty( $meta_keys ) ) { // grab all meta data in one swoop (should be cached from query) $meta_data = get_post_custom( $query-&gt;post-&gt;ID ); // swap out all meta key names with their actual value! foreach ( $meta_keys as $key ) { // using get_post_custom(), all meta data values are arrays if ( isset( $meta_data[ $key ][0] ) ) $value = esc_html( $meta_data[ $key ][0] ); else $value = ''; // meta key not found, so replace with blank list( $format, $link ) = str_replace( "%$key", $value, array( $format, $link ) ); } } // swap out %post_title with actual post title list( $format, $link ) = str_replace( '%post_title', get_the_title(), array( $format, $link ) ); // swap out %link in $format with actual $link $output .= '&lt;li&gt;' . str_replace( '%link', '&lt;a href="' . get_permalink() . '"&gt;' . $link . '&lt;/a&gt;', $format ) . '&lt;/li&gt;'; } wp_reset_postdata(); $output .= '&lt;/ul&gt;'; return $output; } add_shortcode( 'song-list', 'song_list_shortcode' ); </code> You can use it like so; <code> [song-list format="%post_title - %link - %song_date_meta_key"] // The post title - &lt;a href="/post/"&gt;Song Name&lt;/a&gt; - Song Date </code> See how using <code> % </code> indicates a meta key, which'll get swapped out with the value at run-time. Also note that <code> %post_title </code> and <code> %link </code> are two special parameters that get swapped with the post title and anchor link, respectively. You can also format the contents of the link text in the same way; <code> [song-list link="Date: %song_date_meta_key"] // Post Title &lt;a href="/post/"&gt;Date: Song Date&lt;/a&gt; </code> Finally, the <code> key </code> attribute controls which posts are retrieved. <code> [song-list key="song_name"] // Retrieves all posts with the meta key 'song_name' </code> I'd recommend replacing the hard-coded defaults at the beginning of the function with your most often used parameters.
Populating a page with content from post custom fields
wordpress
REQUIRED: Comments are displayed as "Off" while they aren't in wp-admin. Comment form is not displayed in these cases, while it is when a unit test post already has comments. i have installed the Test data . and on some post and comment test post pages. these pages had some comments. and there is also a Comment form under all the comments. why it notices me,"Comment form is not displayed in these cases, while it is when a unit test post already has comments." comments are displayed as "Off" while they aren't in wp-admin, what's this meaning? how to correct it?
OK, I figured it out. It took a bit of digging and many bad suggestions. The solution is actually quite simple. Just replace this in your theme files: Where you have this : <code> &lt;div class="comments"&gt; &lt;?php comments_template(); ?&gt; &lt;/div&gt; </code> Replace it with this: <code> &lt;div class="comments"&gt; &lt;?php if ( comments_open() ) : ?&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;?php comments_template(); ?&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;?php endif; ?&gt; &lt;/div&gt; </code> Note: I thought this was a little ironic, but if you switch your theme to twenty-eleven (the theme that replaces twentyten in 3.2 Beta) it doesn't remove comments like they suggest you should. You can replace the other code that you are using for the comments_popup_link with the similar condition like this: <code> &lt;div class="comments"&gt; &lt;?php if ( comments_open() ) : ?&gt;&lt;br /&gt;&lt;p&gt;&lt;br /&gt;&lt;?php comments_popup_link('0', '1', '%'); ?&gt;&lt;br /&gt;&lt;/p&gt;&lt;br /&gt;&lt;?php endif; ?&gt; &lt;/div&gt; </code> I'm not sure how the theme review works 100%, but the theme check plug-in says you passed! Here is a screenshot. Good Luck!
what's meaning of it when submit a theme?
wordpress
Is there a plugin or snippet that would: Add an email input form to each post Send a predefined message when new media (or attachments) has been uploaded for that post only The requested functionality here is different from other plugins I am aware of because it targets only the end user and only on new media upload (as compared to comments). Any insight at all would be helpful!
As for the email input form, you can use any plugin for Custom Fields ( I use Advanced Custom Fields or Custom Content Type Manager ) or add you own meta box ( tutorial ). And for sending an email to the address inserted as a custom field, use the following code. The custom field is named email_warn . The filter <code> wp_mail_content_type </code> enables html content for emails. And <code> add_attachment </code> will fire at each upload, pull the parent ID and send an email if the custom field is defined and is a valid email <code> add_filter( 'wp_mail_content_type', 'wpse_20324_mail_html' ); add_filter( 'add_attachment', 'wpse_20324_post_upload' ); function wpse_20324_mail_html() { return "text/html"; } function wpse_20324_post_upload( $attachment_ID ) { $uploaded = get_post( $attachment_ID ); $email = get_post_meta( $uploaded-&gt;post_parent, 'email_warn', true ); if( isset( $email ) &amp;&amp; is_email( $email ) ) { /** * The message will contain all post info about the uploaded file */ $vardump = print_r( $uploaded, true ); $message = '&lt;pre&gt;' . $vardump . '&lt;/pre&gt;'; $headers = 'From: Test WPSE &lt;[email protected]&gt;' . "\r\n"; wp_mail( $email, 'subject', $message, $headers ); } } </code>
Is email post notify visitor on new media upload possible?
wordpress
Not sure if this is possible, but bear with me. I think I am halfway there. First a little background: I'm using the build in hierarchy in WordPress to form relationships between post types. I have a post type called series that holds info on a TV series. I have another post type called content that has info on specific episodes and I use the built in post_parent field on the posts data table to point to a series. So basically, I'm trying to do a rewrite/permalink structure similar to this for content: http://website.com/%series-name%/%content-type%/%postname% content-type is a taxonomy attached to content that has a few terms; episode, movie and special. My idea to prevent rewrite collisions was to use this code, inspired by a previous question I had asked stackexchange-url ("here") <code> add_filter( 'rewrite_rules_array', 'content_rewrite_rules',10,1); function content_rewrite_rules( $rules ) { $custom_rules = array(); $type_terms = get_terms('veda_content_type', array('hide_empty'=&gt;false)); if(!is_wp_error($type_terms) &amp;&amp; sizeof($type_terms) &gt; 0) { foreach ($type_terms as $term) { $custom_rules['([^/]+)/'.$term-&gt;slug. '/([^/]+)/?$'] = 'index.php?post_type=veda_content&amp;series_name=$matches[1]&amp;pagename=$matches[2]'; } } return array_merge($custom_rules , $rules); } </code> Using the rewrite analyzer, it seems that it sorta works, except it shows that the series_name query_var is crossed out in red and I'm not sure what that means. My question is: is there another, more efficient way to create the permalink that I want? Also, what the cross out mean? EDIT: I'm trying to see if the rewrite works and my server is giving me bad request errors
I did find some solutions to the problems I had above: Red strike through in the Rewrite Analyzer plug in means that the query_var wasn't defined before hand, so WP automagically deletes them. The other problem I had was solved here: stackexchange-url ("Using %postname% tag with a Custom Permastruct creates 400 Bad Request Errors from the server")
Help with a TV series Rewrite structure
wordpress
Having issues showing my post in separate list based on category I have a static home page set my page: "home" and I have the blog set to my page: "Inspiration" I have 2 main categories "inspiration" and "Portfolio" and those catagories are also the titles of my menu items. So I have Home, Inspiration, and Portfolio. But when I go to portfolio it is just a page not a list of the post in the Portfolio category. I have no problem editing the code since the whole theme is completely custom I am just not sure what to add to make the portfolio page a blog as well. You can see the half finished site here. www.2020mediaonline.com/wordpress I am using WordPress 3.1.1. Any help would be awesome.
i can't able to understand your question,but i guess ,My answer is login as a Wordpress Admin and select settings-> Reading...In There you Select Static Page &amp; Set Front Page and Post page as you want.I think you got Answer.if not means just mention what you want exactly? :)
Seperate WordPress catagories into sepeat list on seperate pages
wordpress
I need to take a site that is installed as a subdomain blog on a multi site install and move it to it's own domain on a standalone wordpress installation. How can this be done? I am running into trouble with the path to the images in posts because multi site uses <code> /blogs.dir/blogid/ </code> Can this be done?
Although I have not tested a use case such as yours. If the trouble is with path to the images in the posts and other you can give WordPress OneClick Migration a try. It was designed with Database level migration but it should work. You may need to run it in forced mood. See the Readme file for full details.
How to convert multi-site to single site
wordpress
I have this code: <code> $args=array( 'public' =&gt; true, '_builtin' =&gt; false ); ?&gt; &lt;select id="&lt;?php echo $this-&gt;get_field_id('posttype'); ?&gt;" name="&lt;?php echo $this-&gt;get_field_name('posttype'); ?&gt;"&gt; &lt;?php foreach(get_post_types($args,'names') as $post_type) { ?&gt; &lt;option &lt;?php selected( $instance['posttype'], $post_type ); ?&gt; value="&lt;?php echo $post_type; ?&gt;"&gt;&lt;?php echo $post_type; ?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; </code> I make custom posts <code> function my_post_type_interior_articles() { register_post_type( 'interior_articles', array( 'label' =&gt; __('Interior Design Articles'), 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_nav_menus' =&gt; false, 'menu_position' =&gt; 5, 'supports' =&gt; array( 'title', 'custom-fields', 'editor', 'excerpt', 'thumbnail') ) ); } add_action('init', 'my_post_type_interior_articles'); </code> in dropdown shows "interior_articles" , but i need to show "Interior Design Articles" How to show cutom post labels in options?
You just need to pull the Labels via <code> get_post_type_object(); </code> <code> &lt;?php $args=array( 'public' =&gt; true, '_builtin' =&gt; false ); $output = 'names'; $operator = 'and'; $post_types=get_post_types($args,$output,$operator); ?&gt; &lt;select id="" name=""&gt; &lt;?php foreach ($post_types as $post_type ) { $label_obj = get_post_type_object($post_type); $labels = $label_obj-&gt;labels-&gt;name; ?&gt; &lt;option &lt;?php selected( $instance['posttype'], $post_type ); ?&gt; value="&lt;?php echo $post_type; ?&gt;"&gt;&lt;?php echo $labels; ?&gt;&lt;/option&gt; &lt;?php } ?&gt; &lt;/select&gt; </code> Read more here: http://codex.wordpress.org/Function_Reference/get_post_type_object
How to show cutom post labels in options?
wordpress
I want to develop a WordPress theme from scratch. Is there any wireframe tool in which I can design the a complete page and it exports the html/php file against it. I want a free tool.
I personally do not know of any free tool that would achieve what you are looking for. The closest thing would be to use a "slice and chop" company that would take your designs and slice them up for you at a price though. There is a great "blank" wordpress theme out there that I use on all of my projects. It has all of the files you need for a theme, with most (if not all) of the queries that you need. All you have to do is pretty much style it. However, the Wordpress Codex is a great resource for learning all the nuts and bolts of wordpress. I know it has been a life saver to me over the years.
Wireframe tool for WordPress theme
wordpress
I'm trying to use contact form 7 on my site. The only server side validation that it seems to do is check if required fields have been entered. Isn't there a danger if someone sends several MB of data through tools like tamper data? Will I need to rewrite the plugin code to take care of validation?
It doesn't take much to tamper data when you use HTML forms; you don't even need a plug-in to do that. That's inherent in all HTML forms. If you're that worried about people tampering with your data, yes, you'll need to rewrite the plug-in code to use session variables or a digital signature.
Server side validation for Contact Form 7
wordpress
I have a field on the admin side where a user enters a number for a price. If a user enters 1000000 I'd like to be able to display on the front-end $1,000,000. Any ideas on how to accomplish this? Edit More details, the post is a custom post type 'property'. To add the meta fields on the back-end I'm using Meta Box Script, http://www.deluxeblogtips.com/2011/03/meta-box-script-update-v30.html The code to display the numbers on the front-end I use <code> $meta = get_post_meta(get_the_ID(), 'rw_propPrice', true); echo $meta; </code>
To format number, you can use the function <code> number_format_i18n </code> (it's not documented now, but you can see its source here ). Its work is format the number based on the language. You might want to look at <code> number_format </code> ( PHP built_in function , and is used by <code> number_format_i18n </code> ) to have more control to decimal point and thousand separator. In your case, this code will help you: <code> $meta = get_post_meta(get_the_ID(), 'rw_propPrice', true); echo '$' . number_format($meta, 0, '.', ','); </code>
Add dollar sign and commas to a number?
wordpress
Is there a way to code "Restore Defaults" button into a plugin options page? I'm writing a plugin right now that has sets up some default values on activation (via <code> register_activation_hook </code> ), and I'd like to give users the option to restore those defaults again with a click. Possible? Thanks!
Nevermind, answered my own question: http://www.keyframesandcode.com/resources/javascript/jQuery/demos/populate-demo.html Used that to update all the text and drop downs. Couldn't get it to work with my checkboxes, but a few other lines of jQuery took care of those. I like the idea of just auto filling the form with the defaults, rather than submitting it right away.
Restore a Plugin's Default Settings
wordpress
In the get_blog_excerpt() function below, the excerpt_more filter works perfectly when the post excerpt is not present, however, when the post has an excerpt, I'm not getting the "Read More" link. I understand that the_excerpt first checks to see if a post excerpt is present, which is fine, but I want the read more link applied to it too. What do I need to change in order to make the excerpt_more apply in all cases? <code> function get_blog_excerpt(){ add_filter('excerpt_length', 'ce4_excerpt_length'); add_filter('excerpt_more', 'ce4_excerpt_more'); return the_excerpt(); } function ce4_excerpt_length($length) { return 150; } function ce4_excerpt_more($more) { global $post; return '...&lt;a href="'. get_permalink($post-&gt;ID) . '"&gt;Read More&lt;/a&gt;'; } function get_blog_links(){ global $post; setup_postdata($post); $myposts = get_posts($args);echo '&lt;div id="menuFooterRecent" class="blog"&gt;'; echo '&lt;ul&gt;'; foreach($myposts as $idx=&gt;$post){ ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php echo get_blog_excerpt(); echo '&lt;div style="clear:both"&gt;&amp;nbsp;&lt;/div&gt;';?&gt;&lt;/li&gt; &lt;?php } echo '&lt;/ul&gt;&lt;/div&gt;'; } </code> The code above is inside functions.php The code below is inside archive.php <code> &lt;?php if(is_category()){ if (get_query_var('cat') == get_category_by_slug('blog')-&gt;term_id){ get_blog_links(); } else { get_category_links(); } } ?&gt; </code>
I'm going to assume that you're calling <code> get_blog_excerpt() </code> in your template somewhere? If so, what happens if you simply call <code> the_excerpt() </code> , and then pull the two <code> add_filter() </code> calls out of the container function? i.e. <code> functions.php </code> would just look like: <code> function ce4_excerpt_length($length) { return 150; } add_filter('excerpt_length', 'ce4_excerpt_length'); function ce4_excerpt_more($more) { global $post; return '...&lt;a href="'. get_permalink($post-&gt;ID) . '"&gt;Read More&lt;/a&gt;'; } add_filter('excerpt_more', 'ce4_excerpt_more'); </code> And in your template, you would just call <code> the_excerpt() </code> . If that works, then I suspect the issue is that your filters aren't getting applied - probably due to being wrapped in the container function.
How to make the excerpt_more filter apply to the actual post excerpt?
wordpress
Hi to all I'm trying to create a function that can ECHO the excerpt of a random post from a choosen category. What I did up to now is: <code> &lt;?php function $titoloslide() = { query_posts(array('orderby' =&gt; 'rand', 'category_name' =&gt; 'testimonianze', 'showposts' =&gt; 1)); if (have_posts()) : while (have_posts()) : the_post(); "&lt;div class='testimonianzefurgonihome'&gt;&lt;a href='#' title='Testimonianze noleggio furgoni KobalRent'&gt;"the_excerpt();"&lt;/a&gt;&lt;/div&gt;" endwhile; endif; wp_reset_query();};?&gt; </code> Obviously... it doesn't work! Is there anyone who can help me? Thank you very much! Why i need all of this inside a function? Because I need to use it as title tag of some images and stuff like this so I can't write all my code inside title="" and I tought that a function could do the trick. I'm trying to use NivoSlider so I need to put this code as a title tag to an image to be shown. example: " title=" /> This function takes a random post from category testimonianze and shows his excerpt (I think it's easy to understan this :P The code works if I use it like this: <code> &lt;?php query_posts(array('orderby' =&gt; 'rand', 'category_name' =&gt; 'testimonianze', 'showposts' =&gt; 1)); if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div class="testimonianzefurgonihome"&gt;&lt;a href="#" title="Testimonianze noleggio furgoni KobalRent"&gt;&lt;?php the_excerpt(); ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php endif;?&gt; &lt;?php wp_reset_query(); ?&gt; </code> But no way to have a working version in any other way even after code corrections. Any idea or suggestions? (Maybe some prays will work too :P )
cleaned up syntax errors: <code> &lt;?php function titoloslide() { query_posts(array( 'orderby' =&gt; 'rand', 'category_name' =&gt; 'testimonianze', 'posts_per_page' =&gt; 1 )); if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div class='testimonianzefurgonihome'&gt;&lt;a href='#' title='Testimonianze noleggio furgoni KobalRent'&gt;&lt;?php the_excerpt(); ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;?php endwhile; endif; wp_reset_query(); } ?&gt; </code>
Function to show random posts from a category
wordpress
I have my plugin all set-up using the Settings API and working but what I have is two manual functions in my plugin that can be run by the admin user by visiting the following URL's <code> &lt;?php echo admin_url(); ?&gt;options-general.php?page=wordpress-file-monitor-plus&amp;sc_wpfmp_action=1&amp;sc_wpfmp_scan=1 &lt;?php echo admin_url(); ?&gt;options-general.php?page=wordpress-file-monitor-plus&amp;sc_wpfmp_action=1&amp;sc_wpfmp_reset_settings=1 </code> I'm using the <code> admin_init </code> hook to lookout for these GET parameters and do those functions. The functions run fine and the user is back on my plugin settings page but the GET parameters are still in the URL. Not a big issue but if the user then goes ahead and save the settings those GET parameters are sent again and thus running those functions again. Why does the Settings API send those parameters when submitting the settings form? The action of the form is to submit to <code> options.php </code> . The only way around my issue I can think of is that after those manual functions have run its code in <code> admin_init </code> is to run a redirect to the settings page without the GET parameters, but if I do this I will lose my admin notices I'm trying to show to the user. Anyway got any suggestions on how I can get around this problem. Maybe you think there is a better way to run these manual functions? EDIT: full settings code: http://pastebin.com/Gk5RF5Lc
Why does the Settings API send those parameters when submitting the settings form? Quite frankly, it doesn't. As you already mentioned, your form simply POST's to <code> options.php </code> , which in turn handles the request, updates the database, and then redirects back to the referer . How the referer is fetched is down to the function <code> wp_get_referer() </code> ; <code> function wp_get_referer() { $ref = ''; if ( ! empty( $_REQUEST['_wp_http_referer'] ) ) $ref = $_REQUEST['_wp_http_referer']; else if ( ! empty( $_SERVER['HTTP_REFERER'] ) ) $ref = $_SERVER['HTTP_REFERER']; if ( $ref !== $_SERVER['REQUEST_URI'] ) return $ref; return false; } </code> That's why you're getting sent back to your options page with the action parameters still there - because they were present in <code> $_SERVER['HTTP_REFERER'] </code> . But you'll also see that you can override this behaviour, by placing a hidden input inside your form like so; <code> &lt;input type="hidden" name="_wp_http_referer" value="&lt;?php echo admin_url( 'options-general.php?page=wordpress-file-monitor-plus' ); ?&gt;" /&gt; </code> Now <code> options.php </code> will always redirect back to... http://example.com/wp-admin/options-general.php?page=wordpress-file-monitor-plus ...regardless of whatever was in the query string previously.
GET parameters interfere with my plugin settings
wordpress
I am trying to get three loops to display. they all belong to the same post type and the same taxonomy family. but i'm trying to separate the taxonomy by three different values. <code> $argsOwners = array( 'tax_query' =&gt; array(array('taxonomy' =&gt; 'position', 'field' =&gt; 'slug', 'terms' =&gt; 'senior-management' ))); $the_query_owners = new WP_Query( $argsOwners ); </code> then i <code> &lt;?php wp_reset_postdata(); // reset the query ?&gt; </code> then i <code> $argsSales = array( 'tax_query' =&gt; array(array('taxonomy' =&gt; 'position', 'field' =&gt; 'slug', 'terms' =&gt; 'sales' ))); $the_query_sales = new WP_Query( $argsSales ); </code> and i repeat again for the third term of "admin". the problem is only the first query will work. any ideas? EDIT EDIT EDIT I think i figure what the issue is. It had to do with whether is was logged in or not. if i was logged in then i would only see the for query displayed. but if im logged out then i get all 3 perfectly.
As @TheDeadMedic said, you've to work like that. in the default loop like: <code> while( have_posts() ) : the_post endwhile; </code> in this case, the loop is running with the default <code> $wp_query </code> variable. But as you are running custom queries, you need to use <code> while( $query_obj-&gt;have_posts() ) : $query_obj-&gt;the_post(); </code> like that But while logged in and logged out, you shouldn't get different results :S
cannot get multiple loops using tax_query
wordpress
I need to build a php foreach that goes through all my terms in my custom taxonomy 'Section'. I know how to get a foreach of all the terms in 'Section', but what i cant do is build it with levels. I want the top parent term to be the heading, and its children will be displayed in a list. Heres an html example of the output i need. <code> &lt;div class="accordian"&gt; &lt;div&gt; Term Parent &lt;/div&gt; &lt;ul&gt; &lt;li&gt; Term Child &lt;/li&gt; &lt;li&gt; Term Child &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="accordian"&gt; &lt;div&gt; Term Parent &lt;/div&gt; &lt;ul&gt; &lt;li&gt; Term Child &lt;/li&gt; &lt;li&gt; Term Child &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code>
I managed to work on it a little more and built the answer myself. Heres the code i needed. <code> &lt;?php $parent_terms = get_terms('section', 'orderby=name&amp;hide_empty=0&amp;parent=0'); foreach ( $parent_terms as $parent_term ) { ?&gt; &lt;div class="accordian open"&gt; &lt;div class="accordian-title module-gradient"&gt;&lt;?php echo $parent_term-&gt;name; ?&gt;&lt;/div&gt; &lt;?php $get_parent = get_term_by('name', $parent_term-&gt;name, 'section'); $parent_id = $get_parent-&gt;term_id; $child_terms = get_terms('section', 'orderby=name&amp;hide_empty=0&amp;parent='.$parent_id); if ( count($child_terms) &gt; 0 ) { ?&gt; &lt;div class="accordian-menu"&gt; &lt;?php foreach ( $child_terms as $child_term ) { ?&gt; &lt;div class="accordian-item"&gt; &lt;?php echo $child_term-&gt;name; ?&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;?php } ?&gt; </code>
Leveled - Terms foreach
wordpress
I tried using wp_list_categories, but that just gives me a list of the categories. I currently have this code in my category-recipes.php file: <code> &lt;ul class="subcats-list"&gt; &lt;h2 class="subcats-title"&gt;&lt;?php echo get_cat_name(38); ?&gt;&lt;/h2&gt; &lt;?php $recipes = new WP_Query(); $recipes-&gt;query('showposts=5&amp;orderby=rand&amp;cat=38&amp;post_type=recipe'); while ($recipes-&gt;have_posts()) : $recipes-&gt;the_post(); ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt;&lt;!-- subcat --&gt; </code> I was thinking about putting a link tag before the <code> get_cat_name </code> but I am not sure what to include in it.
Use get_category_link. Your code (relevant part) will look like: <code> &lt;h2 class="subcats-title"&gt;&lt;a href="&lt;?php echo get_category_link(38); ?&gt;"&gt;&lt;?php echo get_cat_name(38); ?&gt;&lt;/a&gt;&lt;/h2&gt; </code>
Need category header to link to category archive list
wordpress
I would like to add a public profile page to the authors and others contributors in my site. where visitors can see their profile info. I don't wanna use Buddypress, is it possible with WordPress alone?
bainternet posted something in this thread that will help you, (this is actually editing user profiles from frontend) but it will give you the idea, then just echo the fields out on author.php
How to create a public profile for authors/contributors/users?
wordpress
I have a script in archive.php, which is outside the loop, that calls on the function get_blog_links() to list all posts that belong the the current category (my "blog" category). I'm trying to do some trace testing inside the "get_blog_excerpt() function in order to write out either the post excerpt or (if no excerpt appears) the first 55 words of content (the_excerpt) for each post. However, I'm unable to obtain a reference to the_excerpt in my function. Any help much appreciated. <code> //Blog Listing function get_blog_links(){ $myposts = get_posts(); echo '&lt;div&gt;'; echo '&lt;ul&gt;'; foreach($myposts as $idx=&gt;$post){ ?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; // THE FUNCTION CALL IM WORKING ON... &lt;?php echo get_blog_excerpt();?&gt;&lt;/li&gt; &lt;?php } echo '&lt;/ul&gt;&lt;/div&gt;'; } function get_blog_excerpt(){ // return get_the_excerpt(); WORKS // return the_permalink(); WORKS // return the_excerpt(); DOES NOT WORK? // return get_the_content(); DOES NOT WORK? } </code>
I think you have to <code> setup_postdata() </code> with <code> get_posts() </code> to get things that rely on global variables to work. or explicitly pass the post id with the function.
How to obtain a reference to the_excerpt() from custom loop
wordpress
My understanding is that <code> site_url() </code> returns the location where the wordpress core files are. So, if my blog is hosted at <code> http://example.com/blog </code> then <code> site_url() </code> returns <code> http://example.com/blog </code> But then how does <code> home_url() </code> differ? For me, <code> home_url() </code> returns the same thing: <code> http://example.com/blog </code> If that's correct, then can I get wordpress to return <code> http://example.com/ </code> ?
You are asking two questions at once: What's the difference between <code> home_url() </code> and <code> site_url() </code> ? How do I get WordPress to return the URL root without the subdirectory where it's installed? Here are the answers, and I confirmed with Andrew Nacin, a core developer of WordPress, as well as ran some server tests to confirm what Andrew told me. Question # 1 In General > Settings of wp-admin, <code> home_url() </code> references the field labeled "Site Address (URL)". Confusing, huh? Yeah, it says "Site Address" so you might assume <code> site_url() </code> , but you'd be wrong . Run your own test and you'll see. (You can temporarily drop an <code> echo H1 </code> field with <code> site_url() </code> and <code> home_url() </code> values at the top of your your theme's functions.php.) Meanwhile, <code> site_url() </code> references the field labeled "WordPress Address (URL)" in General > Settings. So, if you're wanting to reference where a physical path might be such as calling a plugin's folder path on the URL to load an image, or calling a theme's folder path to load an image, you should actually use other functions for those - look at <code> plugins_url() </code> and <code> get_template_directory_uri() </code> . The <code> site_url() </code> will always be the location where you can reach the site by tacking on <code> /wp-admin </code> on the end, while <code> home_url() </code> would not reliably be this location. The <code> home_url() </code> would be where you have set your homepage by setting General > Settings "Site Address (URL)" field. Question # 2 So, if I have placed my blog in <code> http://example.com/blog </code> , and <code> example.com </code> is just some static site where I have like a portfolio theme, then this would be a scenario that lines up with your question. In such a case, then I would use this snippet of code: <code> &lt;?php function getDomain() { $sURL = site_url(); // WordPress function $asParts = parse_url( $sURL ); // PHP function if ( ! $asParts ) wp_die( 'ERROR: Path corrupt for parsing.' ); // replace this with a better error result $sScheme = $asParts['scheme']; $nPort = $asParts['port']; $sHost = $asParts['host']; $nPort = 80 == $nPort ? '' : $nPort; $nPort = 'https' == $sScheme AND 443 == $nPort ? '' : $nPort; $sPort = ! empty( $sPort ) ? ":$nPort" : ''; $sReturn = $sScheme . '://' . $sHost . $sPort; return $sReturn; } </code>
What's the difference between home_url() and site_url()
wordpress
Is it possible to call the_excerpt() with tags intact? I'd like to create a excerpted listing of my posts in a specific category, but I'd also like the links and formatting carried over from the post content. I'm currently using the_excerpt() which otherwise works fine, however, the tags are stripped out. I can't find a filter to place on the_excerpt() to do this, so barring that, is it possible to filter the_content() to pull the first 100 words with tags and a read more link at the end?
Actually, I just did something like this for a Drupal site. I based my truncation function on this: Truncate text preserving HTML tags with PHP Use the final version of the function at the end of the comments. The function takes its <code> $length </code> parameter in characters, not words, but you can probably use the general rule-of-thumb of 5 characters per word to estimate, if needed. Hook your function to the <code> get_the_excerpt </code> filter, and you should be in pretty good shape.
How to call the_excerpt() with tags or the_content() as an excerpt?
wordpress
<code> get_categories() </code> and related functions, by default, don't return empty categories - categories with no posts. I thought that, since there may be some underlying code checking the post counts, is it possible to additionally filter that list to only include categories that themselves contain posts that have a certain, specific Tag associated? Or is there a somewhat simple alternate method of getting that information? For example, if I had some posts with a Tag of "audio", I'd like a way to use <code> get_categories() </code> (or similar results) but only retrieve a list of categories that contained posts with that "audio" Tag. I am aware that I may have to use the Tag ID directly. I'm just looking for the "best", or most appropriate way to do this. Thanks!
Check out my answer on stackexchange-url ("how to get terms that are associated with others through the posts that they're attached to"). In your case, you could put it into practice like so; <code> $category_IDs = get_terms_soft_associated( 'category', array( 'taxonomy' =&gt; 'post_tag', 'field' =&gt; 'slug', 'terms' =&gt; 'audio' ) ); wp_list_categories( array( 'include' =&gt; $category_IDs ) ); </code> Or for a more general-purpose approach, use a function; <code> /** * List categories for posts that have $tag. * * @param string|int|object $tag Tag slug, ID or object * @param string|array $args Args to pass to {@see wp_list_categories()} * @return string */ function list_categories_with_tag( $tag, $args = '' ) { if ( is_object( $tag ) ) $tag = ( int ) $tag-&gt;term_id; $args = wp_parse_args( $args ); $args['include'] = get_terms_soft_associated( 'category', array( 'taxonomy' =&gt; 'post_tag', 'field' =&gt; is_numeric( $tag ) ? 'term_id' : 'slug', 'terms' =&gt; $tag ) ); return wp_list_categories( $args ); } </code>
When using get_categories or similar, is it possible to filter results that contain certain Tags as well?
wordpress
Not sure when it happened but the custom permalinks for pages on my client's Wordpress site have broken. I can fix it by reverting back to the default permalinks and then using the custom permalinks, but they break again whenever my clients edits a page. Blog posts, archives, tags, categories, and custom post types permalinks all work fine, it's only pages that 404 when using custom permalinks. The site has an .htaccess file with 666 permissions with the following in the file: <code> &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; </code> It also has mod_rewrite enabled. Using Wordpress 3.1.3 It's not the plugins because I have disabled all of them and the permalinks for pages still don't work. Please help.
I figured this out. I was using the Custom Post Type UI plugin and had generated the following code (which I added to the functions file) for a custom taxonomy through the plugin: `register_taxonomy( 'video_type',array ( 0 => 'video',) ,array( 'hierarchical' => true, 'label' => 'Type','show_ui' => true,'query_var' => true,'rewrite' => array('slug' => ''),'singular_label' => 'video_type'` Somehow that code broke the theme. In Custom Post Type UI, you can either create custom posts types and taxonomies and keep the plugin active or use the beta function to copy and paste generated code to your function file. So I ended up deleting that code and keeping the plugin active.
Broken wordpress permalinks on pages only
wordpress
With the following code (in functions.php) my posts (of CPT event) are ordered by _end_date instead of _start_date. What's the proper solution to this as of WP 3.1.3? Of course I'd like to avoid using deprecated <code> meta_key </code> . <code> add_filter( 'pre_get_posts', 'my_get_posts' ); function my_get_posts( $query ) { if ( is_home() ) { $query-&gt;set( 'post_type', 'event' ); $query-&gt;set( 'meta_key', '_start_date' ); $query-&gt;set( 'orderby', 'meta_value_num' ); $query-&gt;set( 'order', 'ASC' ); $query-&gt;set( 'meta_query', array( array( 'key' =&gt; '_end_date', 'value' =&gt; time(), 'compare' =&gt; '&gt;=', 'type' =&gt; 'numeric' ) ) ); } return $query; } </code>
This seems to be a bug in Wordpress. Wordpress actually modifies the meta_query if you specify orderby and meta_key as query vars. Normally this modification adds the new meta_key as the first array in meta_query array and hence the orderby is applied to the first meta key specified in meta_query. But when you modify orderby, meta_key and meta_value query_vars in pre_get_posts filter, due to the (it seems to me) bug in Wordpress, it add the new array in existing meta query but the new array is not inserted as first array, it gets appended to the existing meta_query. And orderby always gets applied to the first meta_key in meta_query. So as a workaround until the bug gets fixed you can specify the meta_key again in the meta_query as the first array, as in the following example: <code> add_filter( 'pre_get_posts', 'my_get_posts' ); function my_get_posts( $query ) { if ( is_home() ) { $query-&gt;set( 'post_type', 'event' ); $query-&gt;set( 'meta_key', '_start_date' ); $query-&gt;set( 'orderby', 'meta_value_num' ); $query-&gt;set( 'order', 'ASC' ); $query-&gt;set( 'meta_query', array( array( 'key' =&gt; '_start_date' ), array( 'key' =&gt; '_end_date', 'value' =&gt; time(), 'compare' =&gt; '&gt;=', 'type' =&gt; 'numeric' ) )); } return $query; } </code>
Using meta_query, how can i filter by a custom field and order by another one?
wordpress
Does anyone know of a plugin that is capable of merging the post meta from one post into another? I'm working on re-releasing the Driftwood contact manager theme and I'm trying to find a way to solve the duplicate contact issue. Obviously this question could impact far more people than just myself. :)
<code> /** * Merge metadata from one post to another. * * @param int $from_ID Source post ID * @param int $to_ID Target post ID * @param bool $overwrite Whether to overwrite metadata if the key already exists * @return bool|array */ function wpse_20231_merge_postmeta( $from_ID, $to_ID, $overwrite = true ) { // get ALL metadata for $from_ID if ( !$source_meta = get_metadata( 'post', $from_ID ) ) return false; if ( !$existing_meta = get_metadata( 'post', $to_ID ) ) $existing_meta = array(); // loop over source meta and update, depending on if overwrite is true &amp; existing meta exists foreach ( $source_meta as $key =&gt; $value ) { if ( $overwrite ? true : !isset( $existing_meta[ $key ] ) ) update_post_meta( $to_ID, $key, maybe_unserialize( $value ) ); } // return new meta data // using plus is like array merge, but from left to right - proceding duplicate keys are ignored return $overwrite ? $source_meta + $existing_meta : $existing_meta + $source_meta; } </code>
Merge posts plugin?
wordpress
I am getting errors like <code> Warning: explode() expects parameter 2 to be string, array given in /data/www/ae/wp-includes/query.php on line 2390 Warning: in_array() expects parameter 2 to be array, null given in /data/www/ae/wp-includes/query.php on line 2399 Warning: in_array() expects parameter 2 to be array, null given in /data/www/ae/wp-includes/query.php on line 2399 Warning: in_array() expects parameter 2 to be array, null given in /data/www/ae/wp-includes/query.php on line 2399 Warning: in_array() expects parameter 2 to be array, null given in /data/www/ae/wp-includes/query.php on line 2399 Warning: in_array() expects parameter 2 to be array, null given in /data/www/ae/wp-includes/query.php on line 2399 Warning: in_array() expects parameter 2 to be array, null given in /data/www/ae/wp-includes/query.php on line 2399 Warning: in_array() expects parameter 2 to be array, null given in /data/www/ae/wp-includes/query.php on line 2399 Warning: in_array() expects parameter 2 to be array, null given in /data/www/ae/wp-includes/query.php on line 2399 </code> Whats wrong?
Installing the hotfix plugin may help to solve the problem. http://wordpress.org/extend/plugins/hotfix/ Currently I am using wordpress3.1.3 and got same type errors while browsing the media(media list page) in admin panel and hotfix plugin solves that.
Errors in Add Image Popup, Media Library Tab: "in_array() expects parameter 2 to be array, null given in wp-includes/query.php"
wordpress
I have a wp_query for a custom post type: events. I have a seven day calendar that is showing featured events on a page. Here is the wp_query and supporting code: https://gist.github.com/1030760 you can see the calendar at seattleite.com/calendar/ the thing works great with one exception. It should be showing a featured event on Sunday. If I change the order => 'asc' to order => 'desc' I see the event for sunday but then I lose the event for today. If I simply remove the order => item then I see what I see if I set order => 'desc' any idea how order is affecting my loop?
If anyone comes across this question. WordPress Codex says the following to <code> 'orderby' =&gt; 'meta_value' </code> and the <code> order </code> param: Note also that the sorting will be alphabetical which is fine for strings (i.e. words), but can be unexpected for numbers (e.g. 1, 3, 34, 4, 56, 6, etc, rather than 1, 3, 4, 6, 34, 56 as you might naturally expect). You are querying event dates, so the order of the results might be wrong because of this alphabetical sorting.
How does order=asc effect a wp_query (its acting pretty weird in a loop)
wordpress
The WordPress Transients API makes it easy to save expensive values and look them up later. If you install an object backend (such as APC object cache, memcache or W3 Total Cache) you can cache these values between requests, gaining even more. But I've noticed that when the name of a transient field is too long, it simply doesn't bother caching it. Aside from being somewhere in the region of 50 characters, I don't know what the maximum length of these names is. Is this documented somewhere? Does it depend on what backend you're using?
A transient that doesn't expire has a max name length of 53 characters yet a transient that does expire has a max name length of 45 characters. http://core.trac.wordpress.org/ticket/15058
Transient / object cache maximum key length
wordpress
Is there a dedicated WP function, action or filter to use when adding/modifying the HTTP headers? For now I just hook a PHP header() call into the WP 'init' hook like this: <code> add_action('init', 'add_header_xua'); function add_header_xua(){ if(!is_admin()){ header('X-UA-Compatible: IE=edge,chrome=1'); } } </code> But is this the correct way to do that?
The init action is the wrong place to do it. A better place would be at template_redirect, so that you only affect the front end view of the site and not the admin areas.
WP function/filter for modifying http headers?
wordpress
I'm a little stuck here. I have a menu in Wordpress with some posts in it. What I would like is to retrieve all the posts as objects. I think I'm pretty close, but the SQL query doesn't seem to work as I want. This is wat I have so far: <code> $querystr = " SELECT wposts.* FROM wp_posts wposts LEFT JOIN wp_postmeta wmeta ON wposts.ID = wmeta.post_id LEFT JOIN wp_term_relationships wrel ON wrel.object_id = wmeta.meta_value LEFT JOIN wp_terms wterms ON wrel.term_taxonomy_id = wterms.term_id WHERE wterms.term_id= $menu_id "; $posts = $wpdb-&gt;get_results($querystr, OBJECT); </code> I'm pretty sure it's a stupid little SQL logic error, but I realy can't find it..
I recently needed the same thing, I had menu of categories and I needed to get the categories that in the menu. After a several hours digging in the WP core, I found the wp_get_nav_menu_items() function that helped me. I finnally came with this, 220 was my menu_id <code> $navcat = wp_get_nav_menu_items('220'); foreach ($navcat as $obj) { $catid = $obj-&gt;object_id; $category = get_category($catid); ... ... } </code> So, if you have a nav menu of posts, I assume you can do the same, something like this should work - <code> $nav_items = wp_get_nav_menu_items('220'); foreach ($nav_items as $obj) { $objid = $obj-&gt;object_id; $postobj = get_post($objid); //do stuff with the post.. } </code> I think it can save you some complexed mySQL query...
Get posts by menu ID
wordpress
I'm trying to figure out how to create a translation for a post using the internal WPML API ( <code> inc/wpml-api.php </code> ) I simply want to create a translation for post ID xx, set some content and publish it. I've tried to play around with <code> wpml_add_translatable_content </code> but couldn't get it right. Unfortunately there is not much documentation available for this. The closest lead I found is this thread, but I couldn't reduce the code to what I need. It's also possible to do this by directly writing to the database, following WPML's table structure, but I want to use the API. Any suggestions are welcome.
I came up with a function that does the job for now : <code> /** * Creates a translation of a post (to be used with WPML) * * @param int $post_id The ID of the post to be translated. * @param string $post_type The post type of the post to be transaled (ie. 'post', 'page', 'custom type', etc.). * @param string $lang The language of the translated post (ie 'fr', 'de', etc.). * * @return the translated post ID * */ function mwm_wpml_translate_post( $post_id, $post_type, $lang ){ // Include WPML API include_once( WP_PLUGIN_DIR . '/sitepress-multilingual-cms/inc/wpml-api.php' ); // Define title of translated post $post_translated_title = get_post( $post_id )-&gt;post_title . ' (' . $lang . ')'; // Insert translated post $post_translated_id = wp_insert_post( array( 'post_title' =&gt; $post_translated_title, 'post_type' =&gt; $post_type ) ); // Get trid of original post $trid = wpml_get_content_trid( 'post_' . $post_type, $post_id ); // Get default language $default_lang = wpml_get_default_language(); // Associate original post and translated post global $wpdb; $wpdb-&gt;update( $wpdb-&gt;prefix.'icl_translations', array( 'trid' =&gt; $trid, 'language_code' =&gt; $lang, 'source_language_code' =&gt; $default_lang ), array( 'element_id' =&gt; $post_translated_id ) ); // Return translated post ID return $post_translated_id; } </code>
[Plugin WPML] : How to create a translation of a post using the WPML API?
wordpress
I just updated to 3.1.3 and now when I go to the admin I get the "Database Update Required" <code> /wp-admin/upgrade.php </code> screen. I click 'Upgrade Now' and it says it's done, but then trying to access anything in the admin gets me the same screen again. How do I get past this? EDIT: In trying to use toscho's solution, I discovered that my wordpress db tables are not writable, which likely led to the error loop. Any ideas for how to track that down?
Discovered that the db files I copied over from another machine had incorrect ownership. Once I <code> chown -R mysql:mysql myblogdbdirectory </code> and restarted MySQL, the database upgrade worked.
Site stuck in "Database Update Required" loop
wordpress
Im trying to use the_excerpt form inside a plugins template file, plugin is wp-favorite-posts by default the plugin only lists and displays the saved post title, i have manged to get it to show everything, tax terms, image etc but having a heck of a time with the_excerpt, what happens when i add <code> &lt;?php the_excerpt( $post_id ); ?&gt; </code> into the code is a continual looping of the favorite post and no excerpt. Im using <code> global $post </code> so that i can get all the info (cept the excerpt) <code> &lt;?php global $post; if (!empty($user)): if (!wpfp_is_user_favlist_public($user)): echo "$user's Favorite Posts."; else: echo "$user's list is not public."; endif; endif; if ($wpfp_before): echo "&lt;p&gt;".$wpfp_before."&lt;/p&gt;"; endif; if ($favorite_post_ids): foreach ($favorite_post_ids as $post_id) { $p = get_post($post_id); ?&gt; &lt;div class="homepage_props"&gt; &lt;div class="homepage_props_inner"&gt; &lt;div class="homepage_propsbanner"&gt; &lt;div class="homepage_new"&gt; &lt;?php if (strtotime($post-&gt;post_date) &gt; strtotime('-7 days')) { ?&gt; &lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/images/new.png" alt="latest property listings" /&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;h2&gt; &lt;span style="float:left; font-weight:bold;"&gt; &lt;?php if ( 'sales' == get_post_type($post_id) ) { echo 'Property For Sale'; } elseif ( 'rentals' == get_post_type($post_id) ) { echo 'Property For Rent'; } elseif ( 'business' == get_post_type($post_id) ) { echo 'Business For Sale&lt;/span&gt;'; } elseif ( 'bandb' == get_post_type() ) { echo 'Bed And Breakfast&lt;/span&gt;'; } ?&gt; &lt;/span&gt; &lt;span style="float:right; font-weight:normal;"&gt; &lt;a href="&lt;?php echo get_permalink($post_id); ?&gt;" title="&lt;?php printf( esc_attr__( 'Permalink to %s', 'themename' ), the_title_attribute( 'echo=0' ) ); ?&gt;" rel="bookmark"&gt;&lt;?php echo get_the_title ( $post_id ); ?&gt;&lt;/a&gt; &lt;/span&gt; &lt;/h2&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;div class="homepage_props_image"&gt; &lt;?php echo "&lt;a href='".get_permalink($post_id)."'&gt;"; echo get_the_post_thumbnail ( $post_id, 'medium' ); echo "&lt;/a&gt;"; ?&gt; &lt;/div&gt;&lt;!-- / homepage_props_image --&gt; &lt;div class="homepage_props_info hyphenate"&gt; &lt;!-- heres where im trying to put the_excerpt --&gt; &lt;/div&gt;&lt;!-- / homepage_props_info --&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;div class="homepage_props_tax"&gt; &lt;?php if ( 'sales' == get_post_type($post_id) ) { echo '&lt;h3&gt;&lt;span style="float:right; font-weight:normal;"&gt;' . get_the_term_list( $post_id, 'property_type', 'Property Type: ', ' ', '' ),'&amp;nbsp;&amp;nbsp;&amp;nbsp;' . get_the_term_list( $post_id, 'location', 'Location: ', ' ', '' ),'&amp;nbsp;&amp;nbsp;&amp;nbsp;'.get_the_term_list( $post_id, 'region', 'Region: ', ' ', '' ); } elseif ( 'rentals' == get_post_type($post_id) ) { echo '&lt;h3&gt;&lt;span style="float:right; font-weight:normal;"&gt;' . get_the_term_list( $post_id, 'property_type', 'Property Type: ', ' ', '' ),'&amp;nbsp;&amp;nbsp;&amp;nbsp;' . get_the_term_list( $post_id, 'location', 'Location: ', ' ', '' ),'&amp;nbsp;&amp;nbsp;&amp;nbsp;' . get_the_term_list( $post_id, 'region', 'Region: ', ' ', '' ); } elseif ( 'business' == get_post_type($post_id) ) { echo '&lt;h3&gt;&lt;span style="float:right; font-weight:normal;"&gt;' . get_the_term_list( $post_id, 'property_type', 'Property Type: ', ' ', '' ),'&amp;nbsp;&amp;nbsp;&amp;nbsp;' . get_the_term_list( $post_id, 'location', 'Location: ', ' ', '' ),'&amp;nbsp;&amp;nbsp;&amp;nbsp;' . get_the_term_list( $post_id, 'region', 'Region: ', ' ', '' ); } ?&gt; &lt;/span&gt;&lt;/h3&gt; &lt;/div&gt;&lt;!-- / homepage_props_tax --&gt; &lt;/div&gt;&lt;!-- / homepage_props_inner --&gt; &lt;/div&gt;&lt;!-- / homepage_props --&gt; &lt;?php } else: echo $wpfp_options['favorites_empty']; endif; ?&gt; &lt;span style="float:left; font-size:0.7em;"&gt;&lt;?php wpfp_clear_list_link(); ?&gt;&lt;/span&gt; &lt;?php wpfp_cookie_warning(); ?&gt; </code> First picture is using the_excerpt Second picture is without the_excerpt
You are doing few things wrong: the_excerpt does not uses post id. When you modify global $post you should always set it back to its original value. you were assigning get_post's return value to $p which was not used in your code. I have made few fixes in your code. The below code is just the copy paste of your code with my fixes so try the code below and let me know if you still have issues. Sorry I had to change bit of your code formatting. <code> &lt;?php if (!empty($user)): if (!wpfp_is_user_favlist_public($user)): echo "$user's Favorite Posts."; else: echo "$user's list is not public."; endif; endif; if ($wpfp_before): echo "&lt;p&gt;".$wpfp_before."&lt;/p&gt;"; endif; if ($favorite_post_ids): foreach ($favorite_post_ids as $post_id) { $p = get_post($post_id); ?&gt; &lt;div class="homepage_props"&gt; &lt;div class="homepage_props_inner"&gt; &lt;div class="homepage_propsbanner"&gt; &lt;div class="homepage_new"&gt; &lt;?php if (strtotime($p-&gt;post_date) &gt; strtotime('-7 days')) { ?&gt; &lt;img src="&lt;?php echo get_template_directory_uri(); ?&gt;/images/new.png" alt="latest property listings" /&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;h2&gt;&lt;span style="float:left; font-weight:bold;"&gt; &lt;?php if ( 'sales' == $p-&gt;post_type ) { echo 'Property For Sale'; } elseif ( 'rentals' == $p-&gt;post_type ) { echo 'Property For Rent'; } elseif ( 'business' == $p-&gt;post_type ) { echo 'Business For Sale'; } elseif ( 'bandb' == $p-&gt;post_type ) { echo 'Bed And Breakfast'; } ?&gt; &lt;/span&gt; &lt;span style="float:right; font-weight:normal;"&gt; &lt;a href="&lt;?php echo get_permalink($post_id); ?&gt;" title="&lt;?php printf( esc_attr__( 'Permalink to %s', 'themename' ), get_the_title( $post_id ) ); ?&gt;" rel="bookmark"&gt;&lt;?php echo get_the_title ( $post_id ); ?&gt;&lt;/a&gt; &lt;/span&gt; &lt;/h2&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;div class="homepage_props_image"&gt; &lt;?php echo "&lt;a href='".get_permalink($post_id)."'&gt;"; echo get_the_post_thumbnail ( $post_id, 'medium' ); echo "&lt;/a&gt;"; ?&gt; &lt;/div&gt;&lt;!-- / homepage_props_image --&gt; &lt;div class="homepage_props_info hyphenate"&gt; &lt;?php echo $p-&gt;post_excerpt; ?&gt; &lt;/div&gt;&lt;!-- / homepage_props_info --&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;div class="homepage_props_tax"&gt; &lt;?php if ( in_array( $p-&gt;post_type, array( 'sales', 'rentals', 'business' ) ) ) { echo '&lt;h3&gt;&lt;span style="float:right; font-weight:normal;"&gt;' .get_the_term_list( $post_id, 'property_type', 'Property Type: ', ' ', '' ),'&amp;nbsp;&amp;nbsp;&amp;nbsp;' .get_the_term_list( $post_id, 'location', 'Location: ', ' ', '' ),'&amp;nbsp;&amp;nbsp;&amp;nbsp;'.get_the_term_list( $post_id, 'region', 'Region: ', ' ', '' ); echo '&lt;/span&gt;&lt;/h3&gt;'; } ?&gt; &lt;/div&gt;&lt;!-- / homepage_props_tax --&gt; &lt;/div&gt;&lt;!-- / homepage_props_inner --&gt; &lt;/div&gt;&lt;!-- / homepage_props --&gt; &lt;?php } else: echo $wpfp_options['favorites_empty']; endif; ?&gt; </code>
Calling the_excerpt from inside a plugin template file
wordpress
I'm using More Fields to create some meta boxes on my custom post type. Is it possible to have a caption for each "group" of fields in the More Fields options? I would like to provide some basic information on the post edit screen. I see you can enter a caption for each individual field but it would be handy to be able to give the group a caption also.
At this point in time I would just as soon not use the More Fields plugin at all, as there are native functions that can do everything you probably want with custom fields. There seems to be no good documentation afoot and the plugin site is obviously not being updated. Alternatively, try WPAlchemy . Quite easy to make discrete meta boxes with multiple form elements and whatever else you want to put into them, including blocks of text.
Captions for More Fields groups, not just individual fields
wordpress
I have a error handling mechanism setup in one of my plugins to add notices and errors to the admin area, just like the core does. It works fine in most cases, but there are some situations (like saving a custom post type) where it doesn't. I'm guessing that a redirect is happening behind the scenes, and the messages are being printed before the redirect happens, so that they appear to never show up. So, I'm guessing this is what's happening User edits a custom post type and hits Publish My post_updated callback is called, which validates and saves the custom fields The callback adds an error message Wordpress does a redirect to a some page to do some processing My admin_notices callback is called, which prints and clears the messages Wordpress redirects back to the post My admin_notices callback is called again, but there are no messages to print because they were printed in step #5 Under normal circumstances steps 4 and 5 don't happen, so everything works fine, but I think when Wordpress saves posts it introduces the extra redirect. Is something I can do to make sure this always works? I was thinking I might be able to check something inside printMessages() and return immediately if it's at step 4, but I'm not sure what. These two questions may shed some light on the problem, but don't fully give a solution: stackexchange-url ("Add validation and error handling when saving custom fields?"), stackexchange-url ("How to display admin error notice if settings saved succesfully?"). Here's the code: <code> /** * Constructor * @author Ian Dunn &lt;[email protected]&gt; */ public function __construct() { // Initialize variables $defaultOptions = array( 'updates' =&gt; array(), 'errors' =&gt; array() ); $this-&gt;options = array_merge( get_option( self::PREFIX . 'options', array() ), $defaultOptions ); $this-&gt;updatedOptions = false; $this-&gt;userMessageCount = array( 'updates' =&gt; 0, 'errors' =&gt; 0 ); // more add_action( 'admin_notices', array($this, 'printMessages') ); add_action( 'post_updated', array($this, 'saveCustomFields') ); // does other stuff } /** * Saves values of the the custom post type's extra fields * @author Ian Dunn &lt;[email protected]&gt; */ public function saveCustomFields() { // does stuff if( true ) // if there was an error $this-&gt;enqueueMessage( 'foo', 'error' ); } /** * Displays updates and errors * @author Ian Dunn &lt;[email protected]&gt; */ public function printMessages() { foreach( array('updates', 'errors') as $type ) { if( $this-&gt;options[$type] &amp;&amp; ( self::DEBUG_MODE || $this-&gt;userMessageCount[$type] ) ) { echo '&lt;div id="message" class="'. ( $type == 'updates' ? 'updated' : 'error' ) .'"&gt;'; foreach($this-&gt;options[$type] as $message) if( $message['mode'] == 'user' || self::DEBUG_MODE ) echo '&lt;p&gt;'. $message['message'] .'&lt;/p&gt;'; echo '&lt;/div&gt;'; $this-&gt;options[$type] = array(); $this-&gt;updatedOptions = true; $this-&gt;userMessageCount[$type] = 0; } } } /** * Queues up a message to be displayed to the user * @author Ian Dunn &lt;[email protected]&gt; * @param string $message The text to show the user * @param string $type 'update' for a success or notification message, or 'error' for an error message * @param string $mode 'user' if it's intended for the user, or 'debug' if it's intended for the developer */ protected function enqueueMessage($message, $type = 'update', $mode = 'user') { array_push($this-&gt;options[$type .'s'], array( 'message' =&gt; $message, 'type' =&gt; $type, 'mode' =&gt; $mode ) ); if($mode == 'user') $this-&gt;userMessageCount[$type . 's']++; $this-&gt;updatedOptions = true; } /** * Destructor * Writes options to the database * @author Ian Dunn &lt;[email protected]&gt; */ public function __destruct() { if($this-&gt;updatedOptions) update_option(self::PREFIX . 'options', $this-&gt;options); } </code> Update: The updated code with the accepted answer has been committed to core.php in the plugin's trunk in case anyone wants to see a full working copy. The next stable release that will have it is 1.2. Update 2: I've abstracted this functionality into a self-contained library that you can include in your plugin. Core is discussing including similar functionality in #11515 .
There are few things that I have pointed out in the code below too: You were overwriting the options read from <code> get_option </code> using <code> array_merge </code> You had hard-coded the Message Counts. saving options in <code> __destruct </code> just does not work. (I don't have any clue yet, may be experts will shed some light on it. I have marked all the sections where I have made the changes with HKFIX , with a bit of description: <code> /** * Constructor * @author Ian Dunn &lt;[email protected]&gt; */ public function __construct() { // Initialize variables $defaultOptions = array( 'updates' =&gt; array(), 'errors' =&gt; array() ); /* HKFIX: array_merge was overwriting the values read from get_option, * moved $defaultOptions as first argument to array_merge */ $this-&gt;options = array_merge( $defaultOptions, get_option( self::PREFIX . 'options', array() ) ); $this-&gt;updatedOptions = false; /* HKFIX: the count for update and error messages was hardcoded, * which was ignoring the messages already in the options table read above * later in print the MessageCounts is used in loop * So I updated to set the count based on the options read from get_option */ $this-&gt;userMessageCount = array(); foreach ( $this-&gt;options as $msg_type =&gt; $msgs ) { $this-&gt;userMessageCount[$msg_type] = count( $msgs ); } // more add_action( 'admin_notices', array($this, 'printMessages') ); add_action( 'post_updated', array($this, 'saveCustomFields') ); // does other stuff } /** * Saves values of the the custom post type's extra fields * @author Ian Dunn &lt;[email protected]&gt; */ public function saveCustomFields() { // does stuff /* HKFIX: this was false, so changed it to true, may be not a fix but thought I should mention ;) */ if( true ) $this-&gt;enqueueMessage( 'foo', 'error' ); } /** * Displays updates and errors * @author Ian Dunn &lt;[email protected]&gt; */ public function printMessages() { foreach( array('updates', 'errors') as $type ) { if( $this-&gt;options[$type] &amp;&amp; ( self::DEBUG_MODE || $this-&gt;userMessageCount[$type] ) ) { echo '&lt;div id="message" class="'. ( $type == 'updates' ? 'updated' : 'error' ) .'"&gt;'; foreach($this-&gt;options[$type] as $message) if( $message['mode'] == 'user' || self::DEBUG_MODE ) echo '&lt;p&gt;'. $message['message'] .'&lt;/p&gt;'; echo '&lt;/div&gt;'; $this-&gt;options[$type] = array(); $this-&gt;updatedOptions = true; $this-&gt;userMessageCount[$type] = 0; } } /* HKFIX: Save the messages, can't wait for destruct */ if ( $this-&gt;updatedOptions ) { $this-&gt;saveMessages(); } } /** * Queues up a message to be displayed to the user * @author Ian Dunn &lt;[email protected]&gt; * @param string $message The text to show the user * @param string $type 'update' for a success or notification message, or 'error' for an error message * @param string $mode 'user' if it's intended for the user, or 'debug' if it's intended for the developer */ protected function enqueueMessage($message, $type = 'update', $mode = 'user') { array_push($this-&gt;options[$type .'s'], array( 'message' =&gt; $message, 'type' =&gt; $type, 'mode' =&gt; $mode ) ); if($mode == 'user') $this-&gt;userMessageCount[$type . 's']++; /* HKFIX: save the messages, can't wait for destruct */ $this-&gt;saveMessages(); } /* HKFIX: Dedicated funciton to save messages * Can also be called from destruct if that is really required */ public function saveMessages() { update_option(self::PREFIX . 'options', $this-&gt;options); } /** * Destructor * Writes options to the database * @author Ian Dunn &lt;[email protected]&gt; */ public function __destruct() { /* HKFIX: Can't rely on saving options in destruct, this just does not work */ // its very late to call update_options in destruct //update_option(self::PREFIX . 'options', $this-&gt;options); } </code>
Custom admin_notices Messages Ignored During Redirects
wordpress
Suppose I have content like <code> [xxx] Here is some content in xxx [/xxx] Here is content outside xxx ... </code> Can I somehow just get content inside <code> [xxx] </code> ONLY content outside <code> [xxx] </code> ONLY
Depends on the shortcode. If you have access to the shortcode's handler function, that function's second argument is the content inside the shortcode: <code> function wpse20136_shortcode( $atts, $content ){ // $content has the content inside xxx } register_shortcode( 'xxx', 'wpse20136_shortcode' ); </code> For getting all content not in shortcodes, that's easy. <code> strip_shortcodes() </code> does that: <code> strip_shortcodes( get_the_content() ); </code> for example, will give you the content of the current post with only the content not inside shortcodes.
How can I just get content inside a shortcode or just outside
wordpress
I'd like to run some code only if a gallery (inserted with the <code> [gallery] </code> shortcode) has been inserted into a post/page. I did the following: <code> gallery_shortcode($post-&gt;ID) ? $gallery = 1 : $gallery = 0; </code> However, this always sets <code> $gallery = 0 </code> whether there's a gallery or not. Am I using this incorrectly?
try : <code> if (strpos($post-&gt;post_content,'[gallery') === false){ $gallery = 0; }else{ $gallery = 1; } </code>
Check if post/page has gallery?
wordpress
I have previously asked about How to automatically send email to Admin when a user/member changes his/hers profile data. And got some very good answers. stackexchange-url ("Send automatic mail to Admin when user/member changes/adds profile.") Now a follow up: I only want to send/email the data (profiledata) that was updated/added.
So, as Bainternet notes, you would need to compare the new field value to what it was right before the edit. In essence, you will need to build in version control for the profile fields. You will need to add a database table to store this info, using the the <code> $wpdb </code> object to write, and read from it. Basically, on <code> personal_options_update </code> and <code> edit_user_profile_update </code> you will glean the data as in the previous answer, but then also compare it to your table storing the what existed in the previous save. You'll only send a particular field's data if there is mismatch.
Send email to Admin when user/member updates specific user/member data
wordpress
EDIT: This used to be How do I force a page to be <code> is_archive == true </code> ? I was trying to solve the wrong problem. Instead of forcing the post/page to have a particular attribute, I should have looked at the classes applied to the menu item. The 'Blog' menu-item has the <code> current-page-ancestor </code> class applied to it. I can style the menu based on this. ORIGINAL QUESTION: I have my own theme where I created an <code> archives.php </code> template in order to have a page that tries to list the different ways to view archives and to give a place for users to browse the archives if they want to. I created a page using the WP admin page and I made it's parent the 'Blog' page. The 'Blog' page is the page where all my posts get emitted. I have a menu at the top and right now, every sub-page under the 'Blog' page causes the menu to highlight 'Blog' (this is the correct behavior). Specifically, the menu item has the style <code> current_page_* </code> applied to it. This doesn't happen when you load <code> blog/archives </code> (the template/page I created in the first paragraph). So when I click on the date of a blog post, it brings me to an archived post page it looks like this (note that the Blog menu item is highlighted): When I go to my archives, it looks like this (note that the menu item is NOT highlighted): I looked at <code> $wp_query </code> to see what the difference was. I saw that <code> is_archive </code> or <code> is_home </code> was true in the cases where the menu-item was correctly styled. How do I force my page to be <code> is_archive == true </code> ? I tried to insert a <code> $wp_query-&gt;set('is_archive', 1); </code> before the call to <code> get_header(); </code> in my template but that didn't work. I also looked in the WP admin dashboard to see if there was something I could click to force the page to be considered an archive. Edit: To be clear, I'm looking for a WP solution. I know that I can hard-code the CSS to get the menu item to appear the way I want it to be, but that doesn't seem to be the right thing to do.
As per the change in the question, the answer to this is: Look at the css classes that are applied to the menu-item of interest. The menu-item which this page should be a child of should have <code> current-page-ancestor </code> applied to it. Make the appropriate changes in your styling sheet to style the menu when this class appears.
How do I highlight the menu for a child page?
wordpress
I'm looking for a specific type of gallery plugin implementation. First of all, it needs to be able to pull from Picasa. Second, I would like it to basically be a static lightbox...and what I mean by this is: Single image displayed with previous/next buttons Able to display the image title/description Able to display <code> Image &lt;x&gt; of &lt;y&gt; </code> Preferably make use of jQuery At this point, I'd prefer to hide all gallery thumbnails and give the focus on the main image. If thumbnails could be easily hidden and shown with a config option, that would be OK.
Picasa plugin i think it'll help you,or help to start a new plugin with some ideas..
jQuery gallery plugin to interface with Picasa
wordpress
I wanted to insert a form with a line of PHP code via shortcode. I am wondering if it's allowed? Has anyone tried it? Take the following for example: <code> function get_form($atts) { return '&lt;form method="post" action=""&gt; &lt;input type="input" name="myinput" value=""&gt;&lt;/input&gt; &lt;input type="hidden" name="myvar" value="&lt;?php echo $current_user-&gt;ID; ?&gt;"&gt; &lt;/form&gt;'; } add_shortcode('myshortcode', 'get_form'); </code> I hope it's clear now...
<code> $current_user </code> isn't declared in the scope of that function. You'd want to modify the code to be more like this: <code> function get_form($atts) { $current_user = wp_get_current_user(); return '&lt;form method="post" action=""&gt; &lt;input type="input" name="myinput" value=""&gt;&lt;/input&gt; &lt;input type="hidden" name="myvar" value="' . $current_user-&gt;ID . '"&gt; &lt;/form&gt;'; } add_shortcode('myshortcode', 'get_form'); </code>
Insert PHP code via shortcode?
wordpress
I was wondering if it would be possible to embed an html page or add an iframe into a dashboard widget. I have a multi author blog and i want to make my admin section a simple as possible for some of my author's are less "technical". So I already added a simple widget containing some text. And I took out the less interesting widgets. And I added some links so they can stay on their dashboard page but be able to do everything they had to do. But I thought it would also be interesting to embed some sort of comment box so they could like talk to each other and discuss things. something like this http://www.htmlcommentbox.com I gives you some html code wich you can paste into your webpage. So I started to experiment but all the things I tried came out negative. I thought that if I would be able to simply embed it into a widget or embed it on a html page and view it trough an Iframe it could work. But like I said can't seem to pull it off. Is it possible? or am I just wasting my time? thanks in advance
Sure, you can do this. It sounds like it would make more sense to add a protected forum to your installation though... but here's how you would do it: <code> // Create the function to output the contents of our Dashboard Widget function iframe_dashboard_widget_function() { // Display whatever it is you want to show echo '&lt;iframe src="http://www.htmlcommentbox.com" width="100%" height="300" frameBorder="0"&gt;Browser not compatible.&lt;/iframe&gt;'; } // Create the function use in the action hook function example_add_dashboard_widgets() { wp_add_dashboard_widget('iframe_dashboard_widget', 'Iframe Dashboard Widget', 'iframe_dashboard_widget_function'); } // Hook into the 'wp_dashboard_setup' action to register our other functions add_action('wp_dashboard_setup', 'example_add_dashboard_widgets' ); </code>
Embed iframe or html page into dashboard widget
wordpress
I am encountering the same problem described here: Unable to set path . In every module where I can edit a page, a <code> p </code> appears after the word 'Path'. I can click on it; clicking on it highlights some of the text. How do I fix this issue?
The path in the editor is just for reference, most of the time users do not even bother looking at it and those that do use if to see what html tag there are in. Example: <code> &lt;p&gt; This is just a sample paragraph &lt;/p&gt; &lt;span&gt; This is just a sample span &lt;/span&gt; &lt;blockquote&gt; This is just a simple blockquote &lt;/blockquote&gt; </code> If i was in the blockquote tags the path would be <code> PATH: blockquote </code> or in the span <code> PATH: span </code> . All in all the feature is use full to most and use less to some OR use full to beginners and use less to advance Just a side note it does not have anything to do with the path of your site that is the line below the title field
How do I fix my 'Path' field when editing pages via the Dashboard?
wordpress
I want to make a TV Show database in Wordpress that has this URL format: <code> /tvshows/friends/01/12/ </code> <code> /tvshows/ </code> would list all series <code> /tvshows/friends/ </code> would list all the seasons available for Friends TV Show <code> /tvshows/friends/01/ </code> would list all episodes of Friends from season 1 <code> /tvshows/friends/01/12/ </code> would show information on the 12th episode of the first season And here are the different methods I've thought about: 1) The first idea that came to my mind is to create Pages and nest them accordingly. Then create 3 different page templates (TVShow.php, Season.php and Episode.php) and style each page accordingly. The main drawback is that once there are 200 series with 4 seasons and 25 episodes each (total of 20,000 pages) it can be a complete mess to update and find everything. (Another drawback is the RSS feed although this can be solved through plugins) 2) Some colleagues suggest me to use Custom Posts but these do not have a hierarchical structure and although I could then use mod_rewrite to make the URLs nice I guess it would be even more hassle than using Pages. (There's this plugin that manages custom posts through a UI although I cannot figure out how to create a hierarchical organization) 3) The last idea is to have them as normal Posts and then Categorize them by Serie name, season and episode hence avoiding all the custom post hassle and using simple Wordpress API functions to list and display everything. Those are the best/possible ways I can think of, the Page-based option may be the most suitable although scalable in a painful way once there are +500 pages. Any ideas, suggestions on how to organize this? Thanks in advance! :)
First, you shouldn't do this with the built in post types of <code> post </code> or <code> page </code> . Use a custom post type. Example: <code> movies </code> and <code> series </code> , where <code> movies </code> is non-hierarchical, but <code> series </code> is. Use register_post_type() </code> and set <code> hierarchical </code> to <code> true </code> (default: <code> false </code> ). Take a look at the <code> rewrite </code> argument > <code> with_front </code> to prepend <code> /series/ </code> . Then add some templates: series-list.php, series-detail.php, series-season.php, series-episode.php...
TV Show database - Best way for structuring it?
wordpress
I'm trying to add a metabox to select a sidebar per page. In order to create the metaboxes I use this class The construction is fairly easy: <code> $meta_boxes[] = array( 'id' =&gt; 'sidebars_side', 'title' =&gt; 'Page Sidebar', 'pages' =&gt; array('page', 'post'), 'context' =&gt; 'side', 'priority' =&gt; 'low', 'fields' =&gt; array( array( 'name' =&gt; 'Sidebars', 'id' =&gt; 'tst_sidebars', 'type' =&gt; 'select', 'options' =&gt; array( ARRAY OF SIDEBARS GOES HERE ), 'multiple' =&gt; false, ) ) ); </code> But I can't for the love of God to construct the array properly. I checked stackexchange-url ("this post") which is great, but I'm stuck somehow. Any help would be highly appreciated.
The class you are using accepts value => name pair in the select options array so <code> foreach ( $GLOBALS['wp_registered_sidebars'] as $sidebar ) { $sidebar_options[$sidebar['id']] = $sidebar['name']; } </code> and then you can use <code> $sidebar_options </code> .
List all sidebars in metabox
wordpress
The WP source shows that <code> wp_filter_kses </code> and <code> wp_filter_post_kses </code> are passed data that's "expected to be escaped with slashes." On the other hand, <code> wp_kses_data </code> is passed data that's "expected to not be escaped" and <code> wp_kses_post </code> has code that looks like wp_kses_data. How safe is it to pass unknown (in terms of escaped with slashes) data to these functions? Can the first set be preferred over the second or is preferring the second set safer? Or is this a case where you absolutely need to know the condition of your data in terms of slashed? --update-- I'm now figuring that if you don't know whether the data is escaped you could use <code> wp_kses_data( stripslashes_deep( $data ) ); </code> and run the return though addslashes() if you need escaped in the end.
From the codex: wp_filter_kses should generally be preferred over wp_kses_data because wp_magic_quotes escapes $_GET, $_POST, $_COOKIE, $_SERVER, and $_REQUEST fairly early in the hook system, shortly after 'plugins_loaded' but earlier then 'init' or 'wp_loaded'. The first set is then preferred. More of a question of, "is stripping slashes more secure than not?" They both use the same allowed HTML. Well yeah it depends, in absolute cases, but I would assume that it is more secure to than not to. Basic useage of kses: <code> $filtered = wp_kses($unfiltered, $allowed_html, $allowed_protocols); </code> All of the wordpress kses functions then just do <code> $filtered = wp_kses($unfiltered, $allowedtags); </code> SO: <code> $filtered = wp_kses_data($unfiltered); $filtered = wp_filter_kses($unfiltered); // does the same, but will also slash escape the data </code> the <code> post </code> variations use a different set of tags; those allowed for use by non-admins.
Which KSES should be used and when?
wordpress
Is it possible to have WordPress email the site administrator whenever a PHP error message is displayed? Ideally the message would also be filtered out of the HTML output, so as to avoid information disclosure. I ask because, while <code> @ini_set('display_errors', 0); </code> is at the top of my <code> wp-config.php </code> and working nicely, I want to receive notifications about errors. I will happily write a custom plugin to do this, if someone who knows more about WP can point me in the direction of where I might hook in to get the job done. Final bit: Am I crazy for wanting something this out-of-the-ordinary?
Displaying PHP errors isn't really a WordPress thing, it is more of a PHP thing directly. No, I don't think you are crazy for wanting this, I had a similar need for a separate application and I wrote this blog post which should be helpful. Essentially, define your own error handler.
Can WordPress email the admin about PHP errors, while hiding them from the site?
wordpress
I have Press Release Section on my page where i would like to be able to add documents pdf, ms doc's etc. Every time when i add new document to a post I would like download button to appear so user will be able to download that document. Could anyone point me at right direction or maybe there is a plugin existing which does that. Many thanks,
No need to insert the download into the post as @kaiser says, you can automate: <code> $download = get_children( 'post_type=attachment&amp;post_mime_type=application/pdf&amp;post_parent='.$post-&gt;ID ); if ($download) { foreach ( $download as $attachment_id =&gt; $attachment ) { echo '&lt;a href="'.wp_get_attachment_url($attachment_id).'" target="_blank" class="download"&gt;Download PDF&lt;/a&gt;'; } } </code>
Downloadable Documents
wordpress
How would I go about not letting empty data into wordpress? <code> &lt;?php foreach($_POST['eirepanel_inline_ads_options_name'] as $post_eirepanel_inline_ads_options_name): if(empty($post_eirepanel_inline_ads_options_name)): echo 'empty'; else: update_option('eirepanel_inline_ads_options', $_POST); $eirepanel_inline_ads_options = get_option('eirepanel_inline_ads_options'); endif; endforeach; ?&gt; </code>
More importantly, you should not let *untrusted, unsanitized $_POST data* into WordPress. But I think the issue is that you're updating the option with the entire $_POST data, instead of the appropriate array key: <code> update_option('eirepanel_inline_ads_options', $_POST); </code> Should probably be something like: <code> update_option('eirepanel_inline_ads_options', $_POST['eirepanel_inline_ads_options_name']); </code> Are your Plugin options discrete (one DB entry per option), or an options array? EDIT Since you're using an options array, the correct approach would be: Define an array to hold the <code> $_POST </code> data ( <code> $input = array() </code> ) Define an array to get the current settings from the DB ( <code> $valid_input = array() </code> ) Sanitize the <code> $_POST </code> data Update the <code> $valid_data </code> array with the sanitized <code> $input </code> array Pass the updated <code> $valid_data </code> back to the DB e.g. <code> $input = ( isset( $_POST ) ? $_POST : false ); $valid_input = get_option( 'eirepanel_inline_ads_options' ); foreach ( $input as $key ) { // sanitize data here } $valid_input = array_merge( $valid_input, $input ); update_option( 'eirepanel_inline_ads_options', $valid_input ); </code> Just quick and dirty, but should give you an idea. Also: using the Settings API would be especially helpful here.
WordPress: update_option, don't update empty options?
wordpress
I have a contact form that I used lot's of times before on other non WP sites but it doesn't seem to work on my current WP site, it just redirects you to a page not found. I don't want to use any plugins to create it. Here's the code: <code> &lt;form class="form" method="POST" action="&lt;?php the_permalink(); ?&gt;"&gt; &lt;table border="0" style="float:left;"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt; &lt;p&gt;Company Name:&lt;/p&gt; &lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="companyname" id="companyname" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;p&gt;Your Name:&lt;/p&gt; &lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="name" id="name" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;p&gt;E-mail:&lt;/p&gt; &lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="email" id="email" /&gt;&lt;/td&gt; &lt;td colspan="2"&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt; &lt;p&gt;Telephone:&lt;/p&gt; &lt;/td&gt; &lt;td&gt;&amp;nbsp;&lt;/td&gt; &lt;td&gt;&lt;input type="text" name="tel" id="tel" /&gt;&lt;/td&gt; &lt;td colspan="2"&gt;&amp;nbsp;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;table border="0" style="float:left;" width="450"&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td valign="top"&gt;&lt;p style="margin-left:42px;margin-right:10px;margin-top:7px;"&gt;Enquiry:&lt;/p&gt;&lt;/td&gt; &lt;td&gt;&lt;textarea name="enquiry"&gt;&lt;/textarea&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td colspan="2"&gt;&lt;button class="blue medium awesome awesomeforward" type="submit" name="submit"&gt;Send message&lt;/button&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;? if(isset($_POST['submit'])) { $to = "[email protected]"; $subject = "Teamworks contact enquiry"; $companyname_field = $_POST['companyname']; $name_field = $_POST['name']; $email_field = $_POST['email']; $tel_field = $_POST['tel']; $enquiry_field = $_POST['enquiry']; $body = "Hello Teamworks,\n\n You have an enquiry from the website, please see the details below:\n\n Name: $name_field\n Company Name: $companyname_field\n E-Mail: $email_field\n Tel: $tel_field\n Message:\n $enquiry_field\n\n Please reply to the enquiry asap.\n\n Kind Regards \n The Teamworks Website"; mail($to, $subject, $body); echo "&lt;/br&gt;Thank you for getting in touch, we will contact you shortly."; } ?&gt; &lt;/form&gt; </code>
When dealing with forms you need to make sure that your form doesn't have a few specific filed names like: name,day,month,year and I'm sure that a few more, so make your form fields names more specific like: contact_name,contact_day,contact_month,contact_year. in your case change <code> name="name" </code> to anything else.
Contact form redirecting to page not found on send
wordpress
I have several custom taxonomies and within two of those ( Company Categories and Photographer Categories ) I have a term that is similar. The Company Category called Boudoir and the Photographer category called Boudoir Photographers. When I created the Boudoir Photographer term in the Photographer Categories it renamed the Boudoir term in the Company Categories to Boudoir Photography. Why did this happen? The number of posts for either taxonomy term doe snot change, only its name and the slug. Thanx in advance!
They are all in your <code> {wpdb-&gt;prefix}_terms </code> table and therefore need to be unique. Else you could only get them via ID.
Why does WP rename similar "term name"-slugs in separate taxonomies?
wordpress
I created a self-hosted WordPress blog (on Dreamhost) several years ago. I've never truly been happy with the name and URL/domain of the blog, and I've decided that I want to change it. Here's what I'd like to do: Register the new domain name. (Say www.newblog.com for example.) Redirect traffic from the old domain name (www.oldblog.com) to the new one (www.newblog.com). Begin using www.newblog.com as the new web address. I'll be staying at the same web host through all this. I know there are lots of smaller steps I need to take in here, so I'd appreciate it if someone could help me fill in the blanks. Thanks!
Every thing you need is covered in the codex Moving WordPress entry.
Changing Wordpress blog name and web address
wordpress
I'm using this code to list the image attachments of a post: <code> &lt;select name="chb_homes_for_sale_specifics_floor_plan" style="width:100%;"&gt; &lt;option value=""&gt;Select&lt;/option&gt; &lt;?php $args = array( 'numberposts' =&gt; -1, 'orderby' =&gt; 'menu_order', 'order' =&gt; 'ASC', 'post_type' =&gt; 'attachment', 'post_parent' =&gt; $post-&gt;ID, 'post_mime_type' =&gt; 'image' ); $image = get_posts($args); if($image) { foreach($image as $key =&gt; $data) : ?&gt; &lt;option value="&lt;?php echo $data-&gt;ID; ?&gt;"&gt;&lt;?php echo $data-&gt;post_title; ?&gt;&lt;/option&gt; &lt;?php endforeach; } ?&gt; &lt;/select&gt; </code> But what I'm showing currently is the attachment <code> post_title </code> but I want to show the file name instead. I could maybe use get attachment URL then parse the URL to get the file name but was wondering if there is a ready made way in WordPress to get the file name.
I would strongly advise against using <code> $post-&gt;guid </code> - WordPress now generates them in the form; http:/example.com/?attachment_id=ID Use the same method that many of the attachment-related functions use; <code> $filename = basename ( get_attached_file( $data-&gt;ID ) ); </code>
How to get attachment file name not attachment URL
wordpress
I created a meta box I notice that <code> save_post </code> seems to be triggered when I land on the page, thus giving me errors like <code> Undefined index: xxx in /data/www/ae/wp-content/themes/xx/functions.php on line 121 </code> <code> add_action('save_post', function($id) { if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return; } if (!isset($_POST) || !is_array($_POST)) { return; } update_post_meta($id, 'xxx', sprintf('%f', $_POST['xxx'])); ... }); </code>
See stackexchange-url ("Why does save_post action fire when creating a new post?") You're getting the error as you need to check for the existence of <code> $_POST['xxx'] </code> , rather than just checking if <code> $_POST </code> is set (it will always be set &amp; an empty array by default). <code> add_action('save_post', function($id) { if ( ( defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE ) || !isset( $_POST['xxx'] ) ) return; update_post_meta( $id, 'xxx', sprintf( '%f', $_POST['xxx'] ) ); // run further code }); </code>
Why is save_post triggered even when I havent saved the post
wordpress
I find myself creating pages just as a "placeholder" to a listing page. eg. I create a page "Blog" and "Portfolio". Both has the editor emtpy. And I just use it so that I can use <code> page-blog.php </code> and <code> page-portfolio.php </code> for the respective listing pages. It doesnt seem proper? Is there a better way?
I guess another way would be including <code> 'has_archive' =&gt; true, </code> into your register_post_type array and using archive-{posttype}.php to style your custom post type listings
Is it proper to create a page just to generate a listing page (eg. for a custom post type)
wordpress
Feedburner won't read your feed if it's over 512k. Our podcast (http://herdingcode.com) has been around for 3 years now, and returning all items puts us way over that limit. We've had new listeners request that we include them all, though, and I'm wondering if that's easily possible. I'm thinking I could hack around with feed-rss2.php and add some conditional logic that puts full details for the most recent 75 shows and truncated descriptions for all the older shows. Has someone already done this, or got some tips on how to set it up?
Dunno if you have images in your feed, but those could be sucking up a bit of space: stackexchange-url ("Reducing image size in RSS only") Here are the basics for setting WP to use a custom feed template: http://www.456bereastreet.com/archive/201103/controlling_and_customising_rss_feeds_in_wordpress/ Here are some tips in authoring the template itself: http://digwp.com/2009/09/easy-custom-feeds-in-wordpress/ As for your looping, try something like this for your "full" 75 most recent posts (inside your RSS structure of course): <code> &lt;?php query_posts('showposts=75'); $ids = array(); while (have_posts()) : the_post(); $ids[] = get_the_ID(); the_title(); the_content(); endwhile; ?&gt; </code> Once that’s done, get all the rest, with just truncated info: <code> &lt;?php query_posts(array('post__not_in' =&gt; $ids)); while (have_posts()) : the_post(); the_title(); the_excerpt(); endwhile; ?&gt; </code>
How can I minimize the content of my RSS feed to fit more items in Feedburner's 512k limit?
wordpress
I'm not sure if I have done this correctly. As I understand it: if I have a class foo and a static method bar I can register that as the callback by passing the array <code> array("foo","bar") </code> as the function name. If I have an instance of a class in $foo and want to call the method bar I pass the array <code> array($foo,'bar') </code> . If I need to register an action inside the class itself would it work with <code> array($this,'bar') </code> ?
If I need to register an action inside the class itself would it work with <code> array($this, 'bar') </code> ? Yes, it works. <code> $this </code> Docs is referring to the concrete instance needed for the callback . That's exactly like the <code> $foo </code> example you give. It's just that <code> $this </code> is bit more special, but it represents basically the same and it works flawlessly with callbacks in PHP. Additional: if I have a class foo and a static method bar I can register that as the callback by passing the array <code> array("foo","bar") </code> as the function name. Yes you can do so, for the static function, you can write it as a string instead of the array as well: <code> foo::bar </code> , see Callbacks Docs . Might be handy.
Registering Class methods as hook callbacks
wordpress
I'm trying to automatically create terms in a certain taxonomy when a certain custom post type is published. The newly created term must be the name of the post that was published. Example: I have a custom post type "country" and a custom taxonomy "country_taxo". When I publish a country say "Kenya" I want a the term "Kenya" to be automatically created under the "country_taxo" taxonomy. I have accomplished this using the "publish_(custom_post_type) action hook", but i can only get it to work statically. Example: <code> // This snippet adds the term "Kenya" to "country_taxo" taxonomy whenever // a country custom post type is published. add_action('publish_country', 'add_country_term'); function add_country_term() { wp_insert_term( 'Keyna', 'country_taxo'); } </code> Like I mentioned above I need this to dynamically add the post title as the term. I tried this, but it doesn't work: <code> add_action('publish_country', 'add_country_term'); function add_country_term($post_ID) { global $wpdb; $country_post_name = $post-&gt;post_name; wp_insert_term( $country_post_name, 'country_taxo'); } </code> Does anyone know how I would go about doing this? Any help is greatly appreciated.
You're almost there - the problem is you're trying to access the <code> $post </code> object when the function only receives the post ID . <code> add_action( 'publish_country', 'add_country_term' ); function add_country_term( $post_ID ) { $post = get_post( $post_ID ); // get post object wp_insert_term( $post-&gt;post_title, 'country_taxo' ); } </code>
Dynamically Create Terms in Taxonomy when Custom Post Type is Published. Almost There!
wordpress
Suppose I have a Custom Taxonomy "Fruits". I want to query for all the values available eg. Oranges, Apples, Mangos etc. How can I do that?
Use <code> get_terms($taxonomy, $args) </code> <code> $terms = get_terms('Fruits'); </code> Codex page
How can I query for all values of a custom taxonomies?
wordpress
I've been trying various ways of doing this. Basically, I've been trying to make it so that a plugin of mine populates the terms of a taxonomy only once during the plugin's activation. The term populating is done in a function via the wp_insert_terms function. Calling the function straight inside the register_activation_hook doesn't seem to work and neither does hooking to the init hook using the register_activation_hook. Anyone have any ideas? Here is a version of my code <code> //version 1 class vsetup { function __construct() { register_activation_hook(__FILE__,array($this,'activate')); $this-&gt;create_taxonomies(); } function activate() { wp_insert_term('Action','genre'); wp_insert_term('Adventure','genre'); } function create_taxonomies() { $genre_args = array( 'hierarchical' =&gt; true, 'labels' =&gt; array( 'name'=&gt; _x('Genres', 'taxonomy general name' ), 'singular_name' =&gt; _x('Genre', 'taxonomy singular name'), 'search_items' =&gt; __('Search Genres'), 'popular_items' =&gt; __('Popular Genres'), 'all_items' =&gt; __('All Genres'), 'edit_item' =&gt; __('Edit Genre'), 'edit_item' =&gt; __('Edit Genre'), 'update_item' =&gt; __('Update Genre'), 'add_new_item' =&gt; __('Add New Genre'), 'new_item_name' =&gt; __('New Genre Name'), 'separate_items_with_commas' =&gt; __('Seperate Genres with Commas'), 'add_or_remove_items' =&gt; __('Add or Remove Genres'), 'choose_from_most_used' =&gt; __('Choose from Most Used Genres') ), 'query_var' =&gt; true, 'rewrite' =&gt; array('slug' =&gt;'genre') ); register_taxonomy('genre', 'post',$genre_args); } } </code> When that didn't work, I tried doing this: <code> //version 2 class vsetup { function __construct() { register_activation_hook(__FILE__,array($this,'activate')); $this-&gt;create_taxonomies(); } function activate() { add_action('init', array($this,'populate_taxonomies')); } function create_taxonomies() { $genre_args = array( 'hierarchical' =&gt; true, 'labels' =&gt; array( 'name'=&gt; _x('Genres', 'taxonomy general name' ), 'singular_name' =&gt; _x('Genre', 'taxonomy singular name'), 'search_items' =&gt; __('Search Genres'), 'popular_items' =&gt; __('Popular Genres'), 'all_items' =&gt; __('All Genres'), 'edit_item' =&gt; __('Edit Genre'), 'edit_item' =&gt; __('Edit Genre'), 'update_item' =&gt; __('Update Genre'), 'add_new_item' =&gt; __('Add New Genre'), 'new_item_name' =&gt; __('New Genre Name'), 'separate_items_with_commas' =&gt; __('Seperate Genres with Commas'), 'add_or_remove_items' =&gt; __('Add or Remove Genres'), 'choose_from_most_used' =&gt; __('Choose from Most Used Genres') ), 'query_var' =&gt; true, 'rewrite' =&gt; array('slug' =&gt;'genre') ); register_taxonomy('genre', 'post',$genre_args); } function populate_taxonomies() { wp_insert_term('Action','genre'); wp_insert_term('Adventure','genre'); } } </code> Neither idea worked for me so far.
Here is the fixed version of your code. <code> class vsetup { function __construct() { register_activation_hook(__FILE__,array($this,'activate')); add_action( 'init', array( $this, 'create_taxonomies' ) ); } function activate() { $this-&gt;create_taxonomies(); wp_insert_term('Action','genre'); wp_insert_term('Adventure','genre'); } function create_taxonomies() { $genre_args = array( 'hierarchical' =&gt; true, 'labels' =&gt; array( 'name'=&gt; _x('Genres', 'taxonomy general name' ), 'singular_name' =&gt; _x('Genre', 'taxonomy singular name'), 'search_items' =&gt; __('Search Genres'), 'popular_items' =&gt; __('Popular Genres'), 'all_items' =&gt; __('All Genres'), 'edit_item' =&gt; __('Edit Genre'), 'edit_item' =&gt; __('Edit Genre'), 'update_item' =&gt; __('Update Genre'), 'add_new_item' =&gt; __('Add New Genre'), 'new_item_name' =&gt; __('New Genre Name'), 'separate_items_with_commas' =&gt; __('Seperate Genres with Commas'), 'add_or_remove_items' =&gt; __('Add or Remove Genres'), 'choose_from_most_used' =&gt; __('Choose from Most Used Genres') ), 'query_var' =&gt; true, 'rewrite' =&gt; array('slug' =&gt;'genre') ); register_taxonomy('genre', 'post',$genre_args); } } </code> And don't forget to create the object/instance of the vsetup class i.e <code> new vsetup() </code> Huh! Forgot to remove the debug statement.
Inserting Taxonomy Terms During a Plugin Activation?
wordpress
So, i got this code to retrieve the images inserted in a gallery within a post: <code> &lt;?php $args = array( 'post_type' =&gt; 'attachment', 'numberposts' =&gt; -1, 'post_status'=&gt;'inherit', 'post_mime_type' =&gt; 'image', 'post_parent' =&gt; $post-&gt;ID, 'orderby' =&gt; 'menu_order', 'order' =&gt; 'ASC' ); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $attachment) { $image_attributes = wp_get_attachment_image_src( $attachment-&gt;ID, 'full' ); ?&gt;&lt;img title="&lt;?php echo $attachment-&gt;post_title; ?&gt;" src="&lt;?php echo $image_attributes[0] ?&gt;" /&gt;&lt;?php } } ?&gt; </code> and the output if fine, except that some pictures are duplicated and given a <code> class="cloned" </code> attribute. This code is running within a basic loop: <code> &lt;?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?&gt; </code> with no extra special things before and after. This is happening locally and online as i wanted to be sure about this weird thing; here's the demo . If you inspect the code you'll see this: <code> &lt;img class="cloned" src="http://k-win.fr/wptest/wp-content/uploads/2011/06/03mopi.jpg" title="03mopi"&gt; &lt;img src="http://k-win.fr/wptest/wp-content/uploads/2011/06/01.jpg" title="01"&gt; &lt;img src="http://k-win.fr/wptest/wp-content/uploads/2011/06/02.jpg" title="02"&gt; &lt;img src="http://k-win.fr/wptest/wp-content/uploads/2011/06/03mopi.jpg" title="03mopi"&gt; &lt;img class="cloned" src="http://k-win.fr/wptest/wp-content/uploads/2011/06/01.jpg" title="01"&gt; </code> But if you check the source code you wont see the <code> class="cloned" </code> i'm speaking of (devil inside!). It's driving me a bit crazy cos it's messing up with the pictures order in some cases and this one has to be respected from the order decided in the gallery's options. I checked with Opera, Chrome and Firefox, and all show me the same thing. Any clue?
that's your nivo-slider at work
Getting attachment images is cloning some of them
wordpress
All I understand about RTL is that some languages are written right-to-left. In a WordPress theme, what role does the <code> rtl.css </code> stylesheet have? I was under the impression that the only difference was paragraph alignment, but the WordPress themes that I have seen have massive <code> rtl.css </code> files. What other requirements are there of CSS to provide true RTL support?
This guy explains it fairly well for wordpress (video, no transcript): Yoav Farhi: Right to Left WordPress . The Wordpress Manual (Codex) has as well some information regarding Right to Left Language Support .
RTL Stylesheet Confusion with WordPress
wordpress
Is there anyway to get wordpress to automatically switch locales based on the HTTP Accept-Language header? Similar to how ASP.NET can do it with their globalization="auto" config setting. The reason for this is that I want my dates to be custom formatted based on where you are viewing the site from - not what the wordpress site settings use for everybody around the world. This way somebody from the USA (en-US) will see 12/25/2011 but somebody from Australia (en-AU) will see 25/12/2011.
that's going to be a bit tricky since WordPress doesn't relate date and time format to language. so to get the current language from the browser you can use <code> $_SERVER['HTTP_ACCEPT_LANGUAGE'] </code> and then based on that you can change the date format: <code> function update_date_format(){ $lang = substr($_SERVER['HTTP_ACCEPT_LANGUAGE'], 0, 2); if (strpos($lang, 'au') &gt; 0){ $date_format = 'd/m/Y'; // 25/12/2011 }else{ $date_format = 'm/d/Y'; // 12/25/2011 } update_option('date_format',$date_format); } </code> after you paste this function in your theme's functions.php add to your theme's header.php at the very top: <code> &lt;?php update_date_format(); ?&gt; </code>
Wordpress Locale Switching on Accept-Language Header
wordpress
In the codex for WP_Query I see you can query by 'page_id=7' for pages or by 'p=7' for posts... is there a way to get a 'post of any post type' by ID? like 'id=7'—that will get it no matter if it's a page, post or custom post type? I can only get WP_Query with p=7 to work if I add &amp;post_type=customposttype. Is there a way to get it from the ID regardless of post type?
'any' should retrieve any type: <code> $args = array( 'p' =&gt; 42, // id of a page, post, or custom type 'post_type' =&gt; 'any'); $my_posts = new WP_Query($args); </code>
WP_Query by just the id?
wordpress
I have a function to display the children of the page in the sidebar php file using wp_list_pages: <code> global $post; ?&gt; &lt;div id="subChildren"&gt; &lt;?php if($post-&gt;post_parent) $children = wp_list_pages("sort_column=menu_order&amp;title_li=&amp;child_of=".$post-&gt;post_parent."&amp;echo=0"); else $children = wp_list_pages("sort_column=menu_order&amp;title_li=&amp;child_of=".$post-&gt;ID."&amp;echo=0"); if ($children) { ?&gt; &lt;ul id="submenu"&gt; &lt;?php echo $children; ?&gt; &lt;/ul&gt; </code> I have also created a shortcode that shows a custom post type using query posts: <code> function casestudy_shortcode() { extract(shortcode_atts(array( 'type' =&gt; 'case_studies', 'limit' =&gt; '1', 'case' =&gt; '', 'size' =&gt; 'small' ),$atts)); //The Query query_posts('post_type='.$type.'&amp;showposts='.$limit.'&amp;p='.$case); //The Loop if ( have_posts() ) : while ( have_posts() ) : the_post(); //return sb_post_image('100','100'); //the_post_thumbnail('portfolio'); return "&lt;div class='".$size."'&gt;&lt;a href=\"".get_permalink()."\"&gt;".get_the_title()."&lt;/a&gt;" . get_the_excerpt() ."&lt;/div&gt;";; endwhile; else: endif; wp_reset_query(); } add_shortcode('casestudy', 'casestudy_shortcode'); </code> The problem I have is that when the shortcode is in a page it makes the sub pages not show up. I assume it is overriding the $post variable. I have tried using wp_query and get_posts for the shortcode but i get the same result. Is there a way around this?
you really shouldn't use <code> query_posts() </code> for anything other then the main query of the page. Instead you should use wp_query() or get_posts() , also since you return a value before running wp_reset_query() then its never actually being reset. so change your shortcode to this: <code> function casestudy_shortcode($atts){ extract(shortcode_atts(array( 'type' =&gt; 'case_studies', 'limit' =&gt; '1', 'case' =&gt; '', 'size' =&gt; 'small' ),$atts)); //save the real $post global $post; $real = $post; //The Query $args = array( 'post_type' =&gt; $type, 'posts_per_page' =&gt; $limit); if ($case != ''){ $args['p'] = $case; } $s_query = NEW WP_Query($args); //The Loop if ( $s_query-&gt;have_posts() ) : while ( $s_query-&gt;have_posts() ) : $s_query-&gt;the_post(); //return sb_post_image('100','100'); //the_post_thumbnail('portfolio'); $return .= "&lt;div class='".$size."'&gt;&lt;a href=\"".get_permalink()."\"&gt;".get_the_title()."&lt;/a&gt;" . get_the_excerpt() ."&lt;/div&gt;"; endwhile; else: endif; $post = $real; wp_reset_query(); return $return; } add_shortcode('casestudy', 'casestudy_shortcode'); </code>
post var problem with shortcode loop
wordpress
I want to ban people or limit registering on unique national ID (You can think it as 11 digit number). Is there any plugin or a code snippet you know? Site will based on MultiSite + BuddyPress. Update: I am not looking for IP ban. You can think it like phone number.. And every user must have 1 unique phone number and i need to ban that phone number if need. (Sorry for bad english)
first of all, thanks a lot for every answer and everyone who thought a solution for this. my best possible solution without changing too much thing: As i said in a comment, i will use http://www.gravityforms.com/add-ons/user-registration/ for registering. This plugin working even you disable wordpress user registeration. So i will disable user registeration and this plugin's form will be only way to register to this site. Critical option in there was "No Duplicates". I will select "No Duplicates" for this number input so plugin will use its previous form data for not letting 2 registeration with this number. So if i want to ban someone, i can just ban him with normal wordpress banning system and he cant register twice so problem is solved imo. And again thanks a lot for trying to help :) Note: I am not doing adversitement or anything, just sharing my solution so i hope its ok.
Using a number for limiting registering or banning on multisite
wordpress
I'm trying to determine if a piece of content can be edited by a user. I would like all roles contributor and above to be authorized by a single check. Here's my code: <code> if( empty( $post_id ) || !current_user_can('edit_post', $post_id) ) { return; } </code> Unfortunately, the only users that don't get the <code> return </code> are super admins. Any idea why?
And the correct capability name is <code> edit_posts </code> . So the correct way of using <code> current_user_can </code> will be like following: <code> if( empty( $post_id ) || !current_user_can( 'edit_posts' ) ) { return; } </code> UPDATE: I have removed the wrong statement, but as the asker mentioned he would like to allow all roles of contributors and above to be authorized for that particular check, I think just checking for <code> edit_posts </code> caps is enough. Sorry for the wrong statement.
Why does this check to see if user is authorized to edit a post fail for all but super admins?
wordpress
I have three columns, each displaying 2 posts, each from different categories and each being a new query. These three columns are shown on thier parent category page, which is set to display 6 posts per page. <code> $soundPosts = new WP_Query('posts_per_page=2&amp;cat=4&amp;paged=' . get_query_var( 'paged' )); $viewsPosts = new WP_Query('posts_per_page=2&amp;cat=5&amp;paged=' . get_query_var( 'paged' )); $wordsPosts = new WP_Query('posts_per_page=2&amp;cat=6&amp;paged=' . get_query_var( 'paged' )); </code> At the moment pagination kind of works, but not properly. It is using the pagination for the main parent category. <code> &lt;div class="navigation"&gt; &lt;div class="left"&gt;&lt;?php previous_posts_link('&amp;#60; Previous') ?&gt;&lt;/div&gt; &lt;div class="right"&gt;&lt;?php next_posts_link('Next &amp;#62;','') ?&gt;&lt;/div&gt; &lt;/div&gt; </code> The pagination kind of works, as the parent category contains the posts, and is set to show 6 posts, but it doesn't always work as the posts aren't always equally distributed throughout the columns. How can I manually build the navigation links, so they run off the queries above, rather than the archive's default pagination? And how and the end of all records can I make the archive return a 404 page, for use with infinte scroll. Also of note, I am aware of this stackexchange-url ("question / answer"), but don't think it is an accpetable solution, or is in fact the same setup I have currently. Thanks alot for any pointers!
OK this is what I ended up with, that works well: <code> // get paged value. $paged = get_query_var( 'paged' ); $maxPages = array(); $max = 0; // Create the queries $soundPosts = new WP_Query('posts_per_page=1&amp;cat=4&amp;paged=' . $paged); $viewsPosts = new WP_Query('posts_per_page=1&amp;cat=5&amp;paged=' . $paged); $wordsPosts = new WP_Query('posts_per_page=1&amp;cat=6&amp;paged=' . $paged); // get max number of pages for each query array_push($maxPages,$soundPosts-&gt;max_num_pages); array_push($maxPages,$viewsPosts-&gt;max_num_pages); array_push($maxPages,$wordsPosts-&gt;max_num_pages); // get the max number of pages from all three. $max = max($maxPages); // If we are out of posts, return 404 if ($paged &gt; $max) { $wp_query-&gt;set_404(); status_header('404'); } // proceed as normal. get_header(); </code> Then for the pagination links, just a bit of logic from the variables created to decide whether to show the links or not. <code> &lt;?php if ($paged &gt; 0 &amp;&amp; $paged &lt; $max) { ?&gt; &lt;div class="left"&gt;&lt;?php previous_posts_link('&amp;#60; Previous') ?&gt;&lt;/div&gt; &lt;?php } if ($paged &lt;= $max) { ?&gt; &lt;div class="right"&gt;&lt;?php next_posts_link('Next &amp;#62;','') ?&gt;&lt;/div&gt; &lt;?php } ?&gt; </code>
3 Columns, 3 Categories, One Archive, and Pagination
wordpress