question
stringlengths 0
34.8k
| answer
stringlengths 0
28.3k
| title
stringlengths 7
150
| forum_tag
stringclasses 12
values |
---|---|---|---|
Is there a way to use the <code> register_taxonomy </code> function to create child taxonomies to a specific parent taxonomy in a hierarchical structure? For example: Let's say I'm creating a theme for selling cars where users can activate it and it automatically creates a hierarchical taxonomy called "Make". Is there any way to have it automatically create a few different vehicle "make" taxonomies, say Toyota, Lexus, etc.?
|
I think you mean you want to create terms in your taxonomy? Have a look at stackexchange-url ("this answer") for detecting when a theme is activated. Then use wp_insert_term to insert the terms into your taxonomy.
|
Create Child Taxonomies
|
wordpress
|
I had a theme in 3.0b2 that was registering custom post types and displaying them in the admin menu just fine -- after upgrading to 3.1.2, they no longer appear in the sidebar admin menu (although they do get queried properly from the theme pages for the non-admin portions of the site). <code> show_ui </code> is set to <code> true </code> and adding <code> show_in_menu </code> as true for good measure had no effect. Can anyone help? <code> function balmer_init() { //print ("Here"); register_post_type('gig', array( 'label' => __('Gigs'), 'singular_label' => __('Gig'), 'public' => true, 'show_ui' => true, '_builtin' => true, '_edit_link' => 'post.php?post=%d', 'capability_type' => 'post', 'hierarchical' => false, 'rewrite' => false, 'query_var' => false, 'supports' => array('title', 'editor',/* 'custom-fields' */), 'register_meta_box_cb' => 'gig_callback', )); } add_action("init","balmer_init"); </code> Thanks!
|
Remove the errors in your registering function: <code> 'Gigs' </code> is not part of the default language file. Either add your text domain as second parameter or drop the translation function. <code> '_builtin' => true </code> is wrong. Remove the parameter; it is for native post types only. <code> 'supports' => array('title', 'editor',/* 'custom-fields' */), </code> – the comma after <code> editor </code> is a syntax error. Turn debugging on to see such errors.
|
Custom post type menu missing after 3.0b2 -> 3.1.2 upgrade
|
wordpress
|
Say I just have a dumb .php file sitting on my WP server and I wanted it to access WP info through the API, how would I go about doing that? For example if I wanted to call <code> bloginfo('url'); </code> As I have scored myself a downvote (with no explanation) I will expound upon why I am interested in this. Sure I can access WP API from all the built-in pages. But let's say I have a page that has little to do with WP. Seems like a lot of overhead to create say a custom template page and then hook it into an actual post, all so that I can have access to a few WP API calls. I ended up using something like this: <code> require $_SERVER['DOCUMENT_ROOT'].'/wp-blog-header.php'; </code>
|
You mean something like this? <code> <?php require 'path/to/wordpress/wp-blog-header.php'; bloginfo('url'); ?> </code>
|
Hook any php file into the wordpress api
|
wordpress
|
Can't figure out why this won't work: <code> function my_get_attachment_link($html){ $postid = get_the_ID(); $html = str_replace('<a','<a rel="shadowbox['.$postid.']"',$html); return $html; } add_filter('wp_get_attachment_link','my_get_attachment_link',10,1); </code> Just trying to hook up all the images on a single post view to a lightbox script. FYI, this didn't work either: http://wordpress.mfields.org/2010/thickbox-for-wordpress-gallery/#highlighter_196509 What could be jamming it up?
|
Your code only works if you are actually calling <code> wp_get_attachment_link() </code> somewhere in your template . If you're not calling the function, then the <code> apply_filters() </code> inside the function will never get called, and therefore your code will have nothing into which to hook.
|
Can't filter wp_get_attachment_link
|
wordpress
|
I've found a way to insert a customized gallery inside my wordpress template but I'm not sure this is the better way. I've uploaded my images with the default image uploader of wordpress to manage the photos, than I've removed it from the post article and managed the media from the <code> loop-single.php </code> page template I've created like this: <code> <?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?> <header> <script type="text/javascript"> /* gallery */ var params = { autostart:true, easing:'easeInOutExpo', transition:750 }; var gallery = new ImgGalleryManager ('#site-gallery', '#gallery-menu', 'selected', params); /* */ </script> <?php $args = array( 'order' => 'ASC', 'post_type' => 'attachment', 'post_parent' => $post->ID, 'post_mime_type' => 'image', 'post_status' => null, 'numberposts' => -1, ); $attachments = get_posts($args); if ($attachments) { $html = '<div id="site-gallery"> <table> <tr>'; foreach ($attachments as $attachment) { //echo apply_filters('the_title', $attachment->post_title); $html .= '<td>'. wp_get_attachment_link($attachment->ID, 'full', false, false).'</td>'; if (empty($list_imgs)) { $list_imgs = '<div id="gallery-menu"><div class="img-selector selected"></div>'; } else { $list_imgs .= '<div class="img-selector"></div>'; } } $html .= '</tr> </table> </div>'.$list_imgs.'</div>'; echo $html; } ?> </header> <div id="cnt-title"><?php the_title(); ?></div> <div id="post-content"> <?php the_content(); ?> </div> <div> <?php the_tags(); ?> </div> <?php endwhile; // end of the loop. ?> </code> I can't believe this is the best way to manage photos but I don't know wordpress and I've did the first thing I thought. Should I use a better way to custom the image gallery of a post or is this the best way? Is it possible to customize the <code> [gallery] </code> in the <code> loop-single.php </code> page without remove it and create it manually? I've read here how to customize the gallery, but if I do it I'll print the customized gallery, and than with <code> <?php the_content(); ?> </code> I'll print it again with the default wordpress style. Does exists some way to customize <code> [gallery] </code> directly?
|
I'm good with everything except for the removed it from the post article part. Leaving the images attached to the Post actually makes it easier to work with the images, because you can query them by <code> post_parent </code> . Also: what do you mean by managed the media from the <code> post-template.php </code> ? Are you saying that you modified the core <code> post-template.php </code> file?
|
Customizing the gallery of the post correctly
|
wordpress
|
How do i get output of this in alphabetical order <code> <?php $termID = 5; $taxonomyName = 'area'; $termchildren = get_term_children( $termID, $taxonomyName ); echo '<ul>'; foreach ($termchildren as $child) { $term = get_term_by( 'id', $child, $taxonomyName ); echo '<li><a href="' . get_term_link( $term->name, $taxonomyName ) . '">' . $term->name . '</a></li>'; } echo '</ul>'; ?> </code>
|
<code> get_term_children() </code> only outputs the term IDs, and you later get details for each term using <code> get_term_by() </code> . You can combine these queries in one using <code> get_terms() </code> with the <code> child_of </code> argument: <code> get_terms( $taxonomyName, array( 'child_of' => $termID ) ); </code> By default this sorts by name. However, it is possible that the <code> child_of </code> argument undoes the sorting. In that case you can sort it again using <code> usort() </code> . See an example at stackexchange-url ("this answer for a related problem").
|
How to get_term_children output in alphabetical order?
|
wordpress
|
Im using a WordPress transient, which expires after an hour, to store a value which is an integer. Im trying to use <code> switch() </code> and multiple <code> case() </code> statements to evaluate if the transient exists or not (i.e true or false). Here are my questions: Which comparison operator ( <code> = </code> , <code> == </code> , <code> === </code> ), in example 2, is ideal for this context? Which of the following examples is appropriate? Would the following examples yield the same result? Example 1: <code> $transient = get_transient( 'foobar' ); switch( $transient ) : case( true ) : // do stuff break; case( false ) : // do stuff break; endswitch; </code> versus Example 2: <code> $transient = get_transient( foobar ); switch( $transient ) : case( $transient = true ) : // do stuff break; case( $transient = false ) : // do stuff break; endswitch; </code> Thanks in advance.
|
Does it have to use a switch? why not something like this: <code> if ( false === ( $value = get_transient( 'value' ) ) ) { // this code runs when there is no valid transient set } else { // this code runs when there is a valid transient set } </code> If the a transient returns a value it will not return true. It returns the value of the transient. If the transient is not set then it returns bool(false) if you are using a switch it would be like this: $transient = get_transient( foobar ); <code> switch( $transient ) : case false: // transient not set break; default: // transient didnt return false break; endswitch; </code>
|
get_transient(), PHP switch(), and comparison operators
|
wordpress
|
I have a website where users can register, login and their edit profile, they can comment but not post. What I am looking for is a way to display a user profile page (where I display the gravatar and the info about the user) clicking on the username. The url must be something like "www.mywebsite.com/user/username". I know about author.php, but I don't know how to link even if the user has no posts and is not an author. UPDATE: I managed to solve it. Instead of linking using <code> <?php the_author_posts_link(); ?> </code> I did an href linking to <code> www.mysite.com/user/<?php echo $user_info->display_name; ?> </code> To rename the slug I installed the Edit author slug plugin , it makes the author slug editable under Settings > permalinks. To customize the user profile, just edit authors.php as you like.
|
Every registered user can have profile, they don't need to have posts. To change Wordpress author's profile permalink, paste the following code in your functions.php: <code> function change_author_permalink_base() { global $wp_rewrite; $wp_rewrite->author_base = "user"; } add_filter( 'init', 'change_author_permalink_base' ); </code> After pasting the code, visit Settings-> Permalink Structure under your wordpress admin, to flush the rewrite rules. This is a required step, otherwise you may get 404 on author profiles. Then code your author.php. As far as linking is concerned this is totally your design decision. If you want to link the profiles from user's comment, you can either add the new link or just link comment author name to their profile. Remember the profile is available only if the user is registered as Wordpress user.
|
Display a registered user profile page
|
wordpress
|
I am using this script to get the last time a user logged in <code> function get_last_login($user_id) { $last_login = get_user_meta($user_id, 'last_login', true); echo human_time_diff($last_login) . " " . __('ago'); } </code> I am calling it in author.php with <code> <p>Last login: <?php get_last_login($userdata->ID); ?></p> </code> I am trying to output like "last login X days ago" but I can't get it working. $last_login output is <code> 2011-05-13 18:00:06 </code> but the final output I get is <code> last login 15108 days ago </code>
|
Are you formatting the <code> mysql2date() </code> input string as <code> 'Y-m-d H:i:s' </code> , as specified in the Codex? Also, why not use this same format as <code> $date_format </code> ? EDIT: What output do you get for <code> $last_login? </code> The second argument in <code> human_time_diff() </code> is optional. Why not just omit it? That way, if you get valid output from <code> $last_login </code> , you should get valid output from <code> human_time_diff() </code> . EDIT: The <code> human_time_diff() </code> function expects a UNIX timestamp for its first argument. Try wrapping <code> $last_login </code> in <code> mktime() </code> , e.g.: <code> $last_login_unix = mktime( $last_login ); human_time_diff( $last_login_unix ); </code> EDIT: Might want to use <code> strtotime() </code> instead of <code> mktime() </code> : <code> $last_login_unix = strtotime( $last_login ); human_time_diff( $last_login_unix ); </code>
|
Display last login time
|
wordpress
|
Basically there are sub-sites that inherit all the pages. But I have worked out ways for each page to be unique to their location, by creating a shortcode that pulls in the Blog Description. The point is I am not trying to spam the web, but this site needs to reach different people in different towns. And I don't want to repeat all the content each time. I have installed threewp broadcast and multipost MU and tested them out, but when you add a site you have to go through each time you add each page to the new site. There are 50+ pages. Essentially I want to make sure the main site is right, then add a new site and have all the pages automatically added. I can go through and mess with the settings on each site to give it the right homepage and all that but adding the pages individually is a pain... ideas?
|
I think that is possible with the plugin WordPress MU Sitewide Tags: ( http://wordpress.org/extend/plugins/wordpress-mu-sitewide-tags/ ) With that plugin you can republish content from all sites OR a selection and you can choose to publish it to the main site OR to a new subsite.
|
How can I automatically duplicate a site's pages onto network site?
|
wordpress
|
What is the best method (as of 3.1 or 3.2 beta) to sort a custom post type archive by a given taxonomy term? I'm trying to make a staff page and I want to sort employees by department. So the taxonomy would be <code> staff </code> and the terms to sort would be <code> sales </code> and <code> support </code> . I tried <code> query_posts </code> and <code> WP_Query </code> but perhaps I messed up the arg array...
|
Good question - I'm fairly sure you can't do this just using wp_query. You'll need to either add a posts_groupby filter, or just query the database directly. This previous question and answer might be helpful stackexchange-url ("Using wp_query is it possible to orderby taxonomy?")
|
Sort Custom Post Type Archive by Taxonomy Term
|
wordpress
|
I was trying to set up a few pages the other day that would hold an authors information (only to be accessed from the author snippet at the bottom of posts), and obviously these pages are showing up in the <code> <?php wp_list_pages('title_li='); ?> </code> , I made sure of my page order (0-5 are the pages that must be there, and I set up the special pages to start with an id of 44 just in case they added some pages), and then tried <code> <?php wp_list_pages('title_li=&exclude=44'); ?> </code> . However, 0-5 show up, as well as 44. Any thoughts on why this is still occurring?
|
it sounds from your text that you are using the number you gave it under 'page attributes' 'order'; use the page ID instead for the 'exclude'.
|
Excluding Pages not working
|
wordpress
|
Now im getting a couple of disposable email accounts in users table, how can I avoid this nasty situation?
|
You might need this plugin: http://wordpress.org/extend/plugins/no-disposable-email/
|
How to disable or protect against disposable email accounts?
|
wordpress
|
I'm using twentyten and have overloaded home.php to do some custom stuff. However, I would still like to have a page that lists all of my recent posts, archive-style. I can get to an archive page for any given category with myblog/category/category-name. But I'd like to get to an archive that just lists all recent posts, regardless of category. Like myblog/archive Am I assuming too much? I know I can create a custom page template and then create a custom page and apply that template. I just thought that wordpress had a built-in "archives" page, no?
|
No, there is no "full archive" page like you describe created by default. This would basically be the twentyten index page set to display "your latest posts." If you don't want to access the archives via some sort of filter (category, author, year, month etc.) then you will need to create your own archive template and page like you described above. you could also use the twentyten index.php as the basis for your new template. So you can create the archive page, set it to use your new template and use the url myblog/archive like you wanted.
|
What is the link to my default "archive" page?
|
wordpress
|
On my Wordpress site I have a three level navigation. In the second level of every main navigation item is a "toolkit" page. I would like to highlight this page in the navigation. Is there anyway that I can add a class to a page, so that I could style its navigation link separately? Is there a plugin out there that would allow me to do this? I'm hoping it would be something like in the Page Editor screen is a custom field that allows me to input a class. The class is then generated when calling the WP_List_Pages function. Then with some simple CSS and can change the background of all those links. Thanks in advance.
|
You could also simply use css: <code> #menu-item-ID </code> (where "ID" is the unique ID of the page/post/category/whatever).
|
Add class to navigation link of page
|
wordpress
|
I'm running WP 3.1.2 on an Apche server with the latest PHP installed. My WP is setup for a subdirectory multisite. The themes for the sites are usually a modified TwentyTen theme. After installing a new plugin, I activate per site, not network, and I'm able to then click through to a few links in the admin UI before I'm prompted with an error starting with Warning: require_once It doesn't matter what plugin is installed or how it's activated (per site or network). I have verified that the "missing file" is where it should be. I am using the latest version, most of them have been updated with in the past month or so and as per the official WP forum for the plugins, other users claim them to work properly. It's becoming a real nuisance to have to go into every plugin and hard code the directory to each plugin file. I have tried reinstalling all the WP core files to no avail. Has anyone else seen this or know how to fix it? Edit: On a completely different domain with a brand new install of WP on a new database, I'm seeing hte same thing. Any new plugin install shows a missing file error. This is extremely annoying and I need to fix it. I suspect it's something within Apache but not sure.
|
I ended up migrating to a new server and that fixed all the problems. I think something was corrupted on the original server after an update.
|
Plugin error after installation
|
wordpress
|
Im trying to build a shortcode which calls an HTML table with a fixed number of columns and a variable number of rows depending on the context. Its hard to manage — or even build, multiple tables over and over through HTML. I've had no trouble creating fixed columns and rows through shortcodes. To illustrate through the usage of a trivial example: Lets assume i build a table with 4 columns and 1 row. The 4 columns will contain the following table headers: Product name Quantity Price per item Total price What if i wanted to create multiple rows (Product 1, Product 2 etc..), if at all possible, how can i build a shortcode that enables me to add more rows as i see fit — without creating a separate shortcode for table rows (been there).
|
pass your data in single variables delimited by some char: <code> [myproduct cols="name,quantity,price" data="name1,5,2.00,name2,3,3.25"] </code> then explode it into an array and output. I didn't bother with table markup here, but you get the idea: <code> function myproduct_func( $atts ) { extract( shortcode_atts( array( 'cols' => 'none', 'data' => 'none', ), $atts ) ); $cols = explode(',',$cols); $data = explode(',',$data); $total = count($cols); $output = ""; foreach($cols as $col): $output .= "| {$col} "; endforeach; $output .= "<br>"; $counter = 1; foreach($data as $datum): $output .= "| {$datum} "; if($counter%$total==0): $output .= "<br>"; endif; $counter++; endforeach; return $output; } add_shortcode( 'myproduct', 'myproduct_func' ); </code>
|
Shortcodes, HTML tables, and multiple rows
|
wordpress
|
I want to have a central "data" sheet that is regularly drawn upon for types of posts that are submitted. Lets say I had a movie review site, but also want to let people post other info, like Trivia or some such. So I would have 2 custom posts types (or perhaps one if I let Reviews just be handled in Posts). I want both the review and the trivia to be search for by the movie title, the production company, the category the movie is in, etc. I've been creating Taxonomies for each of these properties outside of the category. What I've run into though is that every time a new review or piece of trivia is created for that movie, one would have to re-enter all that data. I rather just have them choose the Movie title, and have the rest of that data inherited. So if they chose "Scream 4" for their review, it automatically inherits the "Horror" Category, "Wes Craven" as the director, and "Dimension Films" as the Studio without someone have to individually assign those taxonomies each time something is created. Is there any way to do such a thing?
|
I'd suggest to use Posts 2 Posts plugin, see plugins page and wiki for more information
|
Any way to make posts inherit properties/taxonomies through a single assigned taxonomy
|
wordpress
|
How can I get all enqueued styles or scripts and then deregister them all at once?
|
I hope you know what you are doing. You can wp_print_styles and wp_print_scripts action hooks and then get the global $wp_styles and $wp_scripts object variables in their respective hooks. The "registered" attribute lists registered scripts and the "queue" attribute lists queue scripts on both of the above objects. An example code to empty the scripts and style queue. <code> function pm_remove_all_scripts() { global $wp_scripts; $wp_scripts->queue = array(); } add_action('wp_print_scripts', 'pm_remove_all_scripts', 100); function pm_remove_all_styles() { global $wp_styles; $wp_styles->queue = array(); } add_action('wp_print_styles', 'pm_remove_all_styles', 100); </code>
|
How can I de-register ALL styles all at once? And same with Javascript?
|
wordpress
|
Just noticed that 3.1 added a new filter to customize queries: posts_clauses. All I could find about it is that instead of using the separate query filters like posts_where or posts_join, you can edit them all in one go. I was wondering if someone could give an example of the usage of the new "posts_clauses" filter?
|
Below is the query I found somewhere and was going through it. The purpose of query is to sort the posts based on taxonomy. So, I am sharing the code so it might help you understand the use of posts_clauses. <code> function color_clauses_mike( $clauses, $query ) { global $wpdb; if ( isset( $query->query['orderby'] ) && 'color' == $query->query['orderby'] ) { $clauses['join'] .= <<<SQL LEFT OUTER JOIN {$wpdb->term_relationships} ON {$wpdb->posts}.ID={$wpdb->term_relationships}.object_id LEFT OUTER JOIN {$wpdb->term_taxonomy} USING (term_taxonomy_id) LEFT OUTER JOIN {$wpdb->terms} USING (term_id) SQL; $clauses['where'] .= " AND (taxonomy = 'color' OR taxonomy IS NULL)"; $clauses['groupby'] = "object_id"; $clauses['orderby'] = "GROUP_CONCAT({$wpdb->terms}.name ORDER BY name ASC) "; $clauses['orderby'] .= ( 'ASC' == strtoupper( $query->get('order') ) ) ? 'ASC' : 'DESC'; } return $clauses; } add_filter( 'posts_clauses', 'color_clauses_mike', 10, 2 ); </code> here is the source where I found the above query: http://scribu.net/wordpress/sortable-taxonomy-columns.html
|
Usage of the new "posts_clauses" filter in Wordpress 3.1?
|
wordpress
|
I'm writing a plugin, bar , which is dependent on another plugin, foo , being activated, and I need the functions from foo to be available when bar loads. Normally plugins are loaded in alphabetical order based on the directory name, so bar is loaded before foo . If I rename the bar directory to zbar then it gets loaded last and works fine, but I'm looking for a more elegant and correct solution. I've followed jsdalton's method of altering the <code> active_plugins </code> option , and it is reordering the array to place bar at the end, but bar still can't access foo 's functions when it instantiates. I've read through the relevant core code -- basically <code> wp-settings.php </code> and <code> wp_get_active_and_valid_plugins() </code> in <code> wp-includes\load.php </code> -- and it seems like plugins should be loaded in the order they're indexed inside <code> active_plugins </code> , so I can't figure out what's going wrong. This is on a MultiSite installation. bar is a class and foo is procedural. Here's a stripped-down version of foo/foo.php <code> function foo() { // stuff } </code> And here's a stripped-down version of bar/bar.php <code> class bar { public function __construct() { // ... $active_plugins = get_option('active_plugins'); print_r($active_plugins); if( function_exists('foo') ) wp_die("foo exists"); else wp_die("foo doesn't exist yet"); } } } function this_plugin_last() { $wp_path_to_this_file = preg_replace('/(.*)plugins\/(.*)$/', WP_PLUGIN_DIR."/$2", __FILE__); $this_plugin = plugin_basename(trim($wp_path_to_this_file)); $active_plugins = get_option('active_plugins'); $this_plugin_key = array_search($this_plugin, $active_plugins); if ($this_plugin_key) { array_splice($active_plugins, $this_plugin_key, 1); array_push($active_plugins, $this_plugin); update_option('active_plugins', $active_plugins); } } add_action("plugins_loaded", "this_plugin_last"); $bar = new bar(); </code> This is the output from bar 's constructor: <code> Array ( [0] => foo/foo.php [1] => bar/bar.php ) foo doesn't exist yet </code>
|
No matter what, your constructor of bar will always run before the action is called in your code. I ran into this scenario a while back, and you're mostly there for how I did it. Simply put - comment out everything inside this_plugin_last function, and put your $bar = new bar(); inside there. and just do all of the logic and whatnot that you needed to in that function as well. this ensures that foo will be loaded before you run your code (the plugin itself doesn't necessarily need to be loaded before hand, just what you use that relies on foo).
|
Changing Plugin Load Order
|
wordpress
|
This is somewhat of a follow-up to a question I asked some time ago: stackexchange-url ("Trying to design nice category drilldown with one "held" taxonomy and a repeatable list of categories") I've sort of got a better idea of what I want, but only a vague idea of how to accomplish it and I was hoping to get some feedback. I'm going to be using wordpress as a CMS. Instead of posts with blog-type info, I'd be making Products with a number of shared properties (which I'd assign to taxonomies). I want to create a good search/navigation area for people to be able to find the Product Info/Review that they want. Really something like New Egg (www.newegg.com) has when you try and find a piece of computer equipment you want. Were you go in and start in say the Processor category, and then you can drilldown to what you want. All the posts with the 3GHZ taxonomy. The Search box would adjust then to show all those posts and the remaining taxonomies you could drill down by, socket type, AMD/Intel etc... and have it hold on to those properties as you pass through. I know I can use either cookies or a session to hold the values as I pass down through them, but not entire sure how to approach the rest of the code. I'm looking for any open source examples I might be able to look through where this has been done before that would help me develop something like this for my site. Thanks in advance!
|
There's a way to set custom post-type search. I can only head you in the right direction and answer the first part of your question. The other part about COOKIES you'll have to review php documentation. Also, I don't know exactly what the other <code> $_REQUEST </code> variables you may have set for your custom post type. But here's a technique on how you can hidden input fields to set various post/get/request values. I.E. Here is how you set which custom post type: <code> <form role="search" method="get" id="searchform" action="<?php echo home_url( '/' ); ?>"> <input type="text" name="s" id="s" value="Enter keywords ..." onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/><br /> <select name="post_type"> <option value="">Choose Category:</option> <option value="">All Categories</option> <option value="post_type_a">Post Type A</option> <option value="post_type_b">Post Type B</option> <option value="post_type_c">Post Type C</option> </select><br /> <input type="submit" id="searchsubmit" value="Search Help" /> </code> Thus when you submit the value the search will add <code> $_REQUEST['post_type'] </code> to your search. You can also do this with a hidden form: <code> <input type="hidden" name="post_type" value="your_post_type" /> </code> and have javascript dynamically change the value of above field. More on this: http://wordpress.org/support/topic/limit-search-results-to-custom-post-type?replies=8 http://dbaines.com/blog/archive/wordpress-custom-post-type-multiple-search/ So potentially you could just add another hidden field to limit your search with javascript etc. Hope that helped!
|
Using Wordpress to make a "Product Search" type navigation drilldown
|
wordpress
|
My query is currently sorting by end date. How can I make it so it will sort by the start date? <code> $args = array ('post_type' => 'events', 'meta_query' => array( array( 'key' => 'start_date', 'value' => $min_date, 'compare' => '>' ), array( 'key' => 'start_date', 'value' => $max_date, 'compare' => '<' ), array( 'key' => 'end_date', 'value' => $current_date, 'compare' => '>' ) ), 'orderby' => 'meta_value', 'order' => 'ASC' ); </code>
|
try adding: <code> 'meta_key' => 'start_date' </code>
|
How to "orderby" the first array in a meta_query that uses multiply keys?
|
wordpress
|
Ok, so I have registered a few custom post types and a few taxonomies. Now, for the life of me, I cannot figure out the code I need to add a Custom Field to my Custom Post Type. I need a drop down and a single line text area. But I also need to have separate fields for post types. So, say post type one has 3 fields and post type 2 has 4 fields but the fields are different. Any tips would help I have looked at the codex and found something but cannot make sense of what I need to add to my <code> functions.php </code> file
|
This is probably more complicated than you think, I would look into using a framework: http://wpgear.org/#meta-fields If you want to write your own , here are some decent tutorials: http://net.tutsplus.com/tutorials/wordpress/creating-custom-fields-for-attachments-in-wordpress/ http://sltaylor.co.uk/blog/control-your-own-wordpress-custom-fields/ http://thinkvitamin.com/code/create-your-first-wordpress-custom-post-type/
|
How to Add Custom Fields to a Custom Post Type?
|
wordpress
|
Is there a way to have specific css on the homepage and use a different one for all the other pages?
|
Yes there is. You can add this to your themes header. <code> <?php if(is_home()){ // we are on the home page echo '<link rel="stylesheet" src="your_stylesheet" />'; } ?> </code> You can also use other conditional tags to find out if you are on nearly every type of WordPress page. Conditional Tags Following on from the comments below, this would be better used like this <code> <?php if(is_home()){ // we are on the home page echo '<link rel="stylesheet" src="your_home_stylesheet" />'; }else { echo '<link rel="stylesheet" src="your_default_stylesheet" />'; } ?> </code>
|
Specific css on homepage, different one for other pages
|
wordpress
|
Tried them both and they don't seem to be working, am I missing something? <code> add_action('admin_footer', 'jupload_scripts'); wp_register_script('jquery-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js', array('jquery'), '1.8.6'); wp_enqueue_script( 'jquery-ui' ); } </code>
|
As per Wordpress Codex its best to register and queue your scripts with the hook dedicated for them, even if you want your script to be added to footer. So the correct way of doing it will be: <code> function jupload_scripts() { wp_enqueue_script( 'jquery-ui', 'http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js', array('jquery'), '1.8.6', true ); } add_action( 'admin_print_scripts', 'jupload_scripts' ); </code>
|
Hooks: admin_footer and admin_print_footer_scripts not working?
|
wordpress
|
Some days ago I've upgraded my single-site WP installation to support a multi-site WP website. So I've created two new sites and set the same theme I was using on my single WP blog before. But unluckily, looking at the HTML source, I've noticed that these new sites use a different path to retrieve their theme. They both use "$SITENAME/wp-content/Themes/...", while I would expect it to be merely "/wp-content/Themes/...". I want to change this behavior because I don't want my visitors to download three times my website (because there are 3 sites, and each uses its own wp-content directory). These are my settings: <code> define( 'MULTISITE', true ); define( 'SUBDOMAIN_INSTALL', false ); $base = '/'; define( 'DOMAIN_CURRENT_SITE', 'my-website.org' ); define( 'PATH_CURRENT_SITE', '/' ); define( 'SITE_ID_CURRENT_SITE', 1 ); define( 'BLOG_ID_CURRENT_SITE', 1 ); </code> And this is the .htaccess: <code> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] # uploaded files RewriteRule ^([_0-9a-zA-Z-]+/)?files/(.+) wp-includes/ms-files.php?file=$2 [L] # add a trailing slash to /wp-admin RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^[_0-9a-zA-Z-]+/(wp-(content|admin|includes).*) $1 [L] RewriteRule ^[_0-9a-zA-Z-]+/(.*\.php)$ $1 [L] RewriteRule . index.php [L] </code> Is there a way to do what I want? I was also considering the use of subdomains, in particular "static.my-website.org" to serve the static content, like themes, files, and so on, but if I can't solve this, ...
|
I've just discovered that /$SITENAME/wp-content redirects to /wp-content, so that my visitors don't load the themes three times.
|
How to set a single theme directory on a multisite blog?
|
wordpress
|
I'm trying to be a good thememaker and pass all my settings through the Settings API, but I'm running into some difficulty in the sanitization callback function. The core of the problem is this: the $input variable, passed in by default, is empty. My $_POST[options group] is coming through just fine (it has everything I'd expect to see in $input) but, again, $input is empty. Where do I even start looking to debug this? EDIT 1 In response to Chip, here's what I have (stubbed, obviously): <code> function lblg_sanitize_options( $input ){ global $lblg_shortname, $lblg_default_options; echo "Input: "; print_r($input); </code> If I do something similar using, e.g., Oenology and do a <code> print_r($input); </code> , I get the expected <code> Array( </code> etc. EDIT 2 Here's the results of <code> print_r($_REQUEST); </code> for my theme: <code> Array ( [option_page] => lblg_options [action] => update [_wpnonce] => 1f96eb2410 [_wp_http_referer] => /wp-admin/themes.php?page=lblg_options [lblg_options] => Array ( [layout_stylesheet] => Select a layout: [alt_stylesheet] => *none* [use_custom_header] => true [display_footer_copyright] => true [footer_copyright] => [footer_credit_text] => [save] => Save changes ) ) </code> And here it is for Oenology: <code> Array ( [option_page] => theme_oenology_options [action] => update [_wpnonce] => 748c46a1a1 [_wp_http_referer] => /wp-admin/themes.php?page=oenology-settings [theme_oenology_options] => Array ( [header_nav_menu_position] => below [header_nav_menu_depth] => 1 [display_social_icons] => on [rss_feed] => rss2 [facebook_profile] => [flickr_profile] => [linkedin_profile] => [myspace_profile] => [twitter_profile] => [youtube_profile] => [display_footer_credit] => false [submit-general] => Save Settings ) ) </code> I can't spot the difference. Can you? EDIT 3 Might the various slugs/shortnames/pagenames be conflicting somehow? EDIT 4 Here's what I'm doing for registration: <code> function lblg_admin_init(){ global $lblg_shortname; register_setting( 'lblg_options', $lblg_shortname . '_lblg_options', 'lblg_sanitize_options' ); } </code> Here's what I'm calling out, intra-options-form: <code> settings_fields( 'lblg_options' ); do_settings_sections( 'lblg_options' ); </code> The settings themselves are all being registered in a big loop, in a fashion similar to this: <code> add_settings_field( $key, $value['name'], '', 'lblg_options', $section ); </code> Further thoughts?
|
Answering my own question by way of an answer Chip has embedded in his excellent settings tutorial , namely: it's all about Correlating Function Arguments. Apparently some of the variable names/options group names I was using weren't lining up correctly.
|
Why might $input (Settings API) be coming through empty?
|
wordpress
|
I've just had one questions solved over here: stackexchange-url ("How to display posts from a single category within a custom taxonomy.") Now I'm wondering how to take this code: <code> <?php $args = array( 'posts_per_page' => 1, 'post_type' => 'inventory', 'tax_query' => array( array( 'taxonomy' => 'inventory-category', 'field' => 'slug', 'terms' => array( 'bulk-racks' ) ) ) ); query_posts( $args ); while ( have_posts() ): the_post(); // do stuff here ?> <?php endwhile; ?> </code> and call it using shortcodes, for example to display the bulk-racks category by using this or something similar [inventory-category="bulk-racks"] I know how to create a basic shortcode but I don't know how to write the function that would return the posts based on the shortcode category name input. Once again any help would be greatly appreciated.
|
Take a look at category post shortcode to get an idea and here is the plugin with minor modifications to call your post type and taxonomy: <code> // Taxonomy category shortcode function cat_func($atts) { extract(shortcode_atts(array( 'class_name' => 'cat-post', 'totalposts' => '-1', 'category' => '', 'thumbnail' => 'false', 'excerpt' => 'true', 'orderby' => 'post_date' ), $atts)); $output = '<div class="'.$class_name.'">'; global $post; $args = array( 'posts_per_page' => $totalposts, 'orderby' => $orderby, 'post_type' => 'inventory', 'tax_query' => array( array( 'taxonomy' => 'inventory-category', 'field' => 'slug', 'terms' => array( $category) ) )); $myposts = NEW WP_Query($args); while($myposts->have_posts()) { $myposts->the_post(); $output .= '<div class="cat-post-list">'; if($thumbnail == 'true') { $output .= '<div class="cat-post-images">'.get_the_post_thumbnail($post->ID, 'thumbnail').'</div>'; } $output .= '<div class="cat-content"><span class="cat-post-title"><a href="'.get_permalink().'">'.get_the_title().'</a></span>'; if ($excerpt == 'true') { $output .= '<span class="cat-post-excerpt">'.get_the_excerpt().'</span>'; } $output .= '</div> <div class="cat-clear"></div> </div>'; }; $output .= '</div>'; wp_reset_query(); return $output; } add_shortcode('inventory-category', 'cat_func'); </code> usage : just put this shortcode in your post or pages <code> [inventory-category totalposts="3" category="bulk-racks" thumbnail="true" excerpt="true" ] </code> totalposts - your total number of post to display. default is -1 category - category slug. use comma , for multiple slugs thumbnail - set true if you want to display thumbnail. default is false excerpt - set true if you want to display excertp. default is true orderby - your post will order by . default post_date . check http://codex.wordpress.org/Template_Tags/get_posts for detail
|
How to call custom taxonomy categories with shortcodes
|
wordpress
|
I created a custom post type, two custom taxonomies and displayed them in the 'manage post section, but I'm getting the following warning: Warning: Missing argument 2 for manage_posts_custom_column() in /home/aleche23/alexchen.info/wp-content/themes/techozoic-fluid/functions/custom-post-types.php on line 95 Picture: <code> <?php /** * Create the Blocks custom post type and the Sections custom taxonomy */ add_action('init', 'create_post_type'); // Register custom post types and custom taxonomies function create_post_type() { register_post_type('blocks',array( 'labels' => array( 'name' => __( 'Blocks' ), 'singular_name' => __( 'Block' ), 'add_new_item' => 'Add New Block', 'edit_item' => 'Edit Block', 'new_item' => 'New Block', 'search_items' => 'Search Block', 'not_found' => 'No Blocks found', 'not_found_in_trash' => 'No Blocks found in trash', ), 'public' => true, 'hierarchical' => false, 'taxonomies' => array( 'section'), 'supports' => array('title','editor','thumbnail','custom-fields'), 'rewrite' => array('slug'=>'blocks','with_front'=>false), 'menu_position' => 50, )); register_taxonomy('location','blocks',array( 'hierarchical' => true, 'labels' => array( 'name' => __( 'Locations' ), 'singular_name' => __( 'Location' ), 'add_new_item' => 'Add New Location', 'edit_item' => 'Edit Location', 'new_item' => 'New Location', 'search_items' => 'Search Location', 'not_found' => 'No Location found', 'not_found_in_trash' => 'No Locations found in trash', 'all_items' => __( 'All Locations' ), ), 'query_var' => true, 'rewrite' => array( 'slug' => 'location' ), )); register_taxonomy('section','blocks',array( 'hierarchical' => true, 'labels' => array( 'name' => __( 'Sections' ), 'singular_name' => __( 'Section' ), 'add_new_item' => 'Add New Section', 'edit_item' => 'Edit Section', 'new_item' => 'New Section', 'search_items' => 'Search Section', 'not_found' => 'No Sections found', 'not_found_in_trash' => 'No Sectionss found in trash', 'all_items' => __( 'All Sections' ), ), 'query_var' => true, 'rewrite' => array( 'slug' => 'section' ), )); // Add initial terms if (!get_option('yoursite-blocks-initialized')) { $terms = array( 'Intro', 'Tagline', 'Mainbar', 'Sidebar', 'Featured', 'Content', ); foreach($terms as $term) { if (!get_term_by('name',$term,'section')) { wp_insert_term($term, 'section'); } } update_option('yoursite-blocks-initialized',true); } } // Arrange the position of elements in the table add_filter('manage_blocks_posts_columns', 'manage_blocks_posts_columns'); function manage_blocks_posts_columns($columns) { $columns = array( 'cb' => '<input type="checkbox" />', 'title' => 'Name', 'location_column' => 'Location', 'section_column' => 'Section', 'author' => 'Author', 'date' => 'Date', ); return $columns; } // Verify that we are indeed working with only the custom post type and use a switch statement to test against the column add_filter('manage_posts_custom_column', 'manage_posts_custom_column'); function manage_posts_custom_column( $column,$post_id ) { global $typenow; if ($typenow=='blocks') { $location_taxonomy = 'location'; $section_taxonomy = 'section'; switch ($column) { case 'location_column': $location_column = get_the_terms($post_id,$location_taxonomy); if (is_array($location_column)) { foreach($location_column as $key => $location) { $edit_link = get_term_link($location,$location_taxonomy); $location_column[$key] = '<a href="'.$edit_link.'">' . $location->name . '</a>'; } echo implode(' | ',$location_column); } break; case 'section_column': $section_column = get_the_terms($post_id,$section_taxonomy); if (is_array($section_column)) { foreach($section_column as $key => $section) { $edit_link = get_term_link($section,$section_taxonomy); $section_column[$key] = '<a href="'.$edit_link.'">' . $section->name . '</a>'; } echo implode(' | ',$section_column); } break; } } } // Output multiple taxonomy filters add_action('restrict_manage_posts' ,'restrict_manage_posts'); function restrict_manage_posts() { // Only display these taxonomy filters on desired custom post_type listings global $typenow; if ($typenow == 'blocks') { // Create an array of taxonomy slugs you want to filter by - if you want to retrieve all taxonomies, could use get_taxonomies() to build the list $filters = array('location', 'section'); foreach ($filters as $tax_slug) { // Retrieve the taxonomy object $tax_obj = get_taxonomy($tax_slug); $tax_name = $tax_obj->labels->name; // Retrieve array of term objects per taxonomy $terms = get_terms($tax_slug); // Output html for taxonomy dropdown filter echo "<select name='$tax_slug' id='$tax_slug' class='postform'>"; echo "<option value=''>Show All $tax_name</option>"; foreach ($terms as $term) { // Output each select option line, check against the last $_GET to show the current option selected echo '<option value='. $term->slug, $_GET[$tax_slug] == $term->slug ? ' selected="selected"' : '','>' . $term->name .' (' . $term->count .')</option>'; } echo "</select>"; } } } </code> Which argument I am missing?
|
Change line 93 from <code> add_filter('manage_posts_custom_column', 'manage_posts_custom_column'); </code> to <code> add_filter('manage_posts_custom_column', 'manage_posts_custom_column', 10, 2); </code> The fourth argument specifies how many arguments the function <code> manage_posts_custom_column </code> accepts (one by default). Codex: <code> add_filter() </code>
|
Getting the warning: Missing argument 2 for manage_posts_custom_column()?
|
wordpress
|
i'm trying to implement a custom post template for all posts filed under a specific category. I'm making use of WP-O-Matic plugin that puts in the RSS feeds in this category and would like to make a bit of customization for the branding on posts filed under this particular category. I found the below code from here: http://www.nathanrice.net/blog/wordpress-single-post-templates/ But when I add this to my functions.php I get a warning: Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$' in public_html/wp-content/themes/mytheme/functions.php(16) : runtime-created function on line 1 <code> add_filter( 'single_template', create_function( '$t', 'foreach( (array) get_the_category() as $cat ) { if ( file_exists(TEMPLATEPATH . "/single-{$cat->1176}.php") ) return TEMPLATEPATH . "/single-{$cat->1176}.php"; } return $t;' ) ); </code> Any idea on how to figure this out. P.S: I tried using a different approach where I made single.php as a doorway page to run a WP query. If category id matches then it renders custom-template.php else default-template.php As mentioned here . But I continue to get the following error: Parse error: syntax error, unexpected T_LNUMBER, expecting T_STRING or T_VARIABLE or '{' or '$' in public_html/wp-content/themes/mytheme/functions.php(16) : runtime-created function on line 1 Warning: call_user_func_array() [function.call-user-func-array]: First argument is expected to be a valid callback, '' was given in /public_html/wp-includes/plugin.php on line 166
|
<code> $cat->1176 </code> cannot be a property of an object. PHP Manual : A valid variable name starts with a letter or underscore, followed by any number of letters, numbers, or underscores. As a regular expression, it would be expressed thus: '[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*' Use <code> $cat->term_id </code> and compare it’s value with the number you’re out for. And … don’t use anonymous functions . They cannot be cached by opcode caches like APC and they are hard to debug – as you have seen. Plus, if someone wants to remove this filter in a child theme, that’s now very, very hard.
|
Using custom post template
|
wordpress
|
There any way to run a shortcut that is in a meta box? I'm trying to execute the shortcut but does nothing, is that if the code comes from the wordpress editor does not have any problem
|
use <code> do_shortcode() </code> on your meta box content: http://codex.wordpress.org/Function_Reference/do_shortcode
|
ShortCut on meta boxes
|
wordpress
|
I have been going crazy trying to google up what these globals are. What are allowedposttags and allowedtags? What is the difference between the two? Is there a list of all WP Globals and an explanation of what they are? For MCE Editor - to allow users not logged in to use lists and underline + strikethrough add following: <code> add_action('init', 'my_html_tags_code', 10); function my_html_tags_code() { global $allowedposttags, $allowedtags; //$allowedposttags["ol"] = array(); //$allowedposttags["ul"] = array(); $allowedtags["ol"] = array(); $allowedtags["ul"] = array(); $allowedtags["li"] = array(); $allowedtags["span"] = array( "style" => array() ); } </code>
|
These are arrays that are used by the wp_kses library. Basically they are white lists of html tags and attributes that WordPress allows in posts and comments. If memory serves correctly, "allowedposttags" is used for sanitizing post_content while "allowedtags" is used for comments.
|
What are allowedposttags and allowedtags?
|
wordpress
|
How do I create a random post but it shouldnt be change when the page is refreshed I want a random post that will last for a day and after 24 hours or a day, it will change randomly the post , will be that possible? or are there a plugin that exactly does that , actually what Im trying to create is like a "Random Tip For the Day", you know something like that I hope someone understand my question please help,any help will be appreciated.
|
Here is some code doing what you've asked and using the ideas others have highlighted: <code> <?php if ( false === ( $totd_trans_post_id = get_transient( 'totd_trans_post_id' ) ) ) { $args = array('numberposts' => 1, 'orderby' => 'rand'); $totd = get_posts($args); $midnight = strtotime('midnight +1 day'); $timenow = time(); $timetillmidnight = $midnight - $timenow; echo $midnight; echo ",".$timenow; set_transient('totd_trans_post_id', $totd[0]->ID, $timetillmidnight); } else { $args = array('post__in' => array($totd_trans_post_id)); $totd = get_posts($args); } foreach( $totd as $post ) : setup_postdata($post); ?> <div> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php the_content(); ?> </div> <?php endforeach; ?> </code> get_posts() help Plus the way I have coded it should make the Tip of the Day post change at midnight every day. This can be improved upon because we are showing random there is nothing stopping the same post showing twice in a row...
|
How do I create a random post that will last for a day
|
wordpress
|
I'm writing a theme where I'd like to give users the ability, via a theme option, to specify a typeface for their site with Google Web Fonts . If a user wants to embed a font like, say, News Cycle , then the code needs to specify this in two places, in a <code> <link> </code> tag within the <code> <head> </code> , and in the site's CSS. In the <code> <link> </code> tag, the font is specified with a <code> + </code> (plus sign) in the name: <code> <link href='http://fonts.googleapis.com/css?family=News+Cycle' rel='stylesheet' type='text/css'> </code> However, in the CSS, there is no plus sign: <code> h1 { font-family: 'News Cycle', arial, serif; } </code> Ideally I'd like users to just write or paste the name of the font into a form field, and then, in the code, to replace spaces with plus signs where needed. From googling around, I think this can be done with <code> str_replace </code> or another similar bit of PHP, but I'm a PHP novice. Can anyone shed some light on the best way to do this? At the moment the relevant PHP in my header.php looks a bit like this: <code> <?php $options = get_option('mytheme_theme_options'); if( isset( $options['webfont'] ) && ( !empty( $options['webfont'] ) ) ) printf( "WEBFONT LINK", $options['webfont'] ); ?> </code> Thanks.
|
Wouldn't a better solution be to build your own list of available fonts, and then let the user select which font to use? That way, your validation is much easier, and also, you have more control over how you use/implement the specific setting. In any case, you should be able to do what you want, within your sanitization callback, where you will (presumably) be ensuring that the input string is sanitized and validated (i.e. that the string actually corresponds to a Google web font name). Once you have "Valid Name" as the setting value, it is easy enough to do a <code> str_replace() </code> to replace " " with "+" . I would use two settings: <code> $themename_options['google-webfont-css'] </code> to hold the Font Family name (for CSS), and <code> $themename_options['google-webfont-link'] </code> to hold the link parameter. So: <code> $valid_input['google-webfont-css'] = // validated and sanitized $input['google-webfont-css']; $valid_input['google-webfont-link'] = str_replace( ' ', '+', $valid_input['google-webfont-css']; return $valid_input; </code> (This is inside your validation callback function.)
|
How to change a specific character in a theme option value - replace a space with a plus sign
|
wordpress
|
I'm setting up a simple WP install to host a friend's podcast, and looking into various podcasting plugins. I need something that makes it easy to upload a podcast, attach it to a post, and publish a feed I can provide to iTunes. Most of the buzz seems to indicate that PodPress and Blubrry PowerPress are the two best plugins to use for this, but I haven't found a good list of what one offers over the other. What are the strengths and weaknesses of these plugins? Are there any other great podcasting-related plugins I should be considering?
|
My opinion may not be totally fair, as I haven't tried both lately. But I used podpress for a while. THe problem was that every time WP did a major upgrade, podpress would quit working. I'm using podcastnig plugins for DJ music hosting on rvoodoo.com. Downtime sucks for my artists. So after about a year of having it break (once for many months) the powerpress plugin was offered. I jumped ship, which was easy as powerpress offers an importer for podpress content. PowerPress is huge and powerful. Numerous media players, category casting, etc. I have never had downtime with powerpress. Also, they are very active in development. Any questions Ive had have been oanswered on their forums. They are very open to suggestion too. So as a user who has relied on both for at least a year each, my vote is powerpress. I don't wanna knock podpress, I appreciate anyone making free plugins. And these big involved podcasting ones must take a fair bit of effort. Just one note, neither plugin makes uploading a podcast easier. You upload it yourself. And link to it from within the plugin. I use ftp, as my files are usually over 200M. Browser uploads are unstable at that size. BUt I just ftp the file into my pocast directory I made, and link it when I make a post.
|
Blubrry PowerPress vs. PodPress?
|
wordpress
|
I'm trying to test my wordpress page with some simple jQuery script but it won't work. I've loaded the script with <code> wp_enqueue_script('jquery'); </code> in <code> functions.php </code> as explained in the wordpress guide but something's buggy. I'm testing the page using <code> FireBug </code> installed in <code> Firefox 4 </code> and if I take a look to the loaded scripts list it's all ok, but it also return me the error <code> jQuery is not defined </code> too. I've followed the instructions on the <code> noConflict </code> mode but it still won't work for me: <code> // functions.php <?php function init_scripts () { if (!is_admin()) { wp_enqueue_script('jquery'); } } add_action('init', 'init_scripts'); ?> // header.php <script type="text/javascript"> (function($) { $(document).ready(function() { alert('hello?'); }); }(jQuery)); </script> </code> Where I'm wrong? I've tried this tutorial too and it's says jQuery object is not defined here: <code> // jquery from ajax.googleapis.com is correctly loaded $j=jQuery.noConflict(); // firebug says jQuery is not defined by here $j(document).ready(function(){ alert('test'); }); </code>
|
jQuery needs to be outside the wrapper like so: <code> <script type="text/javascript"> (function($) { $(document).ready(function() { alert('hello?'); }); })(jQuery); </script> </code> Edit: A better way would be: <code> jQuery(document).ready(function($) { // $() will work as an alias for jQuery() inside of this function }); </code> Also make sure any inline script tags are AFTER your call to <code> wp_head(); </code> And even better way: Instead of adding your script tags inline create a functions.js file containing all your extra functions etc. Enqueue it with jQuery as a dependency. <code> add_action( 'template_redirect', 'c3m_enqueue_scripts' ); function c3m_enqueue_scripts() { wp_register_script( 'custom-functions', TEMPLATEPATH .'/path/to/functions.js', array( 'jquery' ) TRUE); wp_enqueue_script( 'jquery' ); wp_enqueue_script( 'custom-functions' ); } </code>
|
Firebug says jQuery is loaded but $() and jQuery() are not defined
|
wordpress
|
is it possible to change the author base slug in dependency of the role? For example, authors get example.com/ninja/%username% and subscribers get example.com/trainee/%username% ? I am thinking of something like: <code> add_action('init', 'set_new_author_base'); function set_new_author_base() { global $wp_rewrite; if($user->role == 'subscriber') $author_slug = 'trainee'; $wp_rewrite->author_base = $author_slug; } elseif($user->role == 'author') { $author_slug = 'ninja'; $wp_rewrite->author_base = $author_slug; } } </code> But I am a little bit desperate because of the if-line. It should work vor unregistered visitors if they browse the site and see the author links, it should work for the logged in authors and subscriber themselves.... I really appreciate any help!
|
In your example, the author rewrite pattern changes from <code> /author/[authorname]/ </code> to <code> /[author_level]/[author_name]/ </code> . If we allow <code> [author_level] </code> to be anything, we will get into conflict with the rules for pages, because <code> /[anything]/[anything]/ </code> can be either an author archive or a regular subpage. For this reason, my solution assumes you have a limited number of author levels, so we can explicitly put them in the rewrite rules. So <code> /ninja/[anything]/ </code> will be an author archive, but <code> /not-ninja/[anything]/ </code> will be a regular page. Changing the URL structure always consists of two parts: changing the URLs that WordPress will accept and changing the URLs that WordPress will generate. First we will change the URLs that WordPress will accept by introducing a new rewrite tag and setting our author base to that tag. <code> // I assume you define these somewhere, this is just to make the example work $wpse17106_author_levels = array( 'trainee', 'ninja' ); add_action( 'init', 'wpse17106_init' ); function wpse17106_init() { global $wp_rewrite; $author_levels = $GLOBALS['wpse17106_author_levels']; // Define the tag and use it in the rewrite rule add_rewrite_tag( '%author_level%', '(' . implode( '|', $author_levels ) . ')' ); $wp_rewrite->author_base = '%author_level%'; } </code> If you check the resulting rewrite rules with stackexchange-url ("my Rewrite Analyzer") you will notice that it contains extra rules for the plain <code> /[author-level]/ </code> pages. This happens because WordPress generates rules for each directory part that contains a rewrite tag, like <code> %author_level% </code> . We don't need these, so filter out all author rewrite rules that don't contain an <code> author_name </code> : <code> add_filter( 'author_rewrite_rules', 'wpse17106_author_rewrite_rules' ); function wpse17106_author_rewrite_rules( $author_rewrite_rules ) { foreach ( $author_rewrite_rules as $pattern => $substitution ) { if ( FALSE === strpos( $substitution, 'author_name' ) ) { unset( $author_rewrite_rules[$pattern] ); } } return $author_rewrite_rules; } </code> Now WordPress should accept URLs using this new pattern. The only thing left to do is change the URLs it generates when it creates a link to an author archive. For that you can hook into the <code> author_link </code> filter, like this very basic example: <code> add_filter( 'author_link', 'wpse17106_author_link', 10, 2 ); function wpse17106_author_link( $link, $author_id ) { if ( 1 == $author_id ) { $author_level = 'ninja'; } else { $author_level = 'trainee'; } $link = str_replace( '%author_level%', $author_levels, $link ); return $link; } </code>
|
Change Author Base Slug for different Roles
|
wordpress
|
Is there a help desk solution plugin (free or paid) for Wordpress? Ideally a visitor would be able to create a ticket from the WP site and the admin would see it via email and in the admin portal of WP. Also offer the option for invoicing per ticket. Edit: The plugin has to play well with my theme without having to alter anything with the exception of adding shortcodes for the helpdesk
|
I have been looking at the WordPress Advanced Ticket System plugin . The free version has an admin interface to submit tickets but front end ticket submission requires the paid version .
|
HelpDesk solution for Wordpress
|
wordpress
|
In the Admin section I'm using quesry posts to get the title and content of a custom post this query_posts('post_type=sfnewsletter'); will get me the content I need but unfortunately what I need to do now is to pass the ID of the custom post via a form and then retrieve that content I've tried <code> query_posts('p=32'); query_posts('page_id=32'); query_posts('page=32'); query_posts('sfnewsletter_id=32'); </code> And not only do I not get the right custom post some of them return a post with an ID of 14 (not the first or last post) I have confirmed that 32 is the correct ID for the custom post I am trying to get. THIS IS THE FORM It passes the ID correctly <code> <form method="post" action="<?php echo sfn_form_url(); ?>" > <table class="form-table"> <tr valign="top"><th scope="row"><?php _e( 'To', 'sfnewsletter' ); ?></th> <td> <select name="sfnewsletter_to" id="sfnewsletter_to"> <option value="0">Please Choose</option> <?php wp_dropdown_roles() ?> </select> </td> </tr> <tr valign="top"><th scope="row"><?php _e( 'Newsletter', 'sfnewsletter' ); ?></th> <td> <select name="sfnewsletter_newsletter" id="sfnewsletter_newsletter"> <option value="0">Please Choose</option> <?php query_posts('post_type=sfnewsletter'); if (have_posts()) : while (have_posts()) : the_post(); echo '<option value="' .get_the_ID(). '">' .get_the_title(). '</option>'; endwhile; endif; ?> </select> </td> </tr> </table> <p class="submit"> <input id="sfnewsletter_hidden" class="regular-text" type="hidden" name="sfnewsletter_hidden" value="<?php esc_attr_e( 'SEND' ); ?>" /> <input type="submit" class="button-primary" value="<?php _e( 'Send Message', 'sfnewsletter' ); ?>" /> </p> </form> </code> THIS IS THE SOLUTION I CAME UP WITH. THE ANSWER I HAVE ACCEPTED THE RIGHT WAY TO DO IT THOUGH, MY WAY IS A FUDGE ok, I have come up with a work around that suits my situation. Since I don't seem to be able to use my custom post ID in the query I have used the ID from the form and converted it into the permalink and then used that in the query like so <code> $sfnewsletter_slug = basename( get_permalink($sfnewsletter_newsletter) ); $the_query = new WP_Query( array( 'post_type' =>'sfnewsletter', 'posts_per_page'=>1, 'name'=>$sfnewsletter_slug ) ); </code> This gives me the output I am looking for.
|
<code> query_posts('post_type=sfnewsletter&p=32'); </code>
|
What is the ID parameter for custom post types in query_posts?
|
wordpress
|
I am using the Custom Post Type feature in Wordpress 3 to create an Events section for my website. I am able to get this to display by using the relevante template files, but I also want the event listings visible on other pages. I've done this with the normal post types but these are based on category IDs which Custom Post Types don't have. Each event has a taxonomy for country and I want to be able to loop through the events and display only events for specific countries so I want to be able to filter that. I've had a look on the Codex and came up with the following but it doesn't display anything: <code> <?php $args = array( 'post_type'=> 'events', 'country' => 'england' ); $the_query = new WP_Query( $args ); if ( $the_query->have_posts() ) : // The Loop while ( $the_query->have_posts() ) : $the_query->the_post(); echo '<li>'; the_title(); echo '</li>'; endwhile; endif; // Reset Post Data wp_reset_postdata(); ?> </code>
|
I've figured out the answer using the Wordpress forum. Solution below: <code> <?php query_posts( array( 'country' => 'event-england' ) ); ?> <?php if( is_tax() ) { global $wp_query; $term = $wp_query->get_queried_object(); $title = $term->name; } ?> <ul> <span class="tax-title"><?php echo($title); ?></span> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a><?php the_excerpt() ?></li> <?php endwhile; else: ?> <?php endif; ?> </ul> </code>
|
Loop for custom post types filtered by a taxonomy
|
wordpress
|
I want to have a login username and password field in the header, and a registration link beside it. I want the registration link to go away once the user is logged in and the login fields to be replace with a logout link. I have found these two snippets but they don't help me achieve what I want.
|
<code> wp_login_form(); // Codex: http://codex.wordpress.org/Function_Reference/wp_login_form // or: wp_loginout(); // Codex: http://codex.wordpress.org/Function_Reference/wp_loginout if ( ! is_user_logged_in() ) // Codex: http://codex.wordpress.org/Function_Reference/is_user_logged_in wp_register('', ''); // Codex: http://codex.wordpress.org/Function_Reference/wp_register </code>
|
How do I add Login fields and registration link to the header?
|
wordpress
|
Is there someway to change the title in wp-admin? Been looking all over google but no one seem to mention it. I simply want to get rid of "— WordPress" and possibly change the "‹" into some other symbol. Any ideas?
|
<code> add_filter('admin_title', 'my_admin_title', 10, 2); function my_admin_title($admin_title, $title) { return get_bloginfo('name').' &bull; '.$title; } </code> You could also do a <code> str_replace </code> on <code> $admin_title </code> to remove "— WordPress" and change "‹". Look at the top of the <code> wp-admin/admin-header.php </code> file to see what is going on by default.
|
Change page title in admin area
|
wordpress
|
I am working on a custom theme where there is option to upload images . I have certain check-boxes in the form which the users select as per where the image has to go. My form code is as follows : <code> <input type="checkbox" class="input" name="vtype[]" value="3"/> <input type="checkbox" class="input" name="vtype[]" value="4" /> <input type="checkbox" class="input" name="vtype[]" value="5" /> <input type="checkbox" class="input" name="vtype[]" value="6" /> </code> function for using the values is : <code> $image_category = implode(',', $_POST['vtype']); </code> if i echo this then the result is fine e.g. 3,4,5 . but if i try to use this value to insert values in database then the value is updated in only the 1st category and nothing happens for the remaining. main function is inserting values in database is : <code> $post = array( 'ID' => '', 'post_author' => $image_author, 'post_category' => array($image_category), 'post_content' => $image_to_attach, 'post_title' => $image_title, 'post_status' => 'publish' ); } // Insert the values in DB $id = wp_insert_post($post); </code>
|
Currently you are passing on this value: <code> 'post_category' => array('3,4,5') // This is a single string </code> While you should be doing this: <code> 'post_category' => array(3,4,5) // Three separate values </code> Don't forget to sanitize the POST values neither: <code> // Initialize categories $post_category = array(); // Prevent "undefined variable" error notices if (isset($_POST['vtype'])) { // Loop over selected categories foreach ((array) $_POST['vtype'] as $vtype) { // Validate vtype (only numbers allowed) if (ctype_digit((string) $vtype)) { // Add category $post_category[] = (int) $vtype; } } } // Save the post with $post_category in database as you did before... </code> You can shorten this whole block to a oneliner as well, if you like. Just for fun: <code> $post_category = (isset($_POST['vtype'])) ? array_filter((array) $_POST['vtype'], 'ctype_digit') : array(); </code>
|
How to use multiple check-box values to work in a function and insert values in database
|
wordpress
|
I'm contemplating a widget with quite a number of options, which will make for a lengthy widget form. To improve the user experience with this form, I'd like to divide it into sections. I don't feel like re-inventing the wheel, so what are some examples of widgets that have fairly complex forms (especially those which are divided into multiple sections) all the while remaining usable and easy to parse visually ? I should add that I'm looking for examples that could be considered "best practices", not messy kitchen sink forms that are difficult to use . I realize this is probably subjective. Thanks for your input!
|
How about native Thickbox with the native jQuery tabs for example: the widget it self is simple and only has a link but one you click on it the thickbox pops up and shows all of the options grouped by tabs: let me know what you think I'll fetch the code for you.
|
Complex widget form UI - examples and best practices
|
wordpress
|
I'm using a little function below to list out the post_terms. The function is outputting very specific markup for the grouping, filter, and href attributes (this is a term selector for the jQuery isotope plugin). <code> $terms = get_terms("post_tag"); $count = count($terms); if($count > 0){ echo '<div class="option-combo tag">'; echo '<h4>Post Tags</h4>'; echo '<ul class="filter option-set floated clearfix">'; echo '<li><a href="#filter-tag-any" data=filter="" data-group="tag" class="selected">any</a>'; foreach ($terms as $term) { echo '<li><a href="#filter-tag-'.$term->slug.'" data-group="tag" data-filter=".tag-'.$term->slug.'">'.$term->name.'</a>'; } echo '</ul>'; echo '</div>'; } </code> Question: Given the requirements above where each term has it's own custom href, data-group, data-filter, how would I go about changing this list format into a tag cloud with my requirements? (an ordered list of terms is way to long for use within a sidebar, hence a tag cloud would work much better when using terms as a selector) I did look through the codex, but didn't see any examples on how to modify the output of the tag cloud. thanks
|
This is how the links are created in <code> wp_generate_tag_cloud </code> (wp-includes/category-template.php) <code> foreach ( $tags as $key => $tag ) { $count = $counts[ $key ]; $real_count = $real_counts[ $key ]; $tag_link = '#' != $tag->link ? esc_url( $tag->link ) : '#'; $tag_id = isset($tags[ $key ]->id) ? $tags[ $key ]->id : $key; $tag_name = $tags[ $key ]->name; $a[] = "<a href='$tag_link' class='tag-link-$tag_id' title='" . esc_attr( call_user_func( $topic_count_text_callback, $real_count ) ) . "' style='font-size: " . ( $smallest + ( ( $count - $min_count ) * $font_step ) ) . "$unit;'>$tag_name</a>"; } </code> There seems not to be a way to do what you need. Maybe copying all <code> wp_generate_tag_cloud </code> and modifying it to your needs in your functions.php?
|
Customizing the wordpress tag-cloud output
|
wordpress
|
What is the difference between custom taxonomies and page templates and custom post types? I think I understand that taxonomy is used to organize data. CPTs are used to give your data a different design. but can't a template be used instead of CPT? or are they used in combination? and can't categories be used instead of creating additional taxonomies? i guess are CPT's and custom taxonomies just tools to make life easier or do they serve a purpose that could not be achieved without them? I have been creating new templates for any page the needs a different look or any page that uses a specific category. have i been doing this wrong or poorly? instead of having 7 templates should i have 7 CPT's or something like that?
|
Taxonomies are categorizations of data. Tags are a taxonomy. Categories are another taxonomy. If you are building a movie website and want to show which actors starred in which movie, "Movies" would be a custom taxonomy. Custom Post Types are really just custom data items. They're stored just like posts and pages, but aren't considered the same thing as a post or a page. In the movie website example above, "Actor" might be a custom post type with a Name, a Biography, and a Headshot as elements. Custom Page Templates are special files for WordPress that dictate how the content will be laid out on the page. They're used strictly with pages in WordPress, not with posts or custom post types. Think of it this way: Types of Data: Posts Pages Menus (yes, these are a custom post type) Custom Post Types Ways to Structure and Relate Data: Tags Categories Post Formats Custom Taxonomies Ways to Present Data: Custom Page Template
|
What are the differences between custom post type and custom page templates?
|
wordpress
|
Error message below: Warning: Cannot modify header information - headers already sent by (output started at /home/content/79/7603579/html/listings/wp-content/themes/OIB theme/functions.php:519) in /home/content/79/7603579/html/listings/wp-includes/pluggable.php on line 897 EDIT: Code around <code> functions.php </code> line 519: <code> <small><?php echo $value['desc']; ?></small> <div class="clearfix"></div> </div> <?php break; case "section": $i++; ?> <div class="rm_section"> <div class="rm_title"> <h3><img src="<?php bloginfo('template_directory')?>/functions/images/trans.gif" class="inactive" alt="""><?php echo $value['name']; ?></h3> <span class="submit"> <input name="save<?php echo $i; ?>" type="submit" value="Save changes" /> </span> <div class="clearfix"></div> </div> <div class="rm_options"> <?php break; } } ?> </code> And the fix, per comment below, removed this code: <code> function cpt_Search_category_Filter($query) { $post_type = array('post','business_sold'); if ($query->is_search || $query->is_category) { $query->set('post_type', $post_type); }; return $query; }; add_filter('pre_get_posts','cpt_Search_category_Filter'); </code>
|
Your <code> functions.php </code> file is outputting instead of returning something, on line 519. Can you post whatever code/functions are around Line 519? EDIT: You have a syntax error in your <code> cpt_Search_category_Filter() </code> function. You have a couple stray semi-colons after closing braces. Change this: <code> function cpt_Search_category_Filter($query) { $post_type = array('post','business_sold'); if ($query->is_search || $query->is_category) { $query->set('post_type', $post_type); }; return $query; }; add_filter('pre_get_posts','cpt_Search_category_Filter'); </code> to this: <code> function cpt_Search_category_Filter($query) { $post_type = array('post','business_sold'); if ($query->is_search || $query->is_category) { $query->set('post_type', $post_type); } return $query; } add_filter('pre_get_posts','cpt_Search_category_Filter'); </code>
|
Error messages when adding code to function.php or trying to delete inactive plugin files
|
wordpress
|
So what I want to do is too have a function similar to a category or tag, but a little more robust. It's for a podcast to list of guests for each episode . Ideally this would do a few things: Guest Data For each guest (added to an episode), display their: name, photo, twitter id, url. Guest Page Clicking on their photo or name would the visitor to a page like the authors page , where more info on that guest could be stored: a short bio, all the episodes that guest has appeared on, etc... Meta Box on pod cast edit screen: The management of this would ideally be managed like categories are now, through checkboxes and names listed on the write page to select from. Further management, (adding bio, photos, ect) would be done in another panel like posts are. My first thought was custom post types or custom taxonomies, but I'm not sure which method is more feasible. Any ideas? Thanks.
|
So what I did was make a custom post type for guests profiles, and use "posts 2 posts" to connect them to specific episodes. The plugin has functions to both list the connected guests on episode pages, and list all episodes associated with that guest on their profile pages. http://wordpress.org/extend/plugins/posts-to-posts/
|
Podcast Guest List
|
wordpress
|
I used the Custom Post UI plugin to create a custom post type called 'business_sold'. I assigned each custom post to one of six categories and an additional one called 'All'. I used a standard WP widgetized menu to list the 'Business Sold' categories, but my custom posts are not called on a search of any category. I can see that WP has recognized the category assignment. Single-business_sold.php is working fine, but neither category-business_sold or archive-business_sold are working. I cannot figure out what I'm doing wrong. Can anyone help me please?
|
Category archive by default it search for posts and not your custom type, you need to tell WordPress to search for your custom type, paste this code in your theme's functions.php file: <code> function cpt_Search_category_Filter($query) { $post_type = array('post','business_sold'); if ($query->is_search || $query->is_category) { $query->set('post_type', $post_type); }; return $query; }; add_filter('pre_get_posts','cpt_Search_category_Filter'); </code> and you should be fine.
|
My custom posts that are assigned to categories, are not called on a category search using a Category Menu
|
wordpress
|
I need to add multiple css files from a css framework to my editor-style.css file. The point is that i don't want to update the editor-style.css file anytime there's a new update from either my theme or the css framework. Is there a filter or hook to add more than one stylesheet ? (I'm aware of <code> @import </code> , but didnt try to use it here.)
|
<code> add_editor_style( $stylesheet ); </code> http://codex.wordpress.org/Function_Reference/add_editor_style
|
Is there a filter for editor-style.css file?
|
wordpress
|
Ok so i am trying to use WordPress's custom fields and have them working but now i have some php code i need help with. <code> <a href="<?php echo get_post_meta( $post->ID, '_ct_text_4dc9e9f74d000', true ); ?>">Go To Store!</a> </code> The above code is what i have for right now. Is there a way to setup a if and else statement so if there is a value in the custom field then show that but else show N/A if there is no value present
|
You mean something like this? <code> $customhref = get_post_meta( $post->ID, '_ct_text_4dc9e9f74d000', true ); if ( $customhref ) { ?> <a href="<?php echo $customhref; ?>">Go To Store!</a> <?php } else { echo 'N/A'; } </code>
|
Custom Field IF/ELSE PHP
|
wordpress
|
I recently upgraded WordPress from 3.0.x to 3.1.2. I had set it up to use custom post types before the upgrade. I need make a list of events that are occurring that started in the past until they occur. For example, if an event started today at Noon, it should show up in this list until it ends, which could be tomorrow at 6:00 PM. Can someone tell me how to modify this query so it will get custom posts that occur between the start and end date (multiple keys)? <code> $args = array ('post_type' => 'events', 'meta_key' => 'end_date_value', 'meta_compare' => '>', 'meta_value' => $current_time, 'orderby' => 'meta_value', 'order' => 'ASC' ); </code>
|
Here is example from Codex on using <code> BETWEEN </code> with new format of meta query, which covers multiple fields as well: <code> $args = array( 'post_type' => 'product', 'meta_query' => array( array( 'key' => 'color', 'value' => 'blue', 'compare' => 'NOT LIKE' ), array( 'key' => 'price', 'value' => array( 20, 100 ), 'type' => 'numeric', 'compare' => 'BETWEEN' ) ) ); $query = new WP_Query( $args ); </code> See Custom Field Parameters for details.
|
How to query custom post types with multiple keys?
|
wordpress
|
I'm finding that if I have errors in my code that's being called by my custom widget's form() method, I don't see any error display - the only indication I have is that in Admin > Appearance > Widgets the sidebars are all gone. What can be done to: a) avoid completely destroying all sidebars in Admin whenever your code has an error b) get more information about what is causing the error or exception?
|
Since the question was asked in May, the WP core team released the Admin Debug Bar , and its ancillary plugin Debug Bar Console is exactly the balm to ease any WP Programmer's pain.
|
Debugging / displaying errors in WP_Widget-> form()
|
wordpress
|
i want to show the syntaxis in some posts about how to run a shortcode, I mean, something like this [myshortcode] but without running it, is that possible?
|
If you use double brackets, WordPress will not execute the shortcode but just display it with single brackets. So <code> [[gallery]] </code> becomes [gallery] in your post.
|
how to show the syntaxis of a shortcode
|
wordpress
|
any suggestions on how to get rid of ul tag wrapped around li tags in custom menu here at http://www.blueoceanportfolios.com/careers/ the custom menu is outputted with nested tags around like <code> <ul id="menu-home" class="navLeft"><li><a href="http://www.blueoceanportfolios.com/careers/">Home</a></li> <li><a href="http://www.blueoceanportfolios.com/careers/?page_id=18">About</a></li> </ul> </code> I am trying to take out the tags and already passed the container => false parameter before outputting custom menu as mentioned at wordpress codex, below is code again. <code> $args = array( 'menu' => 'home_menu', // 'sort_column' => '', 'container' => 'false', //'container_id'=>'myID', 'menu_class' => 'navLeft', 'walker' => new my_walker() ); wp_nav_menu( $args ); </code>
|
The <code> container </code> argument controls what is one level higher - around <code> <ul> </code> . What you need is <code> items_wrap </code> argument that controls the list wrap and defaults to <code> <ul id="%1$s" class="%2$s">%3$s</ul> </code> . Removing the ul wrap in Codex gives following example: <code> wp_nav_menu( array( 'items_wrap' => '%3$s' ) ); </code>
|
removing the list container from the custom menu output
|
wordpress
|
I'm new to SQL and am wondering if I need to use <code> wpdb->prepare </code> for the following query to a table I've created <code> global $wpdb; $tablename = $wpdb->prefix . "my_custom_table"; $sql = "SELECT * FROM " . $tablename . " ORDER BY date_created DESC"; $resulst = $wpdb->get_results( $sql , ARRAY_A ); </code> Do I need to use <code> prepare </code> here? How would I do that? Cheers
|
Its best practice to always use <code> prepare </code> but the main use of it is to prevent against SQL injection attacks, and since there is no input from the users/visitors or they can't effect the query then that is not an issue in your current example. but like i said before its best practice to use it and once you start using it you never stop , so in your example you can use it like so: <code> global $wpdb; $tablename = $wpdb->prefix . "my_custom_table"; $sql = $wpdb->prepare( "SELECT * FROM %s ORDER BY date_created DESC",$tablename ); $resulst = $wpdb->get_results( $sql , ARRAY_A ); </code> to read more about how to use it head to the codex
|
Should I use wpdb prepare?
|
wordpress
|
I'm using get_pages() function to get all subpages from a page like this: <code> $childrens = get_pages(array('child_of' => 7, 'sort_column' => 'post_date', 'sort_order' => 'DESC', 'depth' => -1)); </code> This is supossed to get me a list of all pages (no matter if direct children, children of children, etc) orderen by the date they were created, but instead its showing me the list of pages in a strange order, here's the output when I run a foreach on the $childrens array and output the post_date on each: <code> 2011-05-10 15:37:03 2011-05-10 15:35:59 2011-05-10 15:01:18 2011-05-10 17:12:32 2011-05-10 15:00:47 2011-05-10 14:00:14 2011-05-11 04:19:08 2011-05-10 23:52:54 2011-05-10 15:20:12 2011-05-10 15:05:10 </code> As you can see they're not ordered by date descending, I tried using other options in the sort_column key but none seemed to e working correctly, does anyone know what could be wrong? Thanks in advance!
|
after looking around a bit I managed it to make it work using the following: <code> function sort_pages_by_date($a, $b){ if ($a->post_date == $b->post_date) return 0; if ($a->post_date < $b->post_date) return -1; return 1; } function get_filtered_news($pages) { usort($pages, 'sort_pages_by_date'); rsort($pages); return $output; } add_filter('get_pages', 'get_filtered_news'); </code> I'm using the usort function to sort the array by the objects' date, and the reversing it to get it ordered from newest to oldest, thanks all for pointing me in the right direction I voted all you guys up.
|
get_pages() not ordering as it should
|
wordpress
|
I wish to create a podcast directory site. For which, I'd like the users of my site to be able to upload audio files which are "large" (e.g: more then 2 or 8 MB), and to make that upload "easily" go to the correct field in a relevant plugin (such as "podcasting") Any suggestions will be welcomed.
|
Just to add to what other have said, beyond changing your php.ini settings, upload size is limited mainly by the browser/connection. There are more reliable browser bases solutions that use java/flash or a combination of tech that allow for uploads reliably up to 100MB. http://www.plupload.com/ http://www.swfupload.org/ http://www.uploadify.com/ http://jumploader.com/
|
Creating a podcast directory site - how to allow user to upload "large" files?
|
wordpress
|
I am using the members plugin and have a custom post type of "listing" When I navigate to listings in the backend, I can edit. quickedit, and view. There is no option to trash. I am logged in as the admin. <code> add_action('init', 'listing_init'); function listing_init() { $labels = array( 'name' => _x('Listing', 'post type general name'), 'singular_name' => _x('Listing', 'post type singular name'), 'add_new' => _x('Add New', 'Listing'), 'add_new_item' => __('Add New Listing'), 'edit_item' => __('Edit Listing'), 'new_item' => __('New Listing'), 'view_item' => __('View Listing'), 'search_items' => __('Search Listing'), 'not_found' => __('No Listing found'), 'not_found_in_trash' => __('No Listing found in Trash'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'show_ui_menu' => true, 'query_var' => true, 'rewrite' => true, 'capability_type' => 'listing', 'map_meta_cap' => true, 'hierarchical' => false, 'menu_position' => 5, 'supports' => array('title','editor','thumbnail'), 'taxonomies' => array('category') ); register_post_type('listing',$args); } </code> this is the functions.php custom post type code that I am using. Everything else works great. Inside the members plugin I have roles for delete_listing and delete_listings (which I think is not necessary) Any ideas on what I am doing wrong here?
|
Might you need one of these Admin capabilities ? delete_others_pages delete_others_posts delete_pages delete_plugins delete_posts delete_private_pages delete_private_posts delete_published_pages delete_published_posts Unless you've modified the default capabilities for Administrator, to remove one or more of these capabilities, you should be able to delete any Post (of any Post-Type) as an Admin user.
|
How do I "trash" a custom post type post while logged in as Admin
|
wordpress
|
On the site I'm currently developing I am using 'Custom Post Type UI' to manage my custom post types. Within this I can manage the description for any of the new custom post types that I have created. How would I go about editing the description of the default 'posts' post type? I am outputting this description under the heading in each section. Thanks!
|
you can use <code> global $wp_post_types </code> to edit the description for example: <code> add_action('init' , 'edit_post_description'); function edit_post_description(){ global $wp_post_types; $wp_post_types['post'] ->description = 'type your description here...'; } </code>
|
Post Type Description for 'Posts'
|
wordpress
|
I've created a custom sidebar with this code in my theme's functions.php: <code> register_sidebar(array( 'name' => __('Article - Below Content'), 'id' => 'zg-article-footer', 'description' => 'Use this sidebar to place widgets that will appear directly underneath the Article' )); </code> When I navigate to Appearance > Widgets in my Admin, this sidebar is always the first one on the top of my list of sidebars, and it's always "open" (that is, you can see the description and the list of widgets attached to it). None of my other sidebars are open, and WP Admin doesn't seem to remember my last-opened sidebar. Is there an argument I should use when registering the sidebar that will tell it to default to closed? Or is there an option somewhere else entirely?
|
This is default behavior. I believe that sidebars are listed by ID in <code> Dashboard -> Appearance -> Widgets </code> , and that the sidebar with ID <code> 0 </code> is always open in the default view.
|
Why is my custom sidebar always open on the widgets screen in Admin?
|
wordpress
|
I'd like to count the number of posts created for every category, so: <code> 12 Works (12 posts in works category) 36 Pictures (36 posts in pictures category) 17 Furnitures (17 posts in furnitures category) </code> How can I do that?
|
You can use wp_list_categories() function and set show_count to 1 (true) http://codex.wordpress.org/Template_Tags/wp_list_categories
|
Count the posts number for every category
|
wordpress
|
Thanks to stackexchange-url ("Otto")'s excellent post on advanced taxonomy queries , I (mostly) understand how to create multi-taxonomy and multi-term queries. However, what I don't know is how to build those dynamically based on user input. I'd really like to end up with something like Amazon.com has on their site, with check boxes next to the various terms for a taxonomy in the sidebar (and multiple lists of terms, each with a taxonomy heading). Something like this: How should I go about building something like this? Displaying the content dynamically (content changes when a box is checked) would be great, but I'd certainly settle for having a "submit" button.
|
I am a little fuzzy on specifics of technical side, but I think general outline would be following: Interface - you will need to either submit this as form by button or JavaScript. Query variables - you will need to register custom variable(s) via <code> query_vars </code> filter so your custom data is not discarded from URL. Query - modify query to make complex query, using custom data submitted.
|
How to build a multi-taxonomy, multi-term query based on user input
|
wordpress
|
The title pretty much says what I'm trying to accomplish, but more specifically I have a plugin that I made and it creates a custom post type, lets call them <code> newpages </code> . On these pages I have used <code> template_redirect </code> to take over the design of the pages, but some plugins appear, but I don't want to remove all of the plugins from loading, just a couple. So I was wondering if it's possible to use something like custom fields to disable certain plugins on a per-post basis. Can anybody point me in the right direction? Thanks!
|
I don't see why not. Hook to <code> template_redirect </code> (you already did). Conditionals should work at this point, so use <code> is_single() </code> / <code> is_singular() </code> / etc to check for what you need. Use <code> remove_action() </code> / <code> remove_filter() </code> to unhook unwanted functionality.
|
Disable Individual Plugins (specifically in Custom Post Types) on a per-post basis?
|
wordpress
|
Mike Schindel provided me this code long time ago: <code> <?php /** * Create the Blocks custom post type and the Sections custom taxonomy */ add_action('init', 'my_init_method'); if (!class_exists('YourSite_Blocks')) { class YourSite_Blocks { static function on_load() { add_action('init',array(__CLASS__,'init')); add_filter('manage_blocks_posts_columns', array(__CLASS__,'manage_blocks_posts_columns')); add_filter('manage_posts_custom_column', array(__CLASS__,'manage_posts_custom_column'),10,2); add_action('restrict_manage_posts', array(__CLASS__,'restrict_manage_posts')); } // Register custom post types and custom taxonomies static function init() { register_post_type('blocks',array( 'labels' => array( 'name' => __( 'Blocks' ), 'singular_name' => __( 'Block' ), 'add_new_item' => 'Add New Block', 'edit_item' => 'Edit Block', 'new_item' => 'New Block', 'search_items' => 'Search Block', 'not_found' => 'No Blocks found', 'not_found_in_trash' => 'No Blocks found in trash', ), 'public' => true, 'hierarchical' => false, 'taxonomies' => array( 'section'), 'supports' => array('title','editor','thumbnail','custom-fields'), 'rewrite' => array('slug'=>'blocks','with_front'=>false), 'menu_position' => 50, )); register_taxonomy('location','blocks',array( 'hierarchical' => true, 'labels' => array( 'name' => __( 'Locations' ), 'singular_name' => __( 'Location' ), 'add_new_item' => 'Add New Location', 'edit_item' => 'Edit Location', 'new_item' => 'New Location', 'search_items' => 'Search Location', 'not_found' => 'No Location found', 'not_found_in_trash' => 'No Locations found in trash', 'all_items' => __( 'All Locations' ), ), 'query_var' => true, 'rewrite' => array( 'slug' => 'location' ), )); register_taxonomy('section','blocks',array( 'hierarchical' => true, 'labels' => array( 'name' => __( 'Sections' ), 'singular_name' => __( 'Section' ), 'add_new_item' => 'Add New Section', 'edit_item' => 'Edit Section', 'new_item' => 'New Section', 'search_items' => 'Search Section', 'not_found' => 'No Sections found', 'not_found_in_trash' => 'No Sectionss found in trash', 'all_items' => __( 'All Sections' ), ), 'query_var' => true, 'rewrite' => array( 'slug' => 'section' ), )); // Add initial terms if (!get_option('yoursite-blocks-initialized')) { $terms = array( 'Intro', 'Tagline', 'Mainbar', 'Sidebar', 'Featured', 'Content', ); foreach($terms as $term) { if (!get_term_by('name',$term,'section')) { wp_insert_term($term, 'section'); } } update_option('yoursite-blocks-initialized',true); } } // Arrange the position of elements in the table function manage_blocks_posts_columns($columns) { $columns = array( 'cb' => '<input type="checkbox" />', 'title' => 'Name', 'location_column' => 'Location', 'section_column' => 'Section', 'author' => 'Author', 'date' => 'Date', ); return $columns; } // Verify that we are indeed working with only the custom post type and use a switch statement to test against the column function manage_posts_custom_column( $column,$post_id ) { global $typenow; if ($typenow=='blocks') { $location_taxonomy = 'location'; $section_taxonomy = 'section'; switch ($column) { case 'location_column': $location_column = get_the_terms($post_id,$location_taxonomy); if (is_array($location_column)) { foreach($location_column as $key => $location) { $edit_link = get_term_link($location,$location_taxonomy); $location_column[$key] = '<a href="'.$edit_link.'">' . $location->name . '</a>'; } echo implode(' | ',$location_column); } break; case 'section_column': $section_column = get_the_terms($post_id,$section_taxonomy); if (is_array($section_column)) { foreach($section_column as $key => $section) { $edit_link = get_term_link($section,$section_taxonomy); $section_column[$key] = '<a href="'.$edit_link.'">' . $section->name . '</a>'; } echo implode(' | ',$section_column); } break; } } } // Output multiple taxonomy filters function restrict_manage_posts() { // Only display these taxonomy filters on desired custom post_type listings global $typenow; if ($typenow == 'blocks') { // Create an array of taxonomy slugs you want to filter by - if you want to retrieve all taxonomies, could use get_taxonomies() to build the list $filters = array('location', 'section'); foreach ($filters as $tax_slug) { // Retrieve the taxonomy object $tax_obj = get_taxonomy($tax_slug); $tax_name = $tax_obj->labels->name; // Retrieve array of term objects per taxonomy $terms = get_terms($tax_slug); // Output html for taxonomy dropdown filter echo "<select name='$tax_slug' id='$tax_slug' class='postform'>"; echo "<option value=''>Show All $tax_name</option>"; foreach ($terms as $term) { // Output each select option line, check against the last $_GET to show the current option selected echo '<option value='. $term->slug, $_GET[$tax_slug] == $term->slug ? ' selected="selected"' : '','>' . $term->name .' (' . $term->count .')</option>'; } echo "</select>"; } } } } YourSite_Blocks::on_load(); } </code> It worked perfectly until now. I'm using a theme that seems to have a problem with the first line: <code> add_action('init', 'my_init_method'); </code> Is there any way of modifying this code so that it can still work without that conflicting line of code?
|
What is the error message being generated? Also, to avoid conflicts, all custom Theme functions, classes, options, constants, etc. should be prefixed uniquely , e.g. using <code> theme-slug </code> . It is highly likely that a generic function name like <code> my_init_method </code> is used by another Plugin or Theme. Try renaming it to <code> mytheme-slug_init_method </code> . EDIT: To implement, rename your function call from: <code> function my_init_method() {} </code> to: <code> function mytheme-slug_init_method() {} </code> Then, change your hook call from: <code> add_action( 'init', 'my_init_method' ); </code> to: <code> add_action( 'init', 'mytheme_init_method' ); </code>
|
Is there any way of not using my_init_method in the following code (that creates a custom post type)?
|
wordpress
|
What's the best way to ensure that post and page slugs use underscores instead of hyphens, without needing to edit the slug manually (or updating the page manually) Current permalink: <code> www.<domain>.com/2011/05/this-is-a-test-post/ </code> Desired permalink <code> www.<domain>.com/2011/05/this_is_a_test_post/ </code> One approach I've tried is to hook into <code> sanitize_title </code> , but this seems to only be called when the post is updated, so not very practical for a blog of several thousand post. Is there any way to force each post to update? I need this to preserve compatibility as an old MovableType site is moved into WordPress - using .htaccess isn't really an option
|
IMO hooking into sanitize_title is probably the best way to go here. Check out this plugin by Mark Jaquith which does something similar: http://txfx.net/files/wordpress/periods-in-titles.phps As for updating the old posts, I would just write a simple script that would generate sql to manually update everything. (code not tested) <code> <?php function sanitize_title_with_underscores( $title ) { return str_replace( '-', '_', sanitize_title_with_dashes( $title ) ); } $posts = get_posts( array( 'numberposts' => -1 ) ); foreach ( $posts as $post ) { global $wpdb; $id = absint( $post->ID ); $name = sanitize_title_with_underscores( $post->post_name ); print "\n" . "UPDATE $wpdb->posts SET post_name = '{$name}' WHERE ID = {$id};" } ?> </code> Probably not the most elegant solution, but for something that only needs to be done once, it should work rather well.
|
Using underscores instead of hyphens in the permalink
|
wordpress
|
I just made my first plugin and it got approved by WordPress. Great news for me, but now what? The "instructions" on the Codex are anything but clear for me. I did find an article on Dig WP and I managed to get to the 3rd line of code. After that no joy. Does anyone here have a clear set of instructions on how to do this without the need to read an entire book? I am sure that there are very experienced people here who do this stuff all the time... Thanks in advance!
|
Step 1 - Make sure things are formatted correctly WordPress itself depends on the headers at the top of your main plugin file. In many cases, if your plugin is "My Cool Plugin" this file is <code> my-cool-plugin.php </code> in the main directory of your folder. Make sure the top part of the file follows this format: <code> <?php /* === [Plugin Name] === Plugin Name: [Plugin name] Plugin URI: [Website where plugin information can be found - your blog, maybe] Description: [Short description of your plugin] Author URI: [Your website] Author: [Your name] Version: [This version number] */ </code> The WordPress.org repository depends on your <code> readme.txt </code> file to create a description and download page. So make sure your <code> readme.txt </code> file fits the following format: <code> === [Plugin Name] === Contributors: [Your WordPress.org username] Donate link: [A site people can go to to give you money] Tags: [Search terms related to your plugin] Requires at least: [Minimum version of WordPress required] Tested up to: [Newest version of WordPress you've tested with] Stable tag: [This version number] [Short, one-sentence description of your plugin] == Description == [Long description of your plugin] == Installation == [Steps required to install the plugin] == Frequently Asked Questions == = [A question] = [An answer] = [Another question] = [Another answer] == Screenshots == == Changelog == == Upgrade Notice == </code> There's a handy readme validator on WordPress.org you can use to make sure your readme has everything it needs. Just copy-paste and it will check to make sure all the sections are there and that you're ready to go. Step 2 - Check out the SVN repository It's a good idea to keep your development version separate from the WordPress.org plugin repository. Yes, SVN is used for version control, but WordPress uses it more for release management. If you start committing every changeset to the repository, you'll potentially run into problems. One thing a lot of developers do is develop locally using Git, then transfer your files into the Subversion repository when you're ready to do a release. These instructions assume you're using a Windows computer. If you're on a Mac, you can use SCPlugin instead of TortoiseSVN. The steps you'll need to follow will be the same, only the contextual menus and screenshots will differ slightly because of the UI. I don't have a Mac, so I can't create screenshots to walk you through a tutorial ... but trust me, it's the same process. Install TortoiseSVN if you don't have it already. TortoiseSVN is an open source Subversion GUI for Windows. Trust me, using the GUI is infinitely easier than trying to do things from the command line. You'll run into fewer problems, too. Check out your WordPress-hosted SVN repository Find a place where you want to store the WordPress-hosted version of your plugin. By default, I use <code> /My Documents/WordPress/ </code> for all of my hosted dev work. Right-click inside the folder, and select "SVN Checkout" from the dropdown menu. In the dialog window that pops up, enter your WordPress.org plugin repository URL (I'm using one of mine for demonstration purposes) and choose which subfolder you want to create. Tortoise will think for a bit, then it will pull down the repository from WordPress.org. The newly created folder will have all the requisite folders already set up for you. Now you just copy-paste and commit ... one step at a time. Copy your latest version into <code> /tags </code> This is where I do things backwards from most tutorials. Everyone else will tell you to commit <code> /trunk </code> first, but remember that WordPress doesn't use anything in <code> /trunk </code> except the readme file when looking at plugins. So if you put your plugin into <code> /trunk </code> and lose your network connection (or something else goes wrong) before you commit a tag, you'll have issues. In the <code> /tags </code> folder, create a folder named the same as the version you're releasing for your plugin. So if you're releasing version 0.1, create a <code> /tags/0.1 </code> folder. Copy your entire plugin into this folder. Now right-click inside the folder and select "SVN Commit" from the dropdown menu. You'll see a window pop up that shows all of your changes (you should see all your new files marked as "non-versioned"). Check the box next to all of your plugin's files (or click "Select All" to select all of them). In the box on the top, enter a commit message. Since you're committing a tag, you should probably use something like: Tagging version 0.1 of [My Plugin]. Click OK. Again, Tortoise will think for a few minutes, then it will ask you for your WordPress username and password in order to commit to the server. Provide them, wait for things to go through and say "Success," then move on to the next step. Copy your latest version into <code> /trunk </code> Now navigate to the <code> /trunk </code> folder of the repository and once again copy-paste your plugin to that folder. Go through the same steps above to select your files and prepare the commit. But for a message, use something that explains what the new release does: Version 0.1 of [My Plugin] - adds support for OpenID. Once everything goes through, you just have to wait a bit for WordPress.org's servers to catch up. They can be slower some days than others, but within an hour or so you should see your new release in the repository. Updating a plugin to a new version Once your plugin is in the wild, preparing an update is relatively easy. First, use the SVN Update command to make sure you have the latest version of the repository. If you're the only developer, you should already, but it's good practice to update before you commit anyway. Then go through the process above to create a new sub-folder in <code> /tags </code> for your new version. Say, <code> /tags/0.2 </code> . Don't touch the old <code> /0.1 </code> folder. It's there for a reason and you'll never touch it again. Commit your new tag, then go to the <code> /trunk </code> folder. Replace everything in <code> /trunk </code> with your new version and commit as above. Once the servers update, they'll start talking about the new version rather than the old one.
|
How to add plugin to WordPress Repository?
|
wordpress
|
I need guidance to edit the WordPress plugin and theme files via phpmyadmin If I want to edit a particular plugin file or remove a plugin completely from database, I could able to find them ,but I can able to find the data tables for options , comments, links etc. I don't know how to edit/remove a particular plugin or theme there. Could anybody let me know how to find a particular plugin or the entire ' plugins ' folder in data base? Thank you!
|
Plugins and themes are no in the database, they are physical files under wp-content directory, and that is why you CAN'T find them in the database nor edit them from phpmyadmin. However WordPress has a built in editor for plugins and themes files. For themes its under appearances -> editor and for plugins its under plugins-> editor.
|
How do i edit the plugin files in DataBase via phpMyAdmin?
|
wordpress
|
I'm new with <code> wordpress </code> and I would like to understand better if it's possible to create pages with an url based on the <code> category </code> and then the <code> post title </code> , so: something like <code> http://mysite.com/category-name/the-post-title </code> or <code> http://mysite.com/category-name/12345 </code> (the post id) or <code> http://mysite.com/category-name/12345/the-post-title </code> does exist some plug-in do this or should I consider other ways like <code> url_rewrite </code> to do this?
|
Yes, any of those are possible and configurable under <code> Settings > Permalinks </code> . Have a look at the Permalinks page for other possibilities. One thing to note though, it's suggested to add a number at the beginning of your permalinks to reduce the number of rewrite rules WordPress has to generate to resolve all of your URLs. The permalink strings for your examples would be: <code> /%category%/%postname% /%category%/%post_id% /%category%/%post_id%/%postname% </code>
|
Posts URL structure like site.com/category/the-post-title
|
wordpress
|
I have a WP_Query returning a list of posts of a particular post type and with a certain meta_value (custom field value) Is there a way generate an RSS feed based of these results ?
|
Look at this: http://www.seodenver.com/custom-rss-feed-in-wordpress/
|
How can I generate a RSS feed based on a custom WP_Query?
|
wordpress
|
Okay I have a custom loop within the main loop of the page that shows 4 posts but obviously excludes the current main post. I'll show you: <code> <?php $my_query = new WP_Query( "cat=3&posts_per_page=4" ); if ( $my_query->have_posts() ) : while ( $my_query->have_posts() ) : $my_query->the_post(); if($post->ID == $mainPost) continue; ?> <?php get_template_part('workThumb'); ?> <?php endwhile; endif; wp_reset_postdata(); ?> </code> However I want to show 4 posts in this loop but obviously if it contains the current post then it only shows 3. However if I increase the posts_per_page to 5 then on pages when it doesn't include the current post it shows 5 posts, which I don't want. I hope this makes sense. Any ideas?
|
change your query to: <code> <?php $my_query = new WP_Query( array("cat" => 3, "posts_per_page" => 4, "post__not_in" => array($mainPost))); </code> http://codex.wordpress.org/Function_Reference/WP_Query#Post_.26_Page_Parameters
|
Exclude current post but keep the same posts-per_page amount
|
wordpress
|
I would like to be able to create a rotating background image that resizes with the browser window. I would like to also be able to set a certain amount of images to rotate per page or at the least start at a random number. Here is an example > http://www.theme-dutch.com/presents/screen/ Is there a plugin for this? I am assuming it's Jquery. Thanks.
|
You can use CSS3 <code> background-size </code> to make your background-images stretch to cover the area of the box. If you then create a containing box positioned absolutely over the whole page, you can put your slides in there. At that point it is just a matter of fading them in and out, something which can be easily done via a jQuery plugin like Cycle . Here's an example: http://jsfiddle.net/ZnAqE/1/ As you can see all you need to do to add slides is create a new child <code> div </code> for <code> #slideshow </code> . In WordPress this can be done by looping over your gallery images. Related reading: Supersized – Full Screen Background/Slideshow jQuery Plugin Advanced jQuery background image slideshow
|
Wordpress Rotating Background Images
|
wordpress
|
I have an two wordpress sites that I would like to host on the same domain. One is already up and running, the other is sitting in waiting. Can I get the second as a subdomain, or simple within a folder, to run on the same domain (different DB) without converting to multisite?
|
Point the subdomain to the same directory as the main site, and define different settings in your wp-config.php per <code> $_SERVER['HTTP_HOST'] </code> : Example from my local setup: <code> switch ( $_SERVER['HTTP_HOST'] ) { case 'zzl.dev': $table_prefix = 'zzl_'; $table_name = 'zzl'; break; case 'wpbuch.dev': $table_prefix = 'wpbuch_'; $table_name = 'wpbuch'; break; default: $table_prefix = 'wp_'; $table_name = 'wpdev'; break; } define( 'DB_NAME', $table_name ); </code> You can change much more variables in the switch: all <code> DB_* </code> definitions, <code> WP_PLUGIN_DIR </code> and <code> WP_PLUGIN_URL </code> (to share the plugin list between different sites), <code> WPLANG </code> and so on.
|
Can I run a second wordpress site as a subdomain without using multisite?
|
wordpress
|
I made a WordPress plugin like this: <code> Class MY_CLASS { //codes } Global $myclass; $myclass = New MY_CLASS (); </code> After installed and activated the plugin, can I use this class in other plugins without including the myclass.php file? For example, in another plugin: <code> Global $myclass; $myclass->a = 'dog'; </code>
|
Technically, it is possible. But I would use a slightly different approach. If your second plugin is loaded first you get an error. If you want to replace the class in another plugin, it is hard to do this. So hook into <code> plugins_loaded </code> with a specific priority to create the object and use the object in your second plugin on the same hook with a lower (later) priority: Plugin 1 <code> add_action( 'plugins_loaded', array ( 'My_Class', 'init' ), 10 ); class My_Class { /** * Handler for the action 'init'. Instantiates this class. * * @since 0.1 * @return void */ public static function init() { // Named global variable to make access for other scripts easier. $GLOBALS[ __CLASS__ ] = new self; } public function __construct() { /* Do something awesome. */ } } </code> Plugin 2 <code> add_action( 'plugins_loaded', 'depending_operation', 11 ); function depending_operation() { if ( empty ( $GLOBALS[ 'My_Class' ] ) ) { return; } /* Do something awesome again. */ } </code> Note the 10 and the 11 in <code> add_action() </code> ? This guarantees that your second plugin will never run before the first. It still has to check if the first plugin is active and working. Now you can even replace the class in another plugin: Plugin 3 <code> add_action( 'plugins_loaded', 'replace_global_class', 12 ); function replace_global_class() { $GLOBALS[ 'My_Class' ] = new Replacement_Class; } class Replacement_Class {} </code>
|
Does an activated plugin automatically mean its methods are available to other WP functions?
|
wordpress
|
I like to use the new taxonomy to make a little CRM, really simple <code> contact - name - tel - email - company </code> Fine, the secretary will enter all the name in the database of the cms (WordPress), and i will have all those in, able to display it like a list or whatever i like 1) first question, do i reinvent the wheel, is it already done... Now, with all those nice contact... i have a page, or a list of really good product.. and all those contact can benefit to see it in there mail, much like a newsletter, but simpler... 2) question, how can i get all those email, and have wp to send the wp page/link to those email... plugin, code ? thanks in advance for the light on that
|
I used http://rolopress.com/ a while back and have nice features for contact administration
|
Get something out from taxonomy
|
wordpress
|
I am trying to list only the posts from a single category of my custom taxonomy. I have created a custom post type called "Inventory" and a custom taxonomy called "Inventory Category". I then created a number of categories using the "Inventory Category" taxonomy. I would now like to display the posts from only a single category. fyi, this is not for display on the taxonomy.php page, that is all set up and working fine. This loop will be called on other pages. This is the code I have so far, it returns ALL posts from the "Inventory Category" taxonomy rather than just those in the category "bulk racks". <code> query_posts( array( 'post_type' => 'inventory', 'inventory-category' => 'bulk-racks' ) ); </code> Any help would be greatly appreciated! Here is how i created the custom post type & taxonomy: <code> /* --- Create Inventory Custom Post Type --- */ add_action('init', 'inventory_register'); function inventory_register() { $args = array( 'label' => __('Inventory'), 'singular_label' => __('Inventory'), 'public' => true, 'show_ui' => true, 'capability_type' => 'post', 'hierarchical' => true, 'rewrite' => true, 'supports' => array('title', 'thumbnail', 'revisions','custom-fields') ); register_post_type( 'inventory' , $args ); } /* --- Register Custom Taxonomy for Inventory Lists --- */ add_action( 'init', 'register_my_taxonomies', 0 ); function register_my_taxonomies() { register_taxonomy( 'division', array( 'inventory' ), array( 'hierarchical' => true, 'public' => true, 'labels' => array( 'name' => __( 'Inventory Category' ), 'singular_name' => __( 'Inventory Categories' ), 'show_ui' => true, 'show_in_nav_menus' => true, ), ) ); } </code>
|
I believe your looking for something like this <code> <?php $args = array( 'posts_per_page' => 1, 'post_type' => 'inventory', 'tax_query' => array( array( 'taxonomy' => 'inventory-category', 'field' => 'slug', 'terms' => array( 'bulk-racks' ) ) ) ); query_posts( $args ); while ( have_posts() ): the_post(); // do stuff here ?> <?php endwhile; ?> </code> Heres how to properly register a post type according to the WordPress Codex page on post types and how to register taxonomies
|
How to display posts from a single category within a custom taxonomy
|
wordpress
|
Enabling minify is causing cforms (ajax enabled forms) to produce the following error on submit, whereby it hangs: POST dearearth.net/wp-content/plugins/cforms/lib_ajax.php 500 (Internal Server Error) Current minify settings: http://loomn.it/baK Form page: http://dearearth.net/contact Any suggestions on how to get past this (aside from disabling minify altogether)? Thanks!
|
I believe its a bug which is currently being attended to. Read the article below, which describes the current versions problems. W3 Total Cache Minify Bug Make sure that you've upgraded to the latest version in case its been resolved.
|
W3 Total Cache Minify + cforms II = POST /wp-content/plugins/cforms/lib_ajax.php 500 (Internal Server Error)
|
wordpress
|
Is there a way to accomplish this by the functions.php file ? I tried: <code> add_filter( 'gettext', 'change_post_to_article' ); add_filter( 'ngettext', 'change_post_to_article' ); function change_post_to_article( $translated ) { $translated = str_ireplace( 'Post', 'Article', $translated ); return $translated; </code> } but it does not change all the entries for "post". I still have "Post tags" for example. Any suggestion?
|
This is essentially a duplicate of this question: stackexchange-url ("Is there a way to change 'Posts' to be 'Portfolio' is the WP backend?")
|
Rename "post" to "article" throughout the admin back end
|
wordpress
|
Right, here's the deal. I've got a loop of which displays news posts, these posts can belong to special categories (not normal categories) and I want to be able to filter by them. If I wasn't too interested in aesthetics I'd use a link like this: <code> domain.com/news?filter=cat1 </code> But instead what I want to do is this (» rewritten): <code> domain.com/news/cat1 » domain.com/news/?filter=cat1 </code> I've modified the <code> .htaccess </code> to pass the <code> cat1 </code> value as a GET variable: <code> RewriteEngine On RewriteBase / RewriteRule ^news/(.*)/$ /news/?filter=$1 [L,QSA] # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress </code> The problem is even though this is now successfully passing the <code> filter </code> variable in, WordPress treats the <code> /cat1/ </code> as a page, it obviously cannot find it and thus throws a 404. Is there a way to allow this particular URL rewriting without WordPress firing a 404? It appears it's taking the URL in the address bar and parsing that, what I really want is for it to parse the rewritten URL. Thanks
|
WordPress also has a rewriting mechanism, it's better to use that instead of doing it in the <code> .htaccess </code> file. You can add your own rewrite rules to it. In your case we want to store the <code> cat1 </code> part in a separate query variable, so we also need to tell WordPress to allow this query variable (it uses a whitelist for safety). The precise form of the rewrite rule depends on what <code> http://domain.com/news/ </code> is: is it a Page with a custom template, or something else? You should find this out (using my stackexchange-url ("Rewrite analyzer plugin") for example), and add this to the rewrite rule. <code> add_action( 'init', 'wpse16819_init' ); function wpse16819_init() { // Base form, will probably not work because it does nothing with the `news` part add_rewrite_rule( 'news/([^/]+)/?$', 'index.php?wpse16819_filter=$matches[1]', 'top' ); // Use this instead if `news` is a page add_rewrite_rule( 'news/([^/]+)/?$', 'index.php?wpse16819_filter=$matches[1]&pagename=news', 'top' ); } add_filter( 'query_vars', 'wpse16819_query_vars' ); function wpse16819_query_vars( $query_vars ) { $query_vars[] = 'wpse16819_filter'; return $query_vars; } </code> Remember to flush the rewrite rules (save them to the database) after you add this code. You can do this by visting the Permalinks page in the admin area. You can now access the <code> wpse16819_filter </code> variable with <code> get_query_var( 'wpse16819_filter' ); </code> .
|
Hijacking the URL for filtering
|
wordpress
|
I'm writing a customised walker class for wp_nav_menu and want to be able to specify if an li contains a submenu. So I want my markup to be: <code> <li class="has_children [other-wordpress-classes]"> <a class="parent-link">Some item</a> <ul class="sub-menu"> </code> I know how to add and remove the classes fine, I just cant find anything to tell me if the current item has children items. Any ideas? Thanks in advance.
|
<code> start_el() </code> should get this information in its <code> $args </code> parameter, but it appears WordPress only fills this in if <code> $args </code> is an array , while for the custom navigation menus it is an object. This is reported in a Trac ticket. But no problem, you can fill this in yourself, if you also override the <code> display_element() </code> method in your custom walker (because this is the easiest place to access the child element array): <code> class WPSE16818_Walker extends Walker_Nav_Menu { function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) { $id_field = $this->db_fields['id']; if ( is_object( $args[0] ) ) { $args[0]->has_children = ! empty( $children_elements[$element->$id_field] ); } return parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output ); } function start_el( &$output, $item, $depth, $args ) { if ( $args->has_children ) { // ... } } </code>
|
Add 'has_children' class to parent li when modifying Walker_Nav_Menu
|
wordpress
|
This seems pretty straightforward using cookies in straight HTML. In wordpress, how do I do this? AFAIK, wordpress only provides cookies functions for logging/logged in users. How about when I don't want the user to log in to show my greetings?
|
if you are not looking at coding it yourself then WP Greet Box( http://wordpress.org/extend/plugins/wp-greet-box/ ) could be used to achieve this. This plugin automatically loads a greeting message based on the referrer and it even allows you to customize the greetings, set time out to auto close the greeting etc. The only problem I see(from your question) is that this plugin greets all visitors not just new. If the visitor closes it, it won't be shown again. First time visitors based on cookies aren't reliable anyway, clear the cache and you become first time visitor again!
|
Show greetings on first time visitors?
|
wordpress
|
I'm looking for a solution to notify/force all users in an MU network to change their passwords. Any ideas of a solution out there as a plug-in?
|
You can use PassExpire force all users to change password at next login. Or set it to expires user passwords after 60 (Variable) days and requires a password change on login. Note: This is community wiki answer for this Question (as @tony-zeoli has already answered his own question).
|
Force all users in MU to change their passwords
|
wordpress
|
I've a class which has a function that check and creates table in database. In order to do so i need to use WordPress $wpdb object. I need the function to run only on first plugin activation, so i use the function: <code> register_activation_hook ( __FILE__, array( 'MemorialCandles', 'dbInstall' ) ); </code> The problem is that i get always this error: Fatal error: Using $this when not in object context in /home/xxx/xxx/wordpress/wp-content/plugins/MemorialCandles/memorial-candles.class.php on line 77 the class code: <code> <?php // Global Variables: global $wpdb; register_activation_hook ( __FILE__, array( 'MemorialCandles', 'dbInstall' ) ); /** * Class: MemorialCandles * * Provides skeleton to the plugin and handles queries and action. * * @author Dor Zuberi <[email protected]> * @copyright 2011 Dor Zuberi * @license http://www.php.net/license/3_01.txt */ class MemorialCandles { // Variables /** * @var string stores plugin direction - RTL or LTR. */ private $pluginDirection; /** * @var string stores the plugin database table name. */ private $tableName; // Constructor /** * Initiates the plugin, stores and configure the basic setup procedures. * * @return void */ function __construct() { global $wpdb; $this->tableName = $wpdb->prefix . 'memorialcandles'; } // Getters // Setters // Methods /** * Handles the database table creation. * * @return void */ function dbInstall() { global $wpdb; if( $wpdb->get_var( "SHOW TABLES LIKE `{$this->tableName}`" ) != $this->tableName ) { $sql = "CREATE TABLE `{$this->tableName}` ( id int(8) NOT NULL AUTO_INCREMENT, fullName text NOT NULL, message text NOT NULL, postDate text NOT NULL, galleryID int(8) NOT NULL, UNIQUE KEY id(id) );"; require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); dbDelta( $sql ); } } /** * Handles the database table drop procedure. * * @return void */ function dbUninstall() { global $wpdb; $sql = "DROP TABLE IF EXISTS `{$this->tableName}`;"; $wpdb->query( $sql ); } } ?> </code> Thanks in advance! :D
|
Try: <code> register_activation_hook ( __FILE__, array( new MemorialCandles(), 'dbInstall' ) ); </code> Or define dbInstall as ´static´ and use that to set the table name instead the constructor, which I think is the best approach.
|
Call External Object in Class Function During Callback
|
wordpress
|
I recently adjusted the twentyten theme to display archives in a three column grid. In doing so, it seems that the archive has lost the ability to display posts from the specified taxonomy. For instance, a taxonomy type is 'Flowers', with a specific flower being 'Rose'. When the 'Rose' archive is displayed, it simply lists all posts. I believe I have narrowed the problem to this line: <code> query_posts('cat=0&posts_per_page=12&paged='.$paged); </code> I understand that it is just listing all 'uncategorized' posts, but I am at a loss with how to have display a specific taxonomy archive as would normally be done for a category archive. Any ideas? I am guessing it isn't as hard as I am making it, but I have searched for hours with no luck. Thanks in advance!
|
you can add the current term to you query so if its category, tag or custom taxonomy you will get the posts with the current term, try changing this: <code> query_posts('cat=0&posts_per_page=12&paged='.$paged); </code> with this: <code> $term_slug = get_query_var( 'term' ); $taxonomyName = get_query_var( 'taxonomy' ); query_posts(array('posts_per_page' => 12, 'paged' => $paged, $taxonomyName => $term_slug)); </code>
|
Creating an Archive using a Custom Taxonomy
|
wordpress
|
I'm trying to use some conditional logic to compare custom fields in my query, but a bit stuck. How would I get all posts with ReleasedProject AND PermanentArtist set to 'true'? Here's what I have so far, I'm assuming it's something to do with 'compare': Thanks osu EDIT : To clarify what I want to do - I'm trying to exclude pages that have two custom field values (ReleasedProject and PermanentArtist in this case) set to 'false'. These are set through checkboxes generated using the plugin Custom Field Template. I've updated the code to illustrate that I need to filter out all pages with these two custom fields set to false: <code> global $post; $artist_args = array( 'post_type' => 'page', 'post_parent' => $post->ID, 'posts_per_page' => -1, 'orderby' => 'name', 'order' => 'ASC', 'meta_query' => array( array( 'key' => 'ReleasedProject', 'value' => 'false' ), array( 'key' => 'PermanentArtist', 'value' => 'false' ) ) ); $my_query = new WP_Query($artist_args); </code>
|
If you want all posts that have <code> ReleasedProject </code> AND <code> PermanentArtist </code> both set to true, you need to change the <code> value </code> keys for both of those to <code> 'true' </code> . If you want to exclude all posts that have both of those set to <code> 'false' </code> , you need to add <code> 'compare' => '!=' </code> to both meta query arrays. EDIT The logic behind meta queries is such that all conditions must be met (it's an <code> AND </code> relationship). So if you say <code> 'meta_query' => array( array( 'key' => 'ReleasedProject', 'value' => 'false' ), array( 'key' => 'PermanentArtist', 'value' => 'false' ) ) </code> That means "find all posts that have both Released Project identical to <code> 'false' </code> AND Permanent Artist identical to <code> 'false' </code> ." If you were to add the <code> 'compare' => '!=' </code> statement like I mentioned earlier, it would be saying "find all posts that have both Released Project NOT identical to <code> 'false' </code> AND Permanent Artist NOT identical to <code> 'false' </code> ." If you have a post that has Released Project set to <code> 'false' </code> and Permanent artist set to <code> 'true' </code> , it will not show up in either of those queries. Furthermore, if a meta value is missing, it will not show up in the results either. So if you have a post with Released project set to true, and permanent artist not set at all, this meta query will not find that post: <code> 'meta_query' => array( array( 'key' => 'ReleasedProject', 'value' => 'false', 'compare' => '!=' ), array( 'key' => 'PermanentArtist', 'value' => 'false' 'compare' => '!=' ) ) </code> Basically, meta queries don't do 'either/or' checks, they do 'both/and' checks when you have multiple meta queries.
|
WP 3.1 meta_query for multiple custom field values
|
wordpress
|
I am converting a website from straight html (with tables! Ugh!) to WordPress. The company has a new design every year, and but keeps an archive of their old site(s) with the old design(s) on their website, so people can look back over the years. Keeping the old HTML archives on a WP site What would you recommend to keep the old HTML archives? WP doesn't play well with serving up plain HTML pages. I don't really want to go to all the trouble of creating a decade's worth of sub-domains and hosting the archives there (eg, 2009.mydomain.com, 2008.mydomain.com) because then I'll have to go through all those html pages and update any references to the archives as well (not really a problem with <code> grep </code> and <code> sed </code> , just a pain to do). However, thats really the only way I can think of doing it effectively. Keeping the "annual archive" system Once the old archives are up and running, how do I "maintain" this system in WordPress? I know WP does a nice archive system, but I'd need to show all the 2011 posts and pages with the 2011 design, all the 2012 posts/pages with the 2012 design. My thought was display themes conditionally -- maybe to add a custom field to each post/page and add a function that checks the custom field and serves the appropriate CSS file. Of course, this requires that the theme templates don't really change much from year to year. Or perhaps change entire themes, conditionally (easy enough to copy this conditional function to every theme). Is there a better way of doing this? The other option I thought of was to export the year to be archived to HTML and serve it up as (eg) 2011.mydomain.com. However, then you lose the ability to search through posts/pages, etc. This is particularly annoying as there is a whole custom-post system planned, and archiving the site annually will kind of negate the benefit of the custom-post taxonomies. I'd prefer to keep the wordpressiness and perhaps just use Apache redirection of future "subdomains" to the appropriate archive, to keep a consistent feel across the site's archives (don't want half the archives accessed via 2006.mydomain.com and the future archives from mydomain.com/archives/2012). I hope I have explained this relatively clearly. Any suggestions would be welcome.
|
Checkout Stephanie Leary's HTML Import Plugin . She is an expert on importing old HTML pages into WordPress. You just point the plugin at the existing HTML pages on your server and it pulls them in. To archive you could create a custom taxonomy for the years and use WordPress archive pages to display them.
|
Retaining old HTML archives and displaying themes conditionally
|
wordpress
|
I'm still struggling to get my head around this whole hooking into things, so I'm really stuck on trying to do the following task: If update_post_meta is fired then check to see if the meta_key is equal to something (I want to trigger some code if a particular meta_key is used). If the meta key I'm looking for then run some code that will need to know the <code> $post->ID </code> of the meta key being updated. I need to hook into the delete_post_meta too that kind of does the reverse as above. Can anyone provide me with some example code for hooking into update_post_meta and delete_post_meta?
|
The <code> update_post_meta </code> hooks are called from the more generic <code> update_metadata() </code> function, so you might not have found it directly. The three hooks are: <code> update_post_metadata </code> , a filter which allows you to "hijack" the metadata update and do something else. If you hook up a function that returns a boolean, execution stops there and the boolean is returned. <code> update_post_meta </code> , an action that gets called before the data is updated in the database. <code> updated_post_meta </code> , an action that gets called after the data is updated in the database. If the meta key did not exist in the database yet, <code> update_metadata() </code> passes control to <code> add_metadata() </code> , which has the similar hooks <code> add_post_metadata </code> , <code> add_post_meta </code> , and <code> added_post_meta </code> . This happens before <code> update[d]_post_meta </code> gets called. So if you want to do something when the meta key is added or updated, be sure to hook into both the <code> update* </code> and the <code> add* </code> hooks - but notice that while the <code> updated_* </code> and <code> added_* </code> actions pass similar parameters, <code> update_* </code> and <code> add_* </code> do not ( <code> add_post_meta </code> does not pass a meta ID first). <code> delete_metadata() </code> has similar hooks: <code> delete_post_metadata </code> , <code> delete_post_meta </code> and <code> deleted_post_meta </code> . Sample code: <code> add_action( 'added_post_meta', 'wpse16835_after_post_meta', 10, 4 ); add_action( 'updated_post_meta', 'wpse16835_after_post_meta', 10, 4 ); function wpse16835_after_post_meta( $meta_id, $post_id, $meta_key, $meta_value ) { if ( 'wpse16835_meta_key' == $meta_key ) { wpse16835_do_something( $post_id, $meta_value ); } } add_action( 'deleted_post_meta', 'wpse16835_deleted_post_meta', 10, 4 ); function wpse16835_deleted_post_meta( $deleted_meta_ids, $post_id, $meta_key, $only_delete_these_meta_values ) { if ( 'wpse16835_meta_key' == $meta_key ) { wpse16835_undo_something( $post_id ); } } </code>
|
How to hook update_post_meta and delete_post_meta?
|
wordpress
|
How can I move theme and plugin (widget) settings from a WordPress.com site to a self-hosted installation? My client is moving from <code> hissite.wordpress.com </code> to his own host at <code> hissite.com </code> . I have moved over the content using the Import/Export feature, but I can't access the theme and widget plugin files, since WordPress.com offers no FTP access. We also don't want to pay WordPress.com to move these files over .
|
First off, check if the theme is available in wordpress.org themes: http://wordpress.org/extend/themes/ If it's not, find the name of the theme developer and contact them. Many developers of wordpress.com themes are happy for people to use their themes on self-hosted WordPress blogs. The developer's name and contact details can be found by looking at style.css. You can see the content of style.css by viewing the CSS file in your browser. Alternatively, navigate to style.css for the theme you want in the wordpress.com theme repository: https://wpcom-themes.svn.automattic.com/ This is also where you download the theme. You must seek permission from the theme's author before you download and use their theme unless the theme's style.css includes a note to say it is released under the GPL. If it's GPL then permission has already been given. For plugins, you need to download them from wordpress.org. If they are not available there you will need to find acceptable replacements or track down who developed them and ask if the plugins are going to be made available.
|
Moving WordPress.com theme and widget settings to self-hosted site?
|
wordpress
|
I'm a small-timer, so I was amazed at this question: stackexchange-url ("Ideal WP multisite server setup for up to 1000 sites?"). I know that WordPress is a highly flexible platform, but what types of entities/businesses would need or use this type of setup? In situations like this is there much redundant content? How do you begin designing something like this? Are there lessons in this for the small-timers?
|
Let's see how many use cases I can come up with in 20 seconds (grin) School and university sites where every student gets a blog Community sites (BuddyPress) where every member gets a blog (i.e. Dieting sites like SparkPeople.com) News organizations where the many personalities get a blog (i.e. CBS, CNN, etc.) Businesses trying to emulate the Etsy.com business model, where every site has a store plugin and paypal chained payments gateway Businesses trying to emulate wordpress.com where free blogs are offered and upgrades are available for a fee Businesses that create mini-sites for every affiliate product they promote, on an automated basis Businesses that offer website hosting as a service - instead of a raw hosting account, subscribers get a multisite account pre-configured as a CMS for their business vertical, with access to support and features not available via wordpress.com
|
Mega WordPress Applications WPMU or otherwise
|
wordpress
|
I'm building a category picker select list. I just need to populate an array of categorys like so: <code> $myCats = array("null" => "None (default)", "1" => "Uncategorized", "2" => "Second Category", etc..) </code> Does WP have an existing method call I can use to pull this data alone? I may need to exclude some categories from the listing too.
|
Can't you use wp_dropdown_categories ? <code> wp_dropdown_categories('show_option_none=Select category&exclude=1,2,3&selected=6'); </code>
|
Method to retrieve category names and IDs only as an array?
|
wordpress
|
This isn't as simple of a question as you may think. Basically I have a C# program that is hitting the worpdress site and the wp_schedule doesn't seem to fire off. If I go to the site with my firefox browser then it seems to fire-off. Soooo what's the difference here? What exactly causes the cron to fire? Is it the HTTP GET? Or is there some script or function inside the page that is loaded by browsers?
|
The WP-Cron functions are not actually cron functions. Instead of a cron running and executing tasks precisely as scheduled, it waits until the frontend or admin is loaded, checks if any jobs are scheduled and then fires as needed. To execute the cron jobs, WP loads <code> wp-cron.php </code> , which is located in the root folder. My understanding is that when you visit the site and a cron is scheduled, a request is made to <code> http://yourdomain.com/wp-cron.php </code> , which initiates the scheduled cron job(s). I don't know exactly how this works (I've read about it before, but cannot find the resource again), but this request is made in such a way that not all servers can handle it, causing it not to work. I wonder if your problem is that this request isn't made with a GET request to your site. As an alternative, I would recommend using a GET request to <code> http://yourdomain.com/wp-cron.php </code> . In fact, in the excellent Professional WordPress Plugin Development , they recommend the following: A common method is using wget to load wp-cron.php on a schedule. If your server is Linux- based, cron will already exist and can be scheduled using the crontab command. If your server is Windows-based, you can install wget and create a scheduled task to execute it. The wget command would work like this: wget http://www.example.com/wp-cron.php When wget requests wp-cron.php WordPress looks for all scheduled cron jobs and executes as needed. Setting up true cron on your server will guarantee your cron jobs will run perfectly on schedule without missing a beat. Along with this, you need to disable the default way of handling cron: <code> define(‘DISABLE_WP_CRON’, true); </code> Another discussion of this can be found here: http://caramboo.com/2010/03/wordpress-remote-cron-scheduling/
|
What causes wp_schedule_single_event to fire off?
|
wordpress
|
I'm displaying a comment outside the comment template, getting it with <code> get_comments() </code> and echoing the <code> comment_content </code> . My problem is that the comment loses the formatting (paragraphs, line breaks, etc...). In my template I'm using TinyMCEComments (TinyMCE on comment form). Someone pointed me to this solution, but is not working for me. <code> <?php echo wpautop($comment->comment_content);?> </code>
|
applying the 'the_content' filter could work: <code> <?php echo apply_filters('the_content', $comment->comment_content); ?> </code>
|
Comment formatting with comment_content
|
wordpress
|
I'm using Greg's Threaded Comment Numbering plugin to number the comments. Actually I'm displaying a number beside of each parent comment (no threaded comments numbers). I have 2 problems that I have already tried to solve, but without results: I am displaying the top comment with a different layout, I need to start the numbering from #2. seems an easy task but I didn't find the way modifying the plugin code. Display the total number of threaded comments for each comment that has threads. Example: COMMENT 1 ------------1.1 ------------1.2 ------------1.3 total threaded comments = 3 COMMENT 2 ------------2.1 ------------2.2 total threaded comments = 2 etc..... I am already using the code below to get the total number of parents. I can also get the children but it is the total, I need to display the number of each comment children as in the example <code> $number_of_parents = c_parent_comment_counter($post->ID); $number_of_children = $post->comment_count - $number_of_parents; </code> Thanks! EDIT: as requested here is the wp_list_comments callback function. Sorry for the mess, I am not a programmer, will clean the code when the work is finished :) <code> ## Function: Basic Callback Function From WP Codex (http://codex.wordpress.org/Template_Tags/wp_list_comments), January 2009 function gtcn_basic_callback($comment, $args, $depth) { // no changes here except that we have added in the call to gtcn_comment_numbering $GLOBALS['comment'] = $comment; ?> <li <?php comment_class(); ?> id="li-comment-<?php comment_ID() ?>"> <?php if( empty( $comment->comment_parent ) ) { //if the comment does not have a parent, then it is L1?> <div class="linguetta-posizione"><?php echo gtcn_comment_numbering($comment->comment_ID, $args); ?></div> <?php } ?> <div id="comment-<?php comment_ID(); ?>"> <div class="comment-author vcard"> <div class="comment-barra-user"> <div class="comment-avatar"> <?php if( empty( $comment->comment_parent ) ) { ?><?php echo get_avatar($comment,$size='60'); ?><?php } else { ?><?php echo get_avatar($comment,$size='30'); ?><?php } ?></div> <div class="comment-username"><?php printf(('<cite class="fn">%s</cite> '), get_comment_author_link()) ?><br class="clear"/> <?php if( empty( $comment->comment_parent ) ) { ?><div id="comment-container-points"> <div class="comment-points"><img src="<?php bloginfo('template_url'); ?>/images/ico-points.png" /><a>3333</a></div><div class="comment-level"><img src="<?php bloginfo('template_url'); ?>/images/ico-level.png" /><a>livello</a></div> </div> <?php } else { ?><?php } ?> </div> <?php if ( is_user_logged_in() ) { if( empty( $comment->comment_parent ) ) {?> <div class="comment-votazione"><h2>Vota la risposta:</h2> <?php { //if the comment does not have a parent, then it is L1 if(function_exists(ckrating_display_karma)) { ckrating_display_karma(); } } ?> </div> <?php }} else { if( empty( $comment->comment_parent ) ) { ?> <div class="comment-votazione"><h2>Registrati per votare</h2> </div> <?php }} ?> </div><!-- end BARRA USER --> <br class="clear"/> </div> <?php if ($comment->comment_approved == '0') : ?> <em><?php _e('Your comment is awaiting moderation.') ?></em> <br /> <?php endif; ?> <?php comment_text() ?> <div class="reply"> <?php comment_reply_link(array_merge( $args, array('reply_text' => 'COMMENTA LA RISPOSTA', 'depth' => $depth, 'max_depth' => $args['max_depth']))) ?> </div><div class="comment-meta commentmetadata"><?php if( empty( $comment->comment_parent ) ) { ?>Risposta inserita<?php } else { ?> Commento inserito <?php } ?> <?php echo time_ago_comment(); ?><?php edit_comment_link(('- modifica'),' ','') ?></div> </div></li> <?php } // end basic callback function </code>
|
<code> // inside your callback function: static $ancestors = null; $parent = (int) $comment->comment_parent; // Modify INITIAL VALUE here: $init_val = (int) 1; $is_child = false; if ( $parent > (int) 0 ) { $is_child = true; $ancestors[] = $parent; $child_counter = count( $ancestors ) + $init_val; } /* * Only needed in case you want to reset the counter if the current comment has no children else { $ancestors = $child_counter = null; } */ // This shows the number of the current reply counter if ( $is_child ) printf( __( 'This is the child number: ', TEXTDOMAIN ), $child_counter ); </code>
|
Get threaded comments number
|
wordpress
|
I have about 100 posts, and I want to create pages that only show 10 on each. How would I go about this?
|
You need to add the following query argument: <code> posts_per_page </code> <code> global $query_string; query_posts( $query_string . '&posts_per_page=10' ); </code>
|
I have a custom post type with many posts. How do I split the list into multiple pages?
|
wordpress
|
Is there a plugin or a hack such that I can make short updates similar to twitter's on my own wordpress blog? Perhaps making use of a custom post type or something on those lines? What i'm trying to achieve is to create short (150 character limit) posts different to the regular posts on the blog. Once these short updates are published, i'd like them to appear in a custom div tags on the home page. In short, same functionality as twitter but just on your blog. Thanks
|
If you just want to add a character counter for your excerpt, use this function and js. The Php for your functions.php <code> // This goes in your functions.php file inside your themes folder // Add theme support for post formats add_theme_support( 'post-formats', array( 'aside', 'status' ) ); // Add the character counter to the admin UI function wpse16854_char_count_script( $page ) { $post = get_post( $_GET['post'] ); $post_type = $post->post_type; if ( 'page' !== $post_type ) if ( 'post.php' === $page OR 'post-new.php' === $page ) wp_enqueue_script( 'excerpt-counter', get_template_directory_uri().'/excerpt-counter.js', array('jquery') ); } add_action( 'admin_enqueue_scripts', 'wpse16854_char_count_script' ); </code> The JavaScript <code> // This should be saved inside a file named 'excerpt-counter.js' inside your themes folder jQuery( document ).ready( function($) { $( "#excerpt" ).after( "<p style=\"text-align:center;\"><small>Excerpt length: </small><input type=\"text\" value=\"0\" maxlength=\"3\" size=\"3\" id=\"excerpt_counter\" readonly=\"\"> <small>character(s).</small></p>" ); $( "#ilc_excerpt_counter" ).val( $("#excerpt").val().length ); $( "#excerpt" ).keyup( function() { $( "#ilc_excerpt_counter" ).val( $("#excerpt").val().length ); } ); } ); </code> The Loop Then just use the post format "status" (or aside or whatever) when publishing a "twitter like" post and place the following inside your loop: <code> // place the following inside your loop if ( has_post_format( 'status' ) OR 'status' == get_post_format( $GLOBALS['post']->ID ) OR is_object_in_term( $GLOBALS['post']->ID, 'post_format', 'status' ) ) { the_excerpt(); } else { the_content(); // or however you want to treat normal posts } </code>
|
How to post twitter like updates on wordpress
|
wordpress
|
On the site I am currently developing I have used custom post types for the different types of content it contains (News, Podcasts, Press Releases etc). How would I go about showing the label (plus a bit of text) for each section above the loop? For example: Press Releases Some text under the heading. Press Release 1 Press Release 2 Press Release 3 Press Release 4 Press Release 5 Any idea how I would go about achieving this? Thanks!
|
If the template page in question is the archive index for the custom post type, you can simply create a custom template file, <code> archive-{post-type}.php </code> , and add in the Title and custom text. If you don't want to create a custom template file, you can use this boolean as a conditional in your existing <code> archive.php </code> template file, for creating custom output: <code> <?php is_post_type_archive( $post_types ); ?> </code> To retrieve the Title for a Post Type archive: <code> <?php post_type_archive_title( $prefix, $display ); ?> </code> To retrieve the current Post Type (for use in PHP): <code> <?php get_post_type( $post ) ?> </code> To retrieve all Post Type information (e.g. to output Title, Description, etc. if configured): <code> <?php get_post_type_object(); ?> </code>
|
Custom Post Types - Current section heading above the loop?
|
wordpress
|
Let me preface by saying I don't really understand Add_Filter, but I think that I want to be using it here. If not please let me know. I want to modify wp_get_attachment_link so that the link url changes. So for example if I click on a thumbnail in a gallery instead of going directly to the file I want it to go to www.foo.com. So what I would like to do is replace what wp_get_attachment_link does via add_filter. But I can't figure out how add_filter works. How do I get the parameters from the original function? Original Function Call <code> wp_get_attachment_link($id, $size, $permalink, $icon, $text); </code> Filter <code> add_filter( 'wp_get_attachment_link', 'modify_attachment_link'); function modify_attachment_link() { //how do i access $id, $size, $permalink, $icon and $text??? $foo = $id.$permalink; return $foo; } </code>
|
Look at the function in <code> wp-includes/post-template.php </code> . There you see what information you can get: <code> apply_filters( 'wp_get_attachment_link' , "<a href='$url' title='$post_title'>$link_text</a>" , $id , $size , $permalink , $icon , $text ); </code> Note that you cannot access the <code> $link_text </code> and the <code> $_post </code> object as a standalone variables. Bug? Bug! In your filter you cannot change the order of the arguments, just the number. So <code> add_filter( 'wp_get_attachment_link', 'modify_attachment_link', 10, 2 ); </code> will give you the link markup and <code> $id </code> . The highest number of available arguments is 6 . The return value of your function will replace the first argument. An (untested) example for changing the link URL: <code> /** * Replaces the URL for an attachment link. * * @param string $markup Original link markup * @param int $id Post id * @param mixed $size Image size, array or string * @param string $permalink URL * @param bool $icon Use an icon? * @param bool $text Use text? * @return string New markup */ function modify_attachment_link( $markup, $id, $size, $permalink, $icon, $text ) { // We need just thumbnails. if ( 'thumbnail' !== $size ) { // Return the original string untouched. return $markup; } // We have stored the new URL in a post meta field. // See stackexchange-url for an example. $new_url = get_post_meta( $id, 'extra_url', TRUE ); if ( empty ( $new_url ) ) { // There is no URL. return $markup; } // Recreate the missing information. $_post = & get_post( $id ); $post_title = esc_attr( $_post->post_title ); if ( $text ) { $link_text = esc_attr( $text ); } elseif ( ( is_int( $size ) && $size != 0 ) or ( is_string( $size ) && $size != 'none' ) or $size != FALSE ) { $link_text = wp_get_attachment_image( $id, $size, $icon ); } else { $link_text = ''; } if ( trim( $link_text ) == '' ) { $link_text = $_post->post_title; } return "<a href='$new_url' title='$post_title'>$link_text</a>"; } add_filter( 'wp_get_attachment_link', 'modify_attachment_link', 10, 6 ); </code> Further reading: stackexchange-url ("How can I add a URL field to the attachments window?") stackexchange-url ("attachment url rewrite") stackexchange-url ("Changing attachment urls?")
|
Add_Filter example for wp_get_attachment_link
|
wordpress
|
I created a contact form for my sidebar that is working perfectly in Chrome but not in IE or FF. I've been staring at it for hours and can't find out what I did wrong. I'm not getting any errors anywhere, but when I submit it in FF or IE, it logs "nope" in my console and echos out a message of -1 in #jvmsg. My html is: <code> <li id="jvcontactwidget-3" class="widget widget_contact"> <div class="title"><h2>Test</h2></div> <form id="jvcontact" name="widget_contact" action="" method="post"> <label class="required" for="email">Email Address (required)</label> <input class="required" type="email" name="email"> <label class="required" for="firstName">First Name (required)</label> <input class="required" type="text" name="firstName"> <label class="required" for="lastName">Last Name (required)</label> <input class="required" type="text" name="lastName"> <label for="question">Any questions for us?</label> <textarea rows="5" name="question"></textarea> <input type="submit" value="Send it" style="display: inline-block; "> </form> <div class="jvloading" style="display: none; "></div> <div id="jvsuccess" style="display: none;" >Thanks for the email</div> <div id="jvmsg" style="display: none; "></div> </li> </code> My js file is like this: <code> jQuery(document).ready(function($) { jQuery('#jvcontact').submit(function() { jQuery('.widget_contact input[type="submit"]').hide(); jQuery('.jvloading').show(); var str = jQuery(this).serialize(); jQuery.ajax({ type: 'POST', url: '/wp-admin/admin-ajax.php', data: 'action=contact_form&'+str, success: function(msg) { //jQuery('#jvmsg').ajaxComplete(function(event, request, settings){ if(msg === 'sent') { console.log('sent'); jQuery('#jvmsg').hide(); jQuery('.jvloading').slideUp(); jQuery('.widget_contact input[type="submit"]').slideUp(); jQuery('#jvcontact').slideUp(); jQuery('#jvsuccess').fadeIn('slow'); } else { console.log('nope'); jQuery('#jvmsg').html(msg); jQuery('.jvloading').hide(); jQuery('.widget_contact input[type="submit"]').show(); jQuery('#jvmsg').fadeIn('slow'); } //}); } }); return false; }); </code> }); My php file: <code> function ajax_contact() { if(!empty($_POST)) { $error = ""; //Check to make sure sure that a valid email address is submitted if(trim($_POST['email']) == '') { $error .= "An email address is required<br/>"; } else if (!eregi("^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,4}$", trim($_POST['email']))) { $error .= "A valid email address is required<br/>"; } else { $email = trim($_POST['email']); } //Check to make sure that the first name field is not empty if(trim($_POST['firstName']) == '') { $error .= "Your first name is required<br/>"; } else { $firstName = trim($_POST['firstName']); } //Check to make sure that the last name field is not empty if(trim($_POST['lastName']) == '') { $error .= "Your last name is required<br/>"; } else { $lastName = trim($_POST['lastName']); } if(trim($_POST['question']) == '') { $question = "They had no questions at this time"; } else { $question = $_POST['question']; } $admin_mail = get_bloginfo('admin_email'); if(empty($error)) { $message = "Someone wants to get in touch with you. \n\n Name: " . $firstName . " " . $lastName . "\n Email: " . $email . "\n Question: " . $question . "\n"; $jvMail = wp_mail($admin_mail, 'Contact from your website', $message); echo "sent"; } else { echo $error; } die(); } } add_action('wp_ajax_contact_form', 'ajax_contact'); </code> Thanks for the help!
|
are you logged-in with all browsers? since <code> add_action('wp_ajax_contact_form', 'ajax_contact'); </code> only works for logged in users, so to fix it you need to change it: <code> add_action('wp_ajax_nopriv_contact_form', 'ajax_contact'); </code> if you want your function to work for visitors as well as users.
|
AJAX Contact Form Issue
|
wordpress
|
Hey Guys, I'm trying to build pagination links for the next/previous cousin page. For example, my page structure is like this: Top Level A a1 a2 B b1 b2 When I'm on a2, I want the 'Previous Page' link to go to a1, but the 'Next Page' link to go to b1 (skipping B). I'm using great Next Page, Not Next Post plugin at the moment, but it can only go to next page (so it would include B in the above example). I'm trying to modify it to only show cousins, but running into some trouble. So far I have this: <code> // query gand parent page level, go to next parent page, and then loop to find it's next child, eke! // get grandparent id $parentInfo = get_page($post->post_parent); // query the level above's pages // $getParentPages = get_pages('child_of='.$parentInfo->post_parent.'&parent='.$parentInfo->post_parent.'&'.$getPagesQuery); $getParentPages = get_pages($getPagesQuery); $parentPageCount = count($getParentPages); for($pp=0; $pp < $parentPageCount; $pp++) { // get the array key for our entry // if ($post->post_parent == $getParentPages[$pp]->ID) break; if ($post->ID == $getParentPages[$pp]->ID) break; } // assign our next key $parentNextKey = $pp+1; if (isset($getParentPages[$parentNextKey])) { $anchorName = $getParentPages[$parentNextKey]->post_title; $output = '<a href="'.get_permalink($getParentPages[$parentNextKey]->ID).'" title="'.$anchorName.'">'; } </code> So how would I make that skip B, and go to b1 and so on? Thanks for the help! -Drew
|
I solved this by getting all pages, assigning them by level, and then getting the next page of the same level. If you also want the previous page then you should probably cache the functionality that groups the pages by level. <code> function wpse16875_next_page_same_level_link() { $next_page_same_level = wpse16875_next_page_same_level(); if ( $next_page_same_level ) { return '<a href="' . get_permalink( $next_page_same_level ) . '">' . get_the_title( $next_page_same_level ) . '</a>'; } return ''; } function wpse16875_next_page_same_level() { $current_page = $GLOBALS['post']; $current_page_level = null; $all_pages = get_pages(); $pages_by_id = array(); $page_ids_by_parent_id = array(); $page_ids_by_level = array(); foreach ( $all_pages as $page ) { $pages_by_id[$page->ID] = $page; if ( ! array_key_exists( $page->post_parent, $page_ids_by_parent_id ) ) { $page_ids_by_parent_id[$page->post_parent] = array(); } $page_ids_by_parent_id[$page->post_parent][] = $page->ID; } foreach ( $all_pages as $page ) { $ancestor_page_id = $page->post_parent; $level = 0; while ( 0 != $ancestor_page_id ) { $ancestor_page_id = $pages_by_id[$ancestor_page_id]->post_parent; $level++; } if ( $page->ID == $current_page->ID ) { $current_page_level = $level; } if ( ! array_key_exists( $level, $page_ids_by_level ) ) { $page_ids_by_level[$level] = array(); } $page_ids_by_level[$level][] = $page->ID; } $current_level_page_ids = $page_ids_by_level[$current_page_level]; $current_page_pos_by_level = array_search( $current_page->ID, $current_level_page_ids ); if ( array_key_exists( $current_page_pos_by_level + 1, $current_level_page_ids ) ) { return $pages_by_id[$current_level_page_ids[$current_page_pos_by_level + 1]]; } return null; } </code>
|
Get next/previous cousin page
|
wordpress
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.