question
stringlengths
0
34.8k
answer
stringlengths
0
28.3k
title
stringlengths
7
150
forum_tag
stringclasses
12 values
We've inherited a customer with a good looking Wordpress site but the previous agency didn't fully implement the "Email This" feature. I mean, their theme has a link for "Email this" on every page but there's nothing underneath it. We've been instructed to make it work. So, the ideal would be for a solution which retains the existing button (which has been styled quite nicely), but just supplies the plumbing work underneath. AFter a quick search for a plug in which will implement this, I found: email2friend WP-Email But it's not clear whether these will add their "own" button to the article (which will presumably not look as nice as the existing themed button) Can we plumb it into our existing button? Also, in each case, can we tweak the mini form it throws up to make it match our theme? Finally, if there's a plug in that's better than either of these two, please advise. Update : Went with WP-Email in the end which was fully featured and easy to configure and as mireille raad said, it was easy enough to tweak the CSS and images to make the button fit our site 100%. The form that came with it immediately picked up the colour scheme and fonts used in our theme, without us having to do anything at all.
well wouldn't it be easier to get any plugin working - then go into plugin folder/code and search for the image it uses and replace it with the nice image/themed one ?
Implementing an "Email this" button?
wordpress
I need to display (for pages that use a particular page template) a list of custom post type objects filtered into 2 sets - those with comments, and those without comments. Each of these sets should display the last 10 of its type (ie the latest 10 posts with comments, and the lastest 10 posts without comments) What's the best way of achieving this? So far, the easiest thing I've come up with is to just do a custom select with $wpdb. Hooking the query and adding a posts_join / posts_where filter doesn't seem like the best answer, as it's too global.
And I should have done some searching before asking. Looks like hooking the query might be the best way of doing this. stackexchange-url ("Here's") a good answer from StackOverflow with practically the same question.
Filter custom posts with / without comments
wordpress
I'm really having a few issues with inserting terms. Here is my scenario: I have a taxonomy called veda_release_type: <code> //Release Type and Region $labels = array( 'name'=&gt; _x('Release Types/Regions', 'taxonomy general name' ), 'singular_name' =&gt; _x('Release Type/Region', 'taxonomy singular name'), 'search_items' =&gt; __('Search Release Types/Regions'), 'popular_items' =&gt; __('Popular Release Types/Regions'), 'all_items' =&gt; __('All Release Types/Regions'), 'edit_item' =&gt; __('Edit Release Type/Regions'), 'edit_item' =&gt; __('Edit Release Type/Region'), 'update_item' =&gt; __('Update Release Type/Region'), 'add_new_item' =&gt; __('Add New Release Type/Region'), 'new_item_name' =&gt; __('New Release Type/Region Name'), 'separate_items_with_commas' =&gt; __('Seperate Release Types/Regions with Commas'), 'add_or_remove_items' =&gt; __('Add or Remove Release Types/Regions'), 'choose_from_most_used' =&gt; __('Choose from Most Used Release Types/Regions') ); $args = array( 'hierarchical' =&gt;true, 'labels' =&gt; $labels, 'query_var' =&gt; true, 'rewrite' =&gt; array('slug' =&gt;'release_type') ); register_taxonomy('veda_release_type', 'veda_release',$args); </code> It's obviously hierchical. Top level contains release types ieDVD, blu-ray. The level under that are regions ie. Region 1, Region 2, etc. So, the Hierarchy that I want is: DVD --Region 0 --Region 1 --Region 2 --Region 3 --Region 4 --Region 5 --Region 6 Blu-Ray --Region A --Region B --Region C I created a function called insert_term in my class to check if a term exists then insert it if it doesn't: <code> public function insert_term ($term, $taxonomy, $args = array()) { if (isset($args['parent'])) { $parent = $args['parent']; } else { $parent = 0; } $result = term_exists($term, $taxonomy, $parent); if ($result == false || $result == 0) { return wp_insert_term($term, $taxonomy, $args); } else { return (array) $result; } } </code> And then I call said function to insert the terms: <code> $dvd = $this-&gt;insert_term('DVD','veda_release_type'); $this-&gt;insert_term('Region 0','veda_release_type',array('parent'=&gt;$dvd['term_id'])); $this-&gt;insert_term('Region 1','veda_release_type',array('parent'=&gt;$dvd['term_id'])); $this-&gt;insert_term('Region 2','veda_release_type',array('parent'=&gt;$dvd['term_id'])); $this-&gt;insert_term('Region 3','veda_release_type',array('parent'=&gt;$dvd['term_id'])); $this-&gt;insert_term('Region 4','veda_release_type',array('parent'=&gt;$dvd['term_id'])); $this-&gt;insert_term('Region 5','veda_release_type',array('parent'=&gt;$dvd['term_id'])); $this-&gt;insert_term('Region 6','veda_release_type',array('parent'=&gt;$dvd['term_id'])); $bd = $this-&gt;insert_term('Blu-Ray', 'veda_release_type'); $this-&gt;insert_term('Region A','veda_release_type',array('parent'=&gt;$bd['term_id'])); $this-&gt;insert_term('Region B','veda_release_type',array('parent'=&gt;$bd['term_id'])); $this-&gt;insert_term('Region C','veda_release_type',array('parent'=&gt;$bd['term_id'])); </code> The problem I'm having is that even though the terms get inputed in the database, they don't show up on the taxonomy page. At most, the top level terms show up. I have to try various things until it sorta forces WordPress to recognize the sublevel terms. Has anyone run into this or can recommend a better way? EDIT: Noticed something else: I tried deleting the terms off the database then deactivating and reactivating the plugin that declares the terms. The two parent terms show up in the terms page, but the child terms do not. The child terms DO show up in the "Parent" drop down menu where you want to create a new term. When I add a term whose parent is one of the child terms and refresh the page, THEN the child terms show up.
The hierarchy is cached and it's not invalidated properly. This is a bug, still unresolved as of WP 3.1. A workaround would be to call <code> delete_option("{$taxonomy}_children"); </code> directly. See the _get_term_hierarchy() function.
Inserting terms in an Hierarchical Taxonomy
wordpress
I'm developing a theme, and there's a section for awards &amp; certifications which will consist of just 4-6 small logos. Is there a way to put these images in a category and then display all of these images on the homepage with a simple code so the client won't have to go into the source code? Thanks.
Technically you can't put images in category, because they are not posts by themselves. You can create Custom Post Type for your images, etc, etc (might be overkill in your case). Personally I like to use Links for such stuff. It is ready-made, easy to add images to (just URL), supports own categories and can be flexibly displayed, with wp_list_bookmarks() or widget. I did a post on such usage of links while back - Make use of Links in WordPress .
Is there Photo Categories?
wordpress
I want implement theme option which will have two css files. Example, if current admin set their profile to blue color I want load blue css for the theme options. <code> if (current-value-css-admin) load blue else load gray </code> Let me know how do I get current data for the wp admin color.
This can be retrieved with <code> $color = get_user_option('admin_color'); </code> , just don't forget to check for empty return and default to something in that case. Native color schemes are called <code> fresh </code> (grey) and <code> classic </code> (blue).
How to get a value for admin css color either gray or blue
wordpress
How can I create a URL to an admin page (under /wp-admin/) that I'm not adding to the navigation? I want to use the URL for an ajax request.
Hey, changed my google search terms and found my answer. :) http://codex.wordpress.org/AJAX_in_Plugins
How to create a wp admin page (for use in an ajax request)
wordpress
Following up from stackexchange-url ("Locked out of my own blog and password reset not working"): After posting the question I decided to give the password reset route one last try and this time the e-mail did come through and I was able to get back into the blog. It took me a total of four attempts to reset the password before it finally worked. Given that the first three e-mails were apparently sent but didn't arrive and the last one arrived very quickly, what should I be looking for in my set up that would cause this feature not to work? Or is this just a feature of e-mail that I must live with? There's been no indication that the e-mails were bounced by my ISP or that they've been marked as spam. My ISP is also my web host and domain name registrar. I'm still running Wordpress 2.9.2 (as I said before it's a very infrequently updated blog and the next task is to upgrade to 3.0.4), but I do remember having this problem before with previous versions.
Unfortunately email can be like that. It works most of the time, but sometimes messages just poof. Especially if email is being sent by some small hosting account (more suspicious) as opposed to large email service (less suspicious). You can try to verify with hosting if emails were really sent, but if they were I don't think you will ever know what happened with them along the way. PS btw maybe it will arrive after all, several times I experienced emails sent earlier stuck somewhere and arrive hours later than newer emails
Why would it take four reset password attempts to finally get the e-mail?
wordpress
I have my own Wordpress installation for my infrequently updated blog. I have a habit of forgetting my password so have to request a new one and reset it every two to three months. I've done it again today and got the "Password Reset" e-mail (which arrives within seconds of requesting it). Following the link to actually reset the password gives me the "Check your e-mail for your new password." page but that e-mail never arrives. I've checked my spam folder and there's nothing in that. What's the quickest way of resetting my password and getting back into my blog? Do I have to go via the database? If so what do I need to reset there? I should add that the blog hasn't been hacked - I've checked the pages and they're all OK. No spurious links or content vandalised.
If you can get to phpMyAdmin (or something equivalent), open the DB and find the wp_users table. Select the appropriate user to edit and change the user_pass field to <code> whatever </code> . Set the function to MD5 and save. You should now be able to log in.
Locked out of my own blog and password reset not working
wordpress
Hey, is it possible that i can put a chunk of code somewhere and it will show up after the more tag seperator but within the post ? I mean if i put more seperator after first paragraph then on post areas after that will show up the code i will put.. probably some html with a twitter and rss link. Help is appreicated :) cheers Ayaz
k i found the answer on researching and modifying a code i found : <code> add_filter('the_content', 'adds_block'); function adds_block($content){ if (is_single()) // return $content; global $post; $thePostID = $post-&gt;ID; $test = '&lt;span id="more-' .$thePostID.'"&gt;&lt;/span&gt;' ; return str_replace($test, ads(), $content); } function ads(){ return 'Your Custom Code,,'; } </code> This will add your code after teh more tag area on the post page.
Text after more tag in posts
wordpress
I am trying to hook into activate_plugin. I know that activate_plugin has 1 required param and 2 optional ones. I am trying to acquire all 3. Here's my setup: <code> // create plugin settings menu add_action('admin_menu', 'pe_create_menu'); function pe_create_menu() { //create new sub-level menu add_submenu_page( 'plugins.php', 'Plugin Settings', 'Plugin Enabler', 'administrator', __FILE__, 'pe_settings_page' ); // Add my hook add_action( 'activate_plugin', 'pe_network_activate', 10, 3 ); } </code> And my function: <code> function pe_network_activate( $plugin, $redirect = '', $network_wide = false ) { $args = var_export( func_get_args(), true); _log("Args: " . $args); // write to the WP error_log } </code> $args returns only the first parameter. How do I get all 3? My goal is to be able to tell when a plugin is being network activated, or just normally activated - hence the need for $network_wide.
The <code> activate_plugin() </code> function accepts three parameters, but it emits the <code> activate_plugin </code> action with only one parameter. This can be confusing, but hooks sometimes use the same name as the function they come from, without passing the same parameters. One way to get the difference between a network activation and a regular activation is to monitor the <code> update_site_option </code> and <code> update_option </code> hooks. Only one of them will fire, depending on the <code> $network_wide </code> parameter of <code> activate_plugin() </code> .
How to get all of the activate_plugin action parameters?
wordpress
I'm using CMS Press for custom post types. The issue is the feed doesn't validate because lastBuildDate is blank. I am not using WordPress's default posts for anything and that is causing the problem. I did a test post using WordPress's default post and voila lastBuildDate was filled in and the feed validated. As soon as I deleted the post it removed the date in lastBuildDate and the feed didn't validate. I'm using the code below to add the custom post types in the main feed but this is an issue with the feeds created by the custom post types also. Am I missing something to get the lastBuildDate to populate? <code> if ( ( is_front_page() &amp;&amp; false == $query-&gt;query_vars['suppress_filters'] ) || is_feed() ){ $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; query_posts( array('post_type'=&gt;array('post', 'games', 'entertainment', 'tech', 'podcasts'),'paged'=&gt;$paged ) ); } </code> I answered my own question below.
This is the solution I found based off of @Rarst's answer. Put this in the themes functions.php and it worked like a charm! <code> add_filter('get_lastpostmodified', 'my_lastpostmodified'); function my_lastpostmodified() { global $wpdb; $add_seconds_server = date('Z'); return $wpdb-&gt;get_var("SELECT DATE_ADD(post_modified_gmt, INTERVAL '$add_seconds_server' SECOND) FROM $wpdb-&gt;posts WHERE post_status = 'publish' ORDER BY post_modified_gmt DESC LIMIT 1"); } </code>
Custom post types - RSS lastBuildDate issue
wordpress
Wanted to know if there was any documentation or plugins that allowed a site to pull prices and other information from Amazon.com on DVD's and other products. I'm creating a plugin that stores information about DVD releases and I would like to create code that pulls the price from Amazon, and calculates the difference compared the MSRP and of course provide a link to the Amazon page for purchase. I do know that much of Amazon's API revolves around the product's Amazon ID number, so I know I'll have to story it with the custom post type associated with the release. Has this been done before?
You're looking for something a little more advanced than a simple affiliate integration. Unfortunately, I don't thing there's an existing plug-in solution for the kind of interaction you're trying to achieve. That said, it should still be possible. A cursory search turned up Amazon's Product Advertising API , which seems to be exactly what you'll need. It provides directly programmatic access to the Amazon product database, meaning you can find (and cache) product information and prices fairly easily. You can use this to power a local search of the Amazon database for products or just retrieve information specific to a product based on a known Amazon ID. It's up to you, and I encourage you read through the documentation and see if this is the right platform.
Amazon.com intergration with WordPress?
wordpress
I've recently started using the Hikari Hooks plugin for Wordpress as it seems to allow you to get a good idea of what do_actions are being called on the page, so that you can easily find out where potential hooks for plugin code might lie. Are there better tools/plugins for accomplishing the same thing? In particular I was looking for one that might notify me of post status transition actions such as stackexchange-url ("new_to_publish and draft_to_publish")...It appears that Hikari Hooks does notify you of such changes but not that they are available, only if you're already added them as an action.
It is usually easy to find most hooks in documentation or source. It can be much more tricky for hooks that are dynamically generated, like post transitions. Essentially it doesn't exist in source as specific hook - it is hook that is getting generated dynamically at runtime, depending on variables. <code> do_action("${old_status}_to_$new_status", $post); do_action("${new_status}_$post-&gt;post_type", $post-&gt;ID, $post); </code> At local test stack I often just add <code> var_dump() </code> on variables to source code to see what is going on. Dirty, but easy and fast. Obviously highly not recommended for production environment.
Good tools for locating hooks in a wordpress page/admin interface/blog post?
wordpress
I'm really stuck on this - this follows on from this post: stackexchange-url ("How to override parent functions in child themes") I can't figure out how to override Twenty Ten's set_post_thumbnail_size() function. I've put my code below for the other overrides I'm doing, but nothing happens when I add this to my function twentyten_child_theme_setup(): <code> set_post_thumbnail_size( array(100,100) , array("class" =&gt; "alignleft post_thumbnail"), true ); </code> I'm inserting the thumbnail in my loop like this: <code> &lt;?php if ( function_exists("has_post_thumbnail") &amp;&amp; has_post_thumbnail() ) { the_post_thumbnail(array(100,100), array("class" =&gt; "alignleft post_thumbnail")); } else { ?&gt; &lt;img src="&lt;?php echo bloginfo('stylesheet_directory'); ?&gt;/images/thumb-default.jpg" alt="thumb-default" width="100" height="100" /&gt; &lt;?php } ?&gt; </code> Here's my function below - can anyone help me override this pesky function? Thanks, osu <code> function twentyten_child_theme_setup() { // OVERRIDE SIDEBAR GENERATION! function osu_twentyten_widgets_init() { // Siedbar 1, located on LHS sidebar register_sidebar( array( 'name' =&gt; __( 'Primary Widget Area', 'twentyten-child' ), 'id' =&gt; 'primary-widget-area', 'description' =&gt; __( 'The primary widget area where the navigation goes', 'twentyten-child' ), 'before_widget' =&gt; '&lt;li id="%1$s" class="widget-container %2$s"&gt;', 'after_widget' =&gt; '&lt;/li&gt;', 'before_title' =&gt; '&lt;h3 class="widget-title"&gt;', 'after_title' =&gt; '&lt;/h3&gt;', ) ); // Area 2, located on RHS sidebar register_sidebar( array( 'name' =&gt; __( 'Secondary Widget Area', 'twentyten-child' ), 'id' =&gt; 'secondary-widget-area', 'description' =&gt; __( 'The secondary widget area', 'twentyten-child' ), 'before_widget' =&gt; '&lt;li id="%1$s" class="widget-container %2$s"&gt;', 'after_widget' =&gt; '&lt;/li&gt;', 'before_title' =&gt; '&lt;h3 class="widget-title"&gt;', 'after_title' =&gt; '&lt;/h3&gt;', ) ); } /* Deregister sidebar in parent */ remove_action( 'widgets_init', 'twentyten_widgets_init' ); /** Register sidebars by running twentyten_widgets_init() on the widgets_init hook. */ add_action( 'widgets_init', 'osu_twentyten_widgets_init' ); // OVERRIDE EXCERPT READ MORE LINK function osu_readon_link() { return ' &lt;a href="'. get_permalink() . '" class="readmore"&gt;' . __( 'Read More', 'twentyten-child' ) . '&lt;/a&gt;'; } // Function to override function osu_twentyten_custom_excerpt_more( $output ) { if ( has_excerpt() &amp;&amp; ! is_attachment() ) { $output .= osu_readon_link(); } return $output; } remove_filter( 'get_the_excerpt', 'twentyten_custom_excerpt_more' ); add_filter( 'get_the_excerpt', 'osu_twentyten_custom_excerpt_more' ); } /* IMPORTANT: Run the code for parent function overrides (involving hooks and filters) after theme setup! */ add_action( 'after_setup_theme', 'twentyten_child_theme_setup' ); </code>
What exactly do you mean by nothing happens ? Technically you don't need to remove <code> set_post_thumbnail_size() </code> , as I understand from code - simply making your own call later will overwrite size. There are two ways you can handle this: Adjust your setup function to later priority. Child theme is processed before parent theme. So when you hook with default priority - setup functions are also executed in that order. So <code> add_action( 'after_setup_theme', 'twentyten_child_theme_setup', 11 ); </code> Plug your own <code> twentyten_setup() </code> function. It is wraped in <code> if ( ! function_exists( 'twentyten_setup' ) ) </code> condition in Twenty Ten. So simply copy it to your theme and make changes you need - your version will run instead of original one.
How to remove set_post_thumbnail_size() in child themes?
wordpress
Really rusty on the wordpress front. I am using custom permalinks <code> /%category%/%postname%/ </code> as well as the <code> WP No Category Base </code> plugin, so my urls look like this: http://www.url.com/parent_category/child_category/ I only have an index.php set up at the moment, with the most basic loop possible: <code> &lt;?php if (have_posts()) : ?&gt; &lt;?php query_posts(); ?&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;div class="post"&gt; &lt;?php the_title(); ?&gt; &lt;br /&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php else: ?&gt; &lt;?php endif;?&gt; </code> The problem is, all posts are coming through, instead of just the posts in the category represented by the url. I didn't think I needed a custom query, because the link that took me to the particular url should have been carried across. What am I missing?
The <code> &lt;?php query_posts(); ?&gt; </code> in your code is causing the global query to be reset to show all posts instead of the one set by your rewrite rules. You should remove that line.
Category links including all posts
wordpress
My client wants to implement a special appearance to each of our category pages. Kind of like child themes... she wants to shift the background image, change a few graphics, and tweak the colors according to which category the user is visiting (horror, romance, etc). Is there a reasonable way to do this besides creating a different template for each page with imported CSS styles? Or is that really the only path to accomplish this? UPDATE: The answers below are all great. For our purposes, the easiest thing to do was to use the category specific classes provided by "body_class()" to override current styles. Thanks!
If changes do not require modifications to HTML markup you can accomplish that by loading conditionally additional CSS style files. See Conditional Tags > A Category Page and <code> wp_enqueue_style() </code> in Codex.
Category specific themes?
wordpress
Basically that's the question - I wonder if <code> set_transient() </code> overwrites/updates a transient option with the same key?
Yes, key (prefixed with string identifying it as transient) is used as option name when value is inserted in database.
Does set_transient() overwrite/update transient option with same key?
wordpress
I want to list categories belonging to a parent. The problem is using category id's isn't useful and makes things harder to understand. Is there any easier way to list categories belonging to a parent, similar to the default way supplied in the WP codec? <code> &lt;?php wp_list_categories('child_of=8'); ?&gt; //what category is '8' ?! &lt;?php wp_list_categories('child_of=clients'); ?&gt; //much nicer, but doesn't work </code> I would prefer to avoid using another query in the loop, but to make sense to other developers, I might have to.
You can get ID from slug quite easily: <code> $category = get_category_by_slug( 'clients' ); wp_list_categories('child_of='.$category-&gt;term_id); </code>
Listing Category 'child_of' by slug rather than ID
wordpress
What function will display custom taxonomies associated with a post as text? I'm currently using get_the_term_list which works great for a singular page but not so much when using a taxonomy in the archive-postype.php permalink title tag.
wp_get_object_terms() returns the terms associated with an object (eg a post or a page or custom post) as text (normally in an array). From the Codex page for wp_get_object_terms() <code> $productcategories = wp_get_object_terms($post-&gt;ID, 'productcategories'); </code>
get_the_term_list without links in 3.1
wordpress
I'm trying to create a fallback method when ZipArchive is not present. I'm seeking to use the _unzip_file_pclzip() function contained in wp-admin/includes/file.php However, I'm not sure what is expected for the $needed_dirs argument. My target folder for the zip will be the "styles" folder under my theme folder, so the path would be "wp-content/themes/mytheme/styles/" Is that what's expected for $needed_dirs? <code> function openZip($file_to_open) { global $wp_filesystem;//required if _unzip_file_pclzip is used directly global $target; if(class_exists('ZipArchive')) { $zip = new ZipArchive(); $x = $zip-&gt;open($file_to_open); if($x === true) { $zip-&gt;extractTo($target); $zip-&gt;close(); unlink($file_to_open); } else { die("There was a problem. Please try again!"); } } else { $needed_dirs = array(); _unzip_file_pclzip($file_to_open, $target, $needed_dirs); } } </code>
@Scott B I have not tested this script, taken from inlcudes/file.php -> line 559 <code> _unzip_file_pclzip </code> assumes WP_Filesystem() has already been called, so you need to set up <code> global $wp_filesystem </code> <code> global $wp_filesystem; $needed_dirs = array(); $target = trailingslashit($target); // Determine any parent dir's needed (of the upgrade directory) if ( ! $wp_filesystem-&gt;is_dir($target) ) { //Only do parents if no children exist $path = preg_split('![/\\\]!', untrailingslashit($target)); for ( $i = count($path); $i &gt;= 0; $i-- ) { if ( empty($path[$i]) ) continue; $dir = implode('/', array_slice($path, 0, $i+1) ); if ( preg_match('!^[a-z]:$!i', $dir) ) // Skip it if it looks like a Windows Drive letter. continue; if ( ! $wp_filesystem-&gt;is_dir($dir) ) $needed_dirs[] = $dir; else break; // A folder exists, therefor, we dont need the check the levels below this } } </code>
What should I pass for $needed_dirs when calling _unzip_file_pclzip (aka PclZip)?
wordpress
publish_post Runs when a post is published, or if it is edited and its status is "published". Action function arguments: post ID. - Plugin API Documentation I've added the publish_post hook to a WordPress plugin that I'm writing. The function called by the hook itself, is meant to change the categories of several posts using the wp_update_post function. This hook does not work however as the result returned from running wp_update_post is always 0. My best guess is that running wp_update_post causes another instance of my hook to run because it re-publishes the post...which I believe brings about the "...or if it is edited and its status is "published"" of the statement above. Is there any other action-hook that I can use that will only be called when the post added is completely new and not edited? <code> &lt;?php /* Plugin Name: Category Switcher Plugin Plugin URI: http://www.example.com Description: When a new post is created this plugin will cause the Version: 0.1 Author: Me License: GPL2 ?&gt; &lt;?php class categoryShifter { function shiftCategories($post_ID) { $maxNumPostsFirstTeir = 4; $first_teir_cat = "Fresh News Stories 1"; $second_teir_cat = "Slightly Dated Stories 2"; $firephp = FirePHP::getInstance(true); $firephp-&gt;info('BEGIN: categoryShifter.shiftCategories()'); $firephp-&gt;log($post_ID, 'post_ID: '); $firephp-&gt;trace('trace to here'); $first_teir_id = categoryShifter::getIDForCategory($first_teir_cat, $firephp); $second_teir_id = categoryShifter::getIDForCategory($second_teir_cat, $firephp); $firephp-&gt;log($first_teir_id, '$first_teir_id'); $firephp-&gt;log($second_teir_id, '$second_teir_id'); $qPostArgs = array( 'numberposts' =&gt; 100, 'order' =&gt; 'DESC', 'orderby' =&gt; 'post_date', 'post_type' =&gt; 'post', 'post_status' =&gt; 'published', 'category_name' =&gt; $first_teir_cat ); $firstTeirPosts = get_posts($qPostArgs); $firephp-&gt;log($firstTeirPosts, 'got posts:'); $firephp-&gt;log(sizeof($firstTeirPosts), 'sizeof'); // NOTE: This appears to work. for($i = sizeof($firstTeirPosts)-1; $i &gt; $maxNumPostsFirstTeir-4; $i--) { $newCats = array($second_teir_id); $editingId = $firstTeirPosts-&gt;ID; $result = wp_set_post_categories($editingId, $newCats); /* NOTE: Doesn't work presently... returns an array with the $second_teir_id in it. */ $firephp-&gt;log($result, 'Result'); } /* $my_post = array(); $my_post['ID'] = 132; $my_post['post_category'] = array($second_teir_id); $firephp-&gt;log('Before', 'Before'); if(wp_update_post( $my_post ) == 0) { $firephp-&gt;Error('Fatal Error, Post not updated', 'error'); } $firephp-&gt;log('After', 'After'); */ return $post_ID; } function getIDForCategory($cat_name, $logger) { $logger-&gt;Info("Begin: getIDForCategory()"); $cats = get_categories(); $whichCatId = ""; foreach($cats as $single_cat) { if($single_cat-&gt;name == $cat_name) { $whichCatId = $single_cat-&gt;term_id; break; } } $logger-&gt;Info("End: getIDForCategory()"); return (int)$whichCatId; } } /* Hook Post Creation */ /* add_action('publish_post', array('categoryShifter','shiftCategories')); */ add_action('wp_insert_post', array('categoryShifter', 'shiftCategories')); ?&gt; </code> I've switched to using the wp_insert_post hook for the time being...but I still can't get the wp_set_post_categories function to change the categories of the posts. I understand that I will probably need to update this code so that it takes into account the existing categories of the post and only modifies the ones specified by the plugin, but for now it's really just an alpha.
<code> add_action('new_to_publish', 'your_function'); add_action('draft_to_publish', 'your_function'); add_action('pending_to_publish', 'your_function'); </code>
add_action hook for completely new post?
wordpress
I found a question about magazine style front pages that queries always only 1 post (or custom_post_types, etc.) from a whole load of different categories, tags or custom taxonomies. I thought about this for a while and came with something like this as a start. <code> function pre_saved_posts() { if ( ! is_admin() OR ! current_user_can( 'edit_posts' ) ) return; global $post; // Option-Name $opt_name = 'theme_post_ids'; // get data from DB $db_option_value = get_option( $opt_name ); // If there's nothing in the DB, create an array, else add the ID to the array of post_IDs empty( $db_option_value ) ? $post_ids = array( $post-&gt;ID ) : $post_ids .= $post-&gt;ID; // get posts $posts = get_posts( array( 'include' =&gt; $post_ids ) ); // DB-Option @Option-Table updaten or add empty( $db_option_value ) ? add_option( $opt_name, $posts ) : update_option( $opt_name, $posts ); } // Do it when a post is updated add_action( 'save_post', 'pre_saved_posts', 20 ); </code> Would be displayed like this: <code> $some_posts = get_option( 'theme_post_ids' ); foreach ( $some_posts as $post ) { // possible for ex.: $post-&gt;ID, $post-&gt;post_content, $post-&gt;post_title, etc. } </code> It's not tested and only an example, but maybe there's someone interested in extending this. I still question myself how much sense it makes, but i could imagine that there's one large multidimensional array that contains subarrays for different requests ex. <code> $some_posts = get_option( 'theme_post_ids' ); $home_posts = $someposts['home']; </code> If this would be stored in a <code> global $var </code> , maybe there could be some performance increase. Ideas/Suggestions/Whatever?
Hi @kaiser: Consider using the Transients API instead, that's what it is built for. http://codex.wordpress.org/Transients_API
pre saved posts query from db options table
wordpress
I need to obtain a reference to the $wp_filesystem object. In the test below, the var_dump($wp_filesystem) returns NULL. What additional files are required in order to properly set up $wp_filesystem? I was expecting that since its called in file.php, loading that file would be sufficient to load the object. <code> &lt;?php require('../../../wp-blog-header.php'); require('../../../wp-admin/includes/file.php'); $mytest = somefunction(); function somefunction() { global $wp_filesystem; var_dump($wp_filesystem); return; } ?&gt; </code> UPDATE: I've found that I can call WP_Filesystem() directly to create it, so I'm getting the zip extracted fine, now the problem is that the zip file is copied to the destination folder rather than deleted as my ZipArchive method does. <code> require('../../../wp-blog-header.php'); require('../../../wp-admin/includes/file.php'); function openZip($file_to_open) { global $target; global $wp_filesystem; if(class_exists('ZipArchive')) { $zip = new ZipArchive(); $x = $zip-&gt;open($file_to_open); if($x === true) { $zip-&gt;extractTo($target); $zip-&gt;close(); unlink($file_to_open); } else { die("There was a problem. Please try again!"); } } else { WP_Filesystem(); $my_dirs = ''; //What should this be? I'm already passing he $target directory _unzip_file_pclzip($file_to_open, $target, $my_dirs); } } </code>
<code> $wp_filesystem </code> is a global variable containing the instance of the (auto-)configured filesystem object after the filesystem "factory" has been run. To run the factory "over" the global variable (so to set it), just call the <code> WP_Filesystem() </code> function which is, guess what, undocumented in codex . At least the docblock contains some information and you can read the sourcecode (if that's an option for you). Anyway, I would give it a try to add a function call to your code after requiring the file.php from the <code> /wp-admin/includes </code> directory. Probably this already solves your issue. If you are looking for a (better) file-system abstraction than/next to the built-in one, consider the file-system objects in SPL which is part of PHP already.
$wp_filesystem returns NULL. What are the dependencies?
wordpress
I just converted a site to a multisite setup using WordPress 3.0.4. One thing I found in a hurry is that if I wanted to edit a theme's code, the changes would be reflected on all the subsites that use the same theme. Is there a to customize the code so that only a certain subsite receives the changes??
If it is just css customizations, use this plugin: http://wordpress.org/extend/plugins/safecss/ It's what wp.com uses for their css upgrade. If you have to edit the php, make a copy of the theme with a new name on the theme folder and in style.css.
Customizing 1 theme for multiple blogs in a multisite setup
wordpress
I am looking to display different content after a user registers. Is there a way to find out the registration date and then if it's been 1 day display one thing, but if it's been 2 days display something else? Something like this, but based on the registration date and not a post entry date: <code> &lt;?php if (strtotime($post-&gt;post_date) &gt; strtotime('-30 days')): ?&gt; //Text for posts created in the last 30 days &lt;?php endif; ?&gt; </code>
Yes you can! <code> &lt;?php get_currentuserinfo(); $user_data = get_userdata($user_ID); $registered_date = $user_data-&gt;user_registered; if (strtotime($registered_date) &gt; strtotime('-30 days')){ //Text for users registered in the last 30 days } ?&gt; </code> hope this helps
Find out when a user was created and display varied content depending on time since creation
wordpress
I want implement upload logo to my theme option page. Currently I follow this code What I have done for now load a related jquery for the media upload <code> function load_only() { add_thickbox(); wp_enqueue_script('jquery-option', get_template_directory_uri() . '/admin/js/jquery.option.js', array('jquery','media-upload','thickbox','jquery-ui-core','jquery-ui-tabs'), '1.0'); } </code> Question How to implement the upload form using existing media upload? <code> &lt;input id="theme_options_upload" type="text" name="theme_options_upload" value="&lt;?php esc_attr_e( $options['theme_options_upload'] ); ?&gt;" /&gt; &lt;input type="button" name="just_button" value="&lt;?php esc_attr_e('Upload'); ?&gt;" /&gt; </code> I want to know How to link the button to <code> media-upload.php </code> After we upload image and click <code> Insert into Post </code> button on media-upload the image will place into field <code> name="theme_options_upload" </code> Let me know.
You are most likely to save the url of the image and not the whole image tag, and there is a great tutorial that explains just how to use the media uploader in your own theme or plugin: http://www.webmaster-source.com/2010/01/08/using-the-wordpress-uploader-in-your-plugin-or-theme/ update In case of using this in a meta box you will need the post id so change the js code from: <code> jQuery('#upload_image_button').click(function() { formfield = jQuery('#upload_image').attr('name'); tb_show('', 'media-upload.php?type=image&amp;amp;TB_iframe=true'); return false; }); </code> to <code> jQuery('#upload_image_button').click(function() { formfield = jQuery('#upload_image').attr('name'); post_id = jQuery('#post_ID').val(); tb_show('', 'media-upload.php?post_id='+post_id+'&amp;amp;type=image&amp;amp;TB_iframe=true'); return false; }); </code>
How to use media upload on theme option page?
wordpress
I want a more elegant way to express the following redirect: <code> RewriteCond %{REQUEST_URI} ^/blog/2008/(.*) [NC, OR] RewriteCond %{REQUEST_URI} ^/blog/2009/01/(.*) [NC, OR] RewriteCond %{REQUEST_URI} ^/blog/2009/02/(.*) [NC, OR] RewriteCond %{REQUEST_URI} ^/blog/2009/03/(.*) [NC, OR] RewriteCond %{REQUEST_URI} ^/blog/2009/04/(.*) [NC, OR] RewriteCond %{REQUEST_URI} ^/blog/2009/05/(.*) [NC, OR] RewriteCond %{REQUEST_URI} ^/blog/2009/06(.*) [NC] RewriteRule . http://example.com/blog/? [R=301,L] </code> Ideally, I'd like to use <code> wp_safe_redirect </code> or <code> wp_redirect </code> . The problem with that, however, is that those pages have already been deleted from within WP. Is this possible to do internally, if the posts have been deleted entirely from the DB?
It is no problem that the posts are already gone, we will hook into WP before it queries the database. First we set up our rewrite rules, which will set a special query variable (that we must declare public), and then, in the <code> parse_request </code> action, we check for that variable and redirect if it is set. <code> add_action( 'init', 'wpse8236_init' ); function wpse8236_init() { // This is case-sensitive, we can't set regex flags // Replace `blog` with `[Bb][Ll][Oo][Gg]` to make it case-insensitive add_rewrite_rule( 'blog/2008/', 'index.php?wpse8236_redirect=true', 'top' ); add_rewrite_rule( 'blog/2009/0[1-6]/', 'index.php?wpse8236_redirect=true', 'top' ); } add_action( 'query_vars', 'wpse8236_query_vars' ); function wpse8236_query_vars( $query_vars ) { $query_vars[] = 'wpse8236_redirect'; return $query_vars; } add_action( 'parse_request', 'wpse8236_parse_request' ); function wpse8236_parse_request( &amp;$wp ) { if ( array_key_exists( 'wpse8236_redirect', $wp-&gt;query_vars ) ) { wp_redirect( '/blog/' ); exit(); } </code>
Date based redirects of posts that no longer exist
wordpress
I need to grab a list of current events. The events have a start and end date so I need to be able to select a range as opposed to just getting any list of events that have an end date that is after today's date. Does anyone have any suggestions as to how to do this? (from what I've read there doesn't seem to be a way to use multiple "meta_key" and "meta_compare" values, but there must be a way some how) Here's an example of what I'm using in my arguments, but I need to also do this for the start date as well: <code> 'meta_key' =&gt; 'end_date_value', 'meta_compare' =&gt; '&gt;', 'meta_value' =&gt; $todaysDate, </code>
You can use your current code to create the query and then in your loop run a check before displaying the events something like <code> &lt;?php query_posts('meta_key' =&gt; 'end_date_value', 'meta_compare' =&gt; '&gt;', 'meta_value' =&gt; $todaysDate); while ( have_posts() ) : the_post(); $post_custom = get_post_custom($post_id); if ($startDate &lt; $post_custom['start_date_value']){ //your loop here } } </code> ?> keep in mind that this is not well coded way to do this ,I would probably create a better sql query or use "posts_where" hook. but its a start
How to get events using multiple custom meta fields?
wordpress
When I call the WordPress unzip_file() function below, instead of actually extracting the zip, it merely moves it into the target folder. When I trace $file and $to from includes/file.php I get: <code> file: C:\xampplite\htdocs\testsite/wp-content/themes/mytheme/styles/myzip.zip To: C:\xampplite\htdocs\testsite/wp-content/themes/mytheme/styles/ </code> What am I missing? <code> &lt;?php require('../../../wp-blog-header.php'); require('../../../wp-admin/includes/file.php'); ?&gt; &lt;?php if (!is_user_logged_in()){ die("You Must Be Logged In to Access This"); } if( ! current_user_can('edit_files')) { die("Oops sorry you are not authorized to do this"); } ?&gt; &lt;form enctype="multipart/form-data" action="" method="post"&gt; &lt;input type="file" name="fupload" /&gt;&lt;br /&gt;&lt;br /&gt; &lt;input type="submit" value="Install" onclick="doLoader();" /&gt; &lt;/form&gt; &lt;?php if(isset($_FILES['fupload'])) { $filename = $_FILES['fupload']['name']; $source = $_FILES['fupload']['tmp_name']; $type = $_FILES['fupload']['type']; $name = explode('.', $filename); $target = TEMPLATEPATH.'/styles/'; // permission settings for newly created folders $chmod = 0755; $saved_file_location = $target . $filename; if (move_uploaded_file($source, $saved_file_location)) { unzip_file($saved_file_location, $target); } else { die("There was a problem with the upload. Plese verify you have uploaded a valid zip file"); } } ?&gt; </code>
Do you have a filesystem and setup that allows for direct access? If the filesystem object is expecting FTP credentials, then you may not get the results you're looking for without giving it the right username/password/server information.
Anyone using unzip_file successfully? It uploads the zip but doesn't extract it!
wordpress
This code is working fine, just want to make sure I'm ok with hardcoding the href to the category edit screen with... <code> "edit-tags.php?action=edit&amp;taxonomy=category&amp;post_type=post&amp;tag_ID='.$cat_id.'" </code> Or is there a method I should call to get the category edit link dynamically (in case the call ever gets changed)? <code> //add the filter in order to add custom columns to the category manager add_filter('manage_category_custom_column', 'display_cat_columns', 10, 3); //This function outputs the custom category image onto each row of the category manager grid. function display_cat_columns($arg1, $column_name, $cat_id){ if ('ce4_cat_image' == $column_name) { return '&lt;a href="edit-tags.php?action=edit&amp;taxonomy=category&amp;post_type=post&amp;tag_ID='.$cat_id.'"&gt;get_category_thumbnail_admin($cat_id, 'thumbnail').'&lt;/a&gt;';} } </code>
The function which is used internally (since 3.1) is <code> get_edit_term_link( $term_id, $taxonomy, $object_type = '' ) </code> . Source view here . There's also a function called <code> edit_term_link </code> that will format the link output for you. The built-in functions are probably better to use, because they check for user capabilities, etc., and are better for future compatability. That said, I think you're safe using the hardcoded url for backwards compatability. I don't know how it was done in previous versions, and I think those links might have been hardcoded like you're doing... Edit: I was curious what was done before that function was introduced, so I looked through the source. Prior to 3.1, <code> get_edit_tag_link( $tag_id, $taxonomy = 'post_tag' ) </code> did the same thing - now it's just rewritten to use <code> get_edit_term_link </code> internally. So if you want to support all recent versions of WordPress, use this function: <code> //add the filter in order to add custom columns to the category manager add_filter('manage_category_custom_column', 'display_cat_columns', 10, 3); //This function outputs the custom category image onto each row of the category manager grid. function display_cat_columns($arg1, $column_name, $cat_id){ if ('ce4_cat_image' == $column_name) { if (function_exists ('edit_term_link')) return edit_term_link( get_category_thumbnail_admin($cat_id, 'thumbnail'), '', '', $cat_id, false ); else return '&lt;a href="'.get_edit_tag_link($cat_id, 'category').'"&gt;'. get_category_thumbnail_admin($cat_id, 'thumbnail').'&lt;/a&gt;'; } } </code>
Adding fields to category manager. Does a method exist to get the link to the category edit screen?
wordpress
I have this function: <code> function get_image_link( &amp;$post ) { $image_link_meta = get_post_meta( $post-&gt;ID, 'as_link_to_image', true ); $image_link_from_post = ''; if ( function_exists( 'has_post_thumbnail' ) &amp;&amp; has_post_thumbnail( $post-&gt;ID ) ) { $attachment_image_link = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), full ); } if ( $attachment_image_link[0] ) $image_link_from_post = $attachment_image_link[0]; if( !empty( $image_link_meta ) ) $final_image_link = $image_link_meta; elseif( !empty( $image_link_from_post ) ) $final_image_link = $image_link_from_post; else $final_image_link = WP_PLUGIN_URL . '/link/to/no-image.png'; return $final_image_link; } } </code> Any idea why <code> $image_link_from_post </code> isn't getting a value?
This should be able to return the url of the large image. <code> $largeImg = wp_get_attachment_link( $attachment_id, 'large', false ); </code> There's also this incase that doesn't work. <code> wp_get_attachment_image_src( $attachment_id, 'large' ); </code>
Get the url of the full sized attachment image using post ID?
wordpress
I have a large menu containing 10 parent items with roughly 7 child items each that I am trying to build using the WP-admin > Appearance > Menus. I have nearly all the menu items added but now my wp-admin backend won't save the menu, it keeps timing out and just ending on a blank screen. I have about 4 more items left to enter but I can't save the menu anymore. I have tried increasing the php memory in wp-config.php by adding define('WP_MEMORY_LIMIT', '64M'); but it made no change. Any tweaks or tips to help me get this menu saved, this is the only thing holding the site up and the client is waiting. Thanks very much! maikunari
You can always try to split your menu into 2 separate menus and then just display them next to each other in your theme. It's far from perfect and doesn't help a bit in understanding the root of your problem but it could help. You can use it as temporary workaround to GTD before deadline and then dig deep into memory issues or whatever causes your trouble...
Large WP 3.0 menu times out and won't save
wordpress
I was just looking at wp_update_term and haven't found any possibility to update the "name" of the term. My scenario is pretty simple: I got some predefined taxonomy terms in a config file like this (just an example): <code> $taxonomy_terms = array( 'taxonomy_a' =&gt; array( 'term_a', 'term_b', 'term_c' ) ,'taxonomy_b' =&gt; array( 'term_d', 'term_e', 'term_f' ) ); </code> Now i'm trying to update these terms based on their id. So if the id exists, i change just the name. But here does my problem start: wp_update_term doesn't offer any possibility to update the name of term... Does anybody know of some work around, or do i just oversee something? Thanks!
According to <code> wp_update_term() </code> in Codex you pass fields you want to override in <code> $args </code> argument, try passing <code> name </code> in there?
wp_update_term: How could i update the "name"?
wordpress
Is there anyway to assign all new posts that have a custom post_type to a specific category? For example, say I have a post_type that is for Actors. Is there anyway to assign any post that is under Actors to a "People" category? (but without displaying the Category box in the WordPress Admin)
you can first remove the category meta box from Actors post type edit screen like this <code> function remove_custom_taxonomy() { remove_meta_box( 'categorydiv', 'custom_post_slug', 'side' ); } add_action( 'admin_menu', 'remove_custom_taxonomy' ); </code> then create a function that will add the category on save_post <code> function default_category($post_id){ // check autosave if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return $post_id; } // check for post type if ('Actors' == $_POST['post_type']) { $Default_category_id = '23'; wp_set_post_terms( $post_id,$Default_category_id , 'category', ture ); } } </code> hope this helps
Anyway to assign custom post types to a specific category?
wordpress
How can I make oEmbed work on the excerpt field so I only have to paste the youtube url in there and then be able to echo 'get_the_excerpt()'? I also want to filter oEmbed and change the wmode but I think I found a solution for that here: http://code.hyperspatial.com/all-code/wordpress-code/oembed-wmode/ EDIT: Crap! I was wrong, it doesn't work at all, nothing happens. Anyone got a better solution?
Not entirely sure it is supposed to be used like this, but by analogue with <code> the_content </code> try this: <code> add_filter('the_excerpt', array($wp_embed, 'autoembed'), 9); </code>
Making oEmbed work on the excerpt field
wordpress
I'm working on using the WP API to insert posts via AJAX. What's the proper way of adding tags dynamically to a custom post type? These tags would not be predefined, but rather be created on demand by the user. Currently I'm doing this: <code> $tags = explode(" ", $_POST['post_tags']); $new_entry = array( 'post_title' =&gt; $_POST['post_title'], 'post_content' =&gt; $_POST['post_content'], 'post_status' =&gt; 'publish', 'post_author' =&gt; $current_user-&gt;ID, 'post_type' =&gt; 'customposttype', 'post_tags' =&gt; $tags); $created = wp_insert_post( $new_entry ); </code> (Yes, this is prototype code and I'm not sanitizing input yet :))
Hi @James: If you have the post ID of your newly created post (the <code> $created </code> variable from your question) you use the <code> wp_set_object_terms() </code> function, for example: <code> wp_add_post_tags($created,'My First Tag'); wp_add_post_tags($created,'My Second Tag'); wp_add_post_tags($created,'My Third Tag'); </code>
Creating tags via API
wordpress
(Since my custom post type is a little long, I've for the sake of simplicity, copied over a dummy one) What I am trying to do is, say I describe a few "similar" variables, i.e. price1, price2, price3, etc. would I be able to stack those values in a single column (as opposed to showing it over 3 columns), i.e. <code> $price1&lt;br /&gt;$price2&lt;br /&gt;$price3 </code> ? The reasons are purely aesthetic as the custom post type columns would get really crowded quickly otherwise. Thank you! (like said, the part below isn't the actual code I'm using, but I thought it would be good if someone else would be searching the same thing) <code> add_filter("manage_edit-product_columns", "prod_edit_columns"); add_action("manage_posts_custom_column", "prod_custom_columns"); function prod_edit_columns($columns){ $columns = array( "cb" =&gt; "&lt;input type=\"checkbox\" /&gt;", "title" =&gt; "Product Title", "description" =&gt; "Description", "price1" =&gt; "Price1", "catalog" =&gt; "Catalog", ); return $columns; } function prod_custom_columns($column){ global $post; switch ($column) { case "description": the_excerpt(); break; case "price": // Now here I have to define the field, but how would I drag in other subsequent price fields? $custom = get_post_custom(); echo $custom["price"][0]; break; case "catalog": echo get_the_term_list($post-&gt;ID, 'catalog', '', ', ',''); break; } } </code>
yea you can do just that. you only need to change the output function which in this case is <code> function prod_custom_columns($column){ global $post; switch ($column) { case "description": the_excerpt(); break; case "price": // Now here I have to define the field, but how would I drag in other subsequent price fields? $custom = get_post_custom(); echo $custom["price"][0]; break; case "catalog": echo get_the_term_list($post-&gt;ID, 'catalog', '', ', ',''); break; } } </code> to display what you want for each column say your price change it to something like: <code> case "price": // Now here I have to define the field, but how would I drag in other subsequent price fields? $custom = get_post_custom(); echo $custom["price"][0]; echo 'br /&gt;'; echo $custom["another_FIELD"][0]; echo 'br /&gt;'; echo $custom["yet_another_FIELD"][0]; break; </code> hope this helps
Custom Post Types: Can you add more than one Variable to a Column?
wordpress
I've been given the directive to "retire" about 1000 articles from a wordpress site I maintain. Deleting the posts from the DB is trivial, but how would one go about deleting the orphaned files from the uploads folder?
take a look at Upload Janitor plugin. its a plugin i use to clean up unused images and other files from your uploads folder. but just in case make a backup of your uploads directory first
How to delete orphan attachments?
wordpress
I have two authors pages, one displays about 5 posts. Then I'm trying to setup another page that will be all of their posts. I have created a template called moreauthorposts.php and I'm trying to pass the author variable to this page. Problem is if i pass domain.com/more-author-posts?author=johndoe it gets stripped out. How can I retrieve this value? Is this even possible in wordpress? I know WP Rewrite is jacking my URL structure somehow I'm just not sure. I've tried: <code> get_query_var('author') </code> and tried reading this but didn't have any luck: http://codex.wordpress.org/Query_Overview Suggestions? Thanks.
I'm almost sure that author is built-in so use somthing like author_more so you need to add that var to query_vars first <code> //add author_more to query vars function add_author_more_query_var() { global $wp; $wp-&gt;add_query_var('author_more'); } add_filter('init', 'add_author_more_query_var'); </code> then on your moreauthorposts.php call it like this: <code> if ( get_query_var('author_more') ) { //do your stuff } </code> Update this works in the http://domain.com/index.php?author_more=value but if you want to use this as fancy url you need to add a rewrite rule <code> function add_author_more_rewrite_rule() { add_rewrite_rule('more-author-posts/(\d*)$', 'index.php?author_more=$matches[1]', 'top'); } add_action('init','add_author_more_rewrite_rule'); </code> and now you can use http://domain.com/more-author-posts/value
Passing and retrieving query vars in wordpress
wordpress
Is there any method to close connection similar to mysql_close() for wpdb in wordpress? Is it not necessary to close connection for global wpdb?
There is no explicit method. It stores link identifier in <code> $wpdb-&gt;dbh </code> field, so I guess you could use <code> mysql_close() </code> on it. Why do you need it btw? If you want to reuse <code> $wpdb </code> it is better to create separate <code> wpdb </code> object instead.
How to close wpdb connection?
wordpress
I have a situation where I need to hide a specific category and it's children from users who are logged in as Contributors. I don't want them to see this category and it's children in the categories meta-box on the add new post screen. I can't find a plugin (that works) to do this, wondering if someone else knows of one, or even better if there is a function I can use to do this?
Hi @davemac: Well, I wrote this before I saw that you answered your own question so I might as well post it anyway: <code> add_filter('list_terms_exclusions', 'yoursite_list_terms_exclusions', 10, 2); function yoursite_list_terms_exclusions( $exclusions, $args ) { global $pagenow; if (in_array($pagenow,array('post.php','post-new.php')) &amp;&amp; !current_user_can('see_special_cats')) { $exclusions = " {$exclusions} AND t.slug NOT IN ('slug-one','slug-two')"; } return $exclusions; } </code> This code presumes that you've used a plugin like the Members plugin to create a capability called <code> 'see_special_cats' </code> and that you've assigned it to every role that you want to have access to the categories except of course <code> 'Contributors' </code> . Since you found the plugin you may not need this, but maybe it will help someone else.
How can I hide a category from Contributors in the edit/add new post screen?
wordpress
When someone creates a post in a custom post type and uploads an image the Link URL box shows it as the attachment URL. What I would like is for it to be the permalink to the post. Is there a way to do it without modifying core files?
Hi @kel: Thanks for answering the comments and thanks to @בניית אתרים providing the screenshot; now I have a better idea of what you wanted. Based on what you asked for I think what would be ideal would be for the dialog box to simple generate your preferred URL; that way you don't have to remember to click. You can accomplish what you are after by using the <code> 'attachment_fields_to_edit' </code> hook and modifying the sub-elements of the passed array: <code> $form_fields['url']['html'] </code> . You can copy the following code to your theme's <code> functions.php </code> file, or to a <code> .PHP </code> file for a plugin you might be writing: <code> add_filter('attachment_fields_to_edit','your_attachment_fields_to_edit',10,2); function your_attachment_fields_to_edit($form_fields,$post) { $url = get_permalink($post-&gt;ID); /* UNCOMMENT THESE LINES IF FOR PARENT POST URL AND NOT ATTACHMENT POST URL $url_parts = explode('/',trim($url,'/')); array_pop($url_parts); $url = implode('/',$url_parts) . '/'; */ $form_fields['url']['html'] =&lt;&lt;&lt;HTML &lt;input type="text" class="text urlfield" name="attachments[{$post-&gt;ID}][url]" value="{$url}" /&gt; HTML; return $form_fields; } </code> Here's what it looks like with the commented-out code so that the full permalink to the attachment post shows: Here's what it looks like with the commented-out code so that the full permalink to the attachment post shows: Note that one caveat is this only works after you have saved the parent post because the permalink is evidently not finalized until then. I'm sure there's a workaround but I'll leave that as an exercise for the reader (like my professors used to say...) P.S. I simultaneously love your domain name, and I feel quite queasy about it at the same time! ;-)
Link images to post permalink - custom post types
wordpress
I searched high and low for a plugin that can remove/hide Admin menu items , including custom post types and taxonomies, based on user role. Every one I have tried only does a global hide, not based on user role. Other more complex ones like adminize do not display custom post types or taxonomies. Do I have to write my own function or is there a simple plugin I am overlooking?
Update: reading mike's answer again got me thinking that you can add a new capability to a role and use that as you removal condition, so: <code> // first add your role the capability like so // get the "author" role object $role = get_role( 'administrator' ); // add "see_all_menus" to this role object $role-&gt;add_cap( 'see_all_menus' ); //then remove menu items based on that function remove_those_menu_items( $menu_order ){ global $menu; // check using the new capability with current_user_can if ( !current_user_can( 'see_all_menus' ) ) { foreach ( $menu as $mkey =&gt; $m ) { //custom post type name "portfolio" $key = array_search( 'edit.php?post_type=portfolio', $m ); //pages menu $keyB = array_search( 'edit.php?post_type=page', $m ); //posts menu $keyC = array_search( 'edit.php', $m ); if ( $key || $keyB || $keyC ) unset( $menu[$mkey] ); } } return $menu_order; } //Then just Hook that function to "menu_order" add_filter( 'menu_order', 'remove_those_menu_items' ); </code> Old answer I completely agree with what mike posted but if you're not up to custom coding Take a look at Admin Menu Editor plugin. it lets you set access rights by level.
Plugin to remove Admin menu items based on user role?
wordpress
Man, I can't seem to ever get done with enhancements to WordPress categories. I hope there's more work done on core category options in the future. Especially with the emergence of site theming and siloing of late. I know WP is ahead of most publishing systems in terms of its early support for categories, but it seems they've left lots on the table after that. Does a hook exist that would allow one to enhance the widget options for the category widget in order to allow setting the default sort order? Also, I notice in the codex the options for sort appear to be one of any of these (id, name, slug, count, group) and either ascending or descending. So, Ideally a drop down menu on widget options panel to allow one to set those two parameters (order and orderby) is what I'm looking to do. Otherwise, I'll just filter wp_list_categories and add the order option to my theme options, but it seems more logical to put it on the widget control itself.
Hi @Scott B: From <code> /wp-includes/widgets.php </code> for the <code> WP_Category_Widget </code> class we have the following code (line 438 in WordPress v3.0.4): <code> $cat_args = array('orderby' =&gt; 'name', 'show_count' =&gt; $c, 'hierarchical' =&gt; $h); if ( $d ) { $cat_args['show_option_none'] = __('Select Category'); wp_dropdown_categories( apply_filters('widget_categories_dropdown_args',$cat_args) ); </code> From that I would surmise the hook <code> 'widget_categories_dropdown_args' </code> should allow you to set an <code> 'orderby' </code> parameter? P.S. Have you ever considered using (something like) PhpStorm ? As you ask lots of "How can I get access to..." kind of questions you'd probably find yourself an order of magnitude more productive if you had a tool like PhpStorm that could quickly get you these answers. Just a thought...
Filter Categories widget to allow custom sorting?
wordpress
i am trying to display comments by specific users at a custom area. i am successful to do that, but the problem is the permalink structure . this code gets the url as permalinks disabled, if i enable the permalinks from my settings , then these urls starts giving a 404. here is the code im using : <code> &lt;? if(get_query_var('author_name')) : $curauth = get_userdatabylogin(get_query_var('author_name')); else : $curauth = get_userdata(get_query_var('author')); endif; $querystr = " SELECT comment_ID, comment_post_ID, post_title, comment_content FROM $wpdb-&gt;comments, $wpdb-&gt;posts WHERE user_id = $uid AND comment_post_id = ID AND comment_approved = 1 ORDER BY comment_ID DESC LIMIT 5 "; $comments_array = $wpdb-&gt;get_results($querystr, OBJECT); if ($comments_array): ?&gt; &lt;ul&gt; &lt;? foreach ($comments_array as $comment): setup_postdata($comment); echo "&lt;li&gt;&lt;a href='". get_bloginfo('url') ."/?p=".$comment-&gt;comment_ID."'&gt;Comment on ". $comment-&gt;post_title. "&lt;/a&gt;&lt;br /&gt;". $comment-&gt;comment_content . "&lt;/li&gt;"; endforeach; ?&gt; &lt;/ul&gt; &lt;? endif; ?&gt; </code> So this gets the url as www.mysite.com/p?=xxxx .. if permalinks are enabled as mysite.com/post-perma-links/ it starts giving 404 on these links generated via the above code. rest of the function is workign fine, SO possible to get the permalink url in this case instead of the p?=xxx ? help is appreciated cheers
Hi @Ayaz Malik: You need to use the function <code> get_comment_link() </code> . I've rewritten your code using some improved techniques and included the function call in place of what you had: <code> global $wpdb; $sql =&lt;&lt;&lt;SQL SELECT {$wpdb-&gt;comments}.comment_ID, {$wpdb-&gt;comments}.comment_post_ID, {$wpdb-&gt;comments}.comment_content, {$wpdb-&gt;posts}.post_title FROM {$wpdb-&gt;comments} INNER JOIN {$wpdb-&gt;posts} ON {$wpdb-&gt;comments}.comment_post_id={$wpdb-&gt;posts}.ID WHERE 1=1 AND {$wpdb-&gt;comments}.user_id = %d AND {$wpdb-&gt;comments}.comment_approved = 1 ORDER BY {$wpdb-&gt;comments}.comment_ID DESC LIMIT 5 SQL; $sql = $wpdb-&gt;prepare($sql,$uid); // $uid is assumed pre-defined before this code $comments = $wpdb-&gt;get_results($sql, OBJECT); if ($comments) { echo '&lt;ul&gt;'; foreach ($comments as $comment) { setup_postdata($comment); $link = get_comment_link($comment-&gt;comment_ID); echo "&lt;li&gt;&lt;a href='{$link}'&gt;Comment on {$comment-&gt;post_title}&lt;/a&gt;&lt;br /&gt;" . "{$comment-&gt;comment_content}&lt;/li&gt;"; } echo '&lt;/ul&gt;'; } </code>
Problem in getting user comments permalinks
wordpress
How can I show user's post counts of one's (Author) own in the admin post list (edit.php) instead of all post count of the system? like published (10), Draft (5) ... of his own or logedin user. Thanks in advance.
Have a look here for the solution (code needs optimizing, but it works): stackexchange-url ("Help to condense/optimize some working code")
Showing Post Counts of One's (Author) Own in the admin post list
wordpress
I'm making a website for a student activity and have a wordpress page for each member under a common parent group. Each page contains some member info (currently unstructured) and a profile picture. I would like to list all these members under a member page with perhaps a grid of profile pictures and names. Is there a plugin that can accomplish this? Note that each member does not have a wordpress account. I already found plugins that can do that, but it's not what I am looking for.
You might consider create a stackexchange-url ("custom post type") <code> 'person' </code> to mirror your user and then you'll be able to create member pages by creating a <code> single-person.php </code> theme template file. This answer provides code for doing that: Commenting in user profile page?
Wordpress for a club website -- Members page
wordpress
I think I'm on the right track with what I need to do, at least for doing one of the ways it could be done. I'm not really sure though, I could be way off for all I know. This is part of the code I needed help with last night for resizing the uploaded image files, but now I am trying to figure out how to use the wp_delete_attachment($id) function to delete images attached to the posts. So, I have this jQuery script that adds/ removes extra fields, for uploading more images to attach. For every added image there is a link to remove them. Clicking remove has only ever just remove the div which the link clicked was contained by, and when saving the post the attached file would show up as still attached. In my click event handler for the remove link, I need to first run function that will call the wp_delete_attachment(), to permanently delete the file/attachment, THEN I can use jQuery to remove the div of that attachment from the page. That way when saving the post it will have been deleted and not show up again still. Here's my functions I've been trying to work with: <code> // a function that returns the delete attachment php function, // and a message saying Deleted that fades in and out. jQuery(function() { function delete_att( attID ) { var div = jQuery('#img_uploads'), msg = $('div').html('&lt;strong&gt;Attachment Deleted!&lt;/strong&gt;').fadeIn().delay(200).fadeOut().appendTo('div'); return '&lt;?php wp_delete_attachment( ' + attID + ', true ); ?&gt;', msg; } </code> And the click handler which calls this function and then removes the containing div element from the page is: <code> jQuery('.remImage').live('click', function() { if( size &gt; 1 ) { var postID = jQuery('#attID').val() delete_att( postID ); //jQuery(this).parents('.attchmt').find('#attID'); jQuery(this).parents('.attchmt').detach(); size--; } return false; }); }); </code> The code to add extra fields is between these two parts but these are the key pieces for what I need help with. Currently, the way I have it coded here I am getting this error message. idk wtf this means exactly though lol. <code> Error: uncaught exception: [Exception... "Node cannot be inserted at the specified point in the hierarchy" code: "3" nsresult: "0x80530003 (NS_ERROR_DOM_HIERARCHY_REQUEST_ERR)" location: "http://code.jquery.com/jquery-1.4.4.min.js Line: 113"] </code> So here is the full code which I am using, exactly. https://gist.github.com/802465 Just trying to pass info to/from jQuery and Php and that's always a pain in the ass, (for me).
I have finally figured out how to do it, and it now works 100%!! Plus it uses the admin-ajax.php so clicking the Remove link there is an ajax request sent to the function that does the deleting of the attachment and returns the message saying it has been deleted. Here's the code for my solution, first is the html for the metabox: <code> &lt;a class="remImage" href="#"&gt;&lt;?php _e('Remove');?&gt;&lt;/a&gt; &lt;input type="hidden" id="att_remove" name="att_remove[]" value="&lt;?php echo $attachment-&gt;ID; ?&gt;" /&gt; &lt;input type="hidden" name="nonce" id="nonce" value="&lt;?php echo wp_create_nonce( 'delete_attachment' ); ?&gt;" /&gt; </code> Here's the Php function: <code> add_action( 'wp_ajax_delete_attachment', 'delete_attachment' ); function delete_attachment( $post ) { //echo $_POST['att_ID']; $msg = 'Attachment ID [' . $_POST['att_ID'] . '] has been deleted!'; if( wp_delete_attachment( $_POST['att_ID'], true )) { echo $msg; } die(); } </code> And the jQuery script that sends the attachment ID and action, etc., then removes the div from the DOM after receiving the ajax response is: <code> jQuery('.remImage').live('click', function() { if( size &gt; 1 ) { jQuery.ajax({ type: 'post', url: ajaxurl, data: { action: 'delete_attachment', att_ID: jQuery(this).parents('.attchmt').find('#att_remove').val(), _ajax_nonce: jQuery('#nonce').val(), post_type: 'attachment' }, success: function( html ) { alert( html ); } }); jQuery(this).parents('.attchmt').detach(); size--; } return false; }); </code> I am now able to finally complete what I thought was totally impossible after the number of attempts I've made in trying to make it and have failed each time. It will soon be a plugin, that I can then use on any site easily, with simple options to define the post type to add it to.
How to delete post attachments when jQuery is used with a click event on the delete link
wordpress
I have a all my custom post types list together in blog format. What I'm trying to do is echo the post type name on each post. I tried this: <code> get_post_type_object('post'); echo $obj-&gt;labels-&gt;singular_name; </code> But it just displayed "Post" for everything instead of the custom post type name
If you are within The Loop, try: <code> $post_type = get_post_type( $post-&gt;ID ); echo $post_type; </code> Does this work for you?
Echo current custom post type
wordpress
Somebody knows some trick in Add new Post to: Disable the upload of audio, video and other filetypes. Only accept the upload of an image (jpg, png, gif). Limit the upload of each Post to only One image (no more than one). Thanks in advance.
Hi José Pablo Orozco Marín: I was about to give up thinking that it wasn't possible or at least easy and then I stumbled onto the <code> wp_handle_upload_prefilter </code> filter which gives you exactly what you asked for! Here's the code: <code> add_filter('wp_handle_upload_prefilter', 'yoursite_wp_handle_upload_prefilter'); function yoursite_wp_handle_upload_prefilter($file) { // This bit is for the flash uploader if ($file['type']=='application/octet-stream' &amp;&amp; isset($file['tmp_name'])) { $file_size = getimagesize($file['tmp_name']); if (isset($file_size['error']) &amp;&amp; $file_size['error']!=0) { $file['error'] = "Unexpected Error: {$file_size['error']}"; return $file; } else { $file['type'] = $file_size['mime']; } } list($category,$type) = explode('/',$file['type']); if ('image'!=$category || !in_array($type,array('jpg','jpeg','gif','png'))) { $file['error'] = "Sorry, you can only upload a .GIF, a .JPG, or a .PNG image file."; } else if ($post_id = (isset($_REQUEST['post_id']) ? $_REQUEST['post_id'] : false)) { if (count(get_posts("post_type=attachment&amp;post_parent={$post_id}"))&gt;0) $file['error'] = "Sorry, you cannot upload more than one (1) image."; } return $file; } </code> And here are some screenshots showing how it looks in action:
Limit image upload to one and disable audio, video and other document file types to upload
wordpress
I've already read what I can on a couple of sites and installed this plug-in: http://en.support.wordpress.com/code/posting-source-code/ http://alexgorbatchev.com/SyntaxHighlighter/ I'm missing how to make it work. Question 1: Do I have to type in the Visual window or the HTML window? Question 2: Does TinyMCE mess with this? I've seen my code disappear in the HTML window. I currently have typed in my code in Visual Window like this: <code> [sourcecode language="php"] &lt;? Header( "HTTP/1.1 301 Moved Permanently" ); Header( "Location: http://CMSTrainingVideos.com" ); if ($_GET["page_id"] == 1) Header( "Location: http://CMSTrainingVideos.com/?p=35"); if ($_GET["page_id"] == 2) Header( "Location: http://CMSTrainingVideos.com/?p=43"); ?&gt; [/sourcecode] </code> I also tried <code> &lt;pre language="php"&gt; </code> with the "Geshi" syntax highligher, and no luck there either. But nothing is happening, i.e. no syntax highlighting: http://cmstrainingvideos.com/?p=53
I use a similar plugin called WP Syntax, which works better, in my experience, so I'm going to answer for that one: Question 1: Do I have to type in the Visual window or the HTML window? In the HTML window. I prefer the <code> &lt;pre lang="php"&gt; </code> mode. Question 2: Does TinyMCE mess with this? Yes, it will html encode special chars, for example transforming <code> =&gt; </code> into <code> =&amp;gt; </code> etc. so you should probably disable the rich editor alltogether.
Proper implementation/use of code/syntax highlighting
wordpress
The purpose of this function is to simply wrap the first occurrence of the keyword in bold tags. I'm getting an error on the line marked below. Warning: DOMDocument::loadHTML() [domdocument.loadhtml]: error parsing attribute name in Entity, line: 4 in C:\xampplite\htdocs\testsite\wp-content\plugins\mylugin\test.php on line 40 Is this the correct way to pass the post_content object? <code> add_filter('wp_insert_post_data', 'my_bold_keyword' ); function my_bold_keyword($content){ $myKeyword = "test 123"; $d = new DOMDocument(); $d-&gt;loadHTML($content['post_content']); //ERROR OCCURS HERE $x = new DOMXpath($d); $Matches = $x-&gt;query("//text()[contains(.,$myKeyword) and not(ancestor::h1) and not(ancestor::h2) and not(ancestor::h3) and not(ancestor::h4) and not(ancestor::h5) and not(ancestor::h6)]"); if($Matches &amp;&amp; $Matches-&gt;length &gt; 0){ $myText = $Matches-&gt;item(0); // need to wrap #myText in &lt;b&gt; wrapper } return $content; } </code>
Hi @Scott B: Here's a modified version of what you have that resolves the error (although the XPath does not match; I'm not an XPath guru so can't help with the proper XPath syntax): <code> add_filter('wp_insert_post_data', 'my_bold_keyword', 10, 2 ); function my_bold_keyword( $data, $postarr ) { $myKeyword = "test 123"; $d = new DOMDocument(); $d-&gt;loadHTML($postarr['post_content']); //ERROR NO LONGER OCCURS HERE $x = new DOMXpath($d); $Matches = $x-&gt;query("//text()[contains(.,$myKeyword) and not(ancestor::h1) and not(ancestor::h2) and not(ancestor::h3) and not(ancestor::h4) and not(ancestor::h5) and not(ancestor::h6)]"); if($Matches &amp;&amp; $Matches-&gt;length &gt; 0){ $myText = $Matches-&gt;item(0); // need to wrap #myText in &lt;b&gt; wrapper } return $content; } </code> P.S. About that PhpStorm... '-)
Error passing post_content to function
wordpress
I'm using PHP Exec to build a widget to show a list of upcoming events: <code> &lt;?php function filter_whene($whene = '') { $whene .= " AND post_date &gt;= '" . date('Y-m-d') . "' "; return $whene; } add_filter('posts_whene', 'filter_whene'); query_posts('cat=10&amp;showposts=3&amp;'); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;li&gt;&lt;?php the_date(); ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;?php the_title(); ?&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php endwhile; else: ?&gt;&lt;p&gt;Não há eventos agendados.&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php remove_filter('posts_whene', 'filter_whene'); ?&gt; &lt;?php wp_reset_query(); ?&gt; </code> It seems to work on the front end but I get: Fatal error: Cannot redeclare filter_whene() (previously declared in /home/content/a/c/a/acamorg/html/cea2/wp-content/plugins/exec-php/includes/runtime.php(42) : eval()'d code:3) in /home/content/a/c/a/acamorg/html/cea2/wp-content/plugins/exec-php/includes/runtime.php(42) : eval()'d code on line 6 on the widget backend. Any suggestions? Thank you.
Hi @user2816: It would seem you are using that code in more than one widget? Try changing part of that code from these: <code> function filter_whene($whene = '') { $whene .= " AND post_date &gt;= '" . date('Y-m-d') . "' "; return $whene; } add_filter('posts_whene', 'filter_whene'); </code> To this: <code> if (!function_exists('filter_whene')) { function filter_whene($whene = '') { $whene .= " AND post_date &gt;= '" . date('Y-m-d') . "' "; return $whene; } } add_filter('posts_whene', 'filter_whene'); </code> Better, move as much of your code as possible to your theme's <code> functions.php </code> file. Wrap it in a function and then you only have to type one line of code in your PHP Exec widget. Or better yet, get rid of that plugin completely and write your own widget ; because PHP Exec is evil . P.S. Okay, PHP Exec is not evil per se , but once you try to do anything more than trivial it creates more problems than it solves.
Get posts after today (upcoming events)
wordpress
I'm working on the admin interface for a plugin I'm developing, and it involves collapsible layouts. I want the state of the layout to be remembered when the page is refreshed, so I'm trying to use some simple cookies to do so. In the interface, there are "collapse" buttons that collapse sections of the admin panel. Whenever a button is clicked, I need a cookie set for the state of that section. So if a section is closed, a cookie needs to be created to remember that. Then, if the same button is clicked, the cookie needs to be modified to indicate that the section has been reopened. Here's the code I have so far for setting a cookie to true (or false) when a button is clicked: <code> $('.ss-show-collapse').click(function(){ var collapse_anchor = '.'+$(this).attr("id")+' span'; show_collapse = '.ss-show'+$(this).attr("id").replace('ss-show-collapse', ''); $(show_collapse ).toggleFade('slow'); $(collapse_anchor).toggle(); if (getCookie($(this).attr("id")) == true) { setCookie($(this).attr("id"), false, 1); } else { setCookie($(this).attr("id"), true, 1); } alert(getCookie($(this).attr("id"))); // just to see that the cookie was modified return false; }); </code> It works fine to set the cookie to "true" the first time, but will never delete the cookie if it already exists.
<code> if (getCookie($(this).attr("id")) == true) { </code> The above code will NEVER evaluate as true because cookie values are stored as strings. You are trying to store a boolean value, which is converted to a string when it is written to the cookie. When the browser reads the cookie value, it is also read as a string. The fixed version of your code should be: <code> $('.ss-show-collapse').click(function(){ var collapse_anchor = '.'+$(this).attr("id")+' span'; show_collapse = '.ss-show'+$(this).attr("id").replace('ss-show-collapse', ''); $(show_collapse ).toggleFade('slow'); $(collapse_anchor).toggle(); if (getCookie($(this).attr("id")) == 'true') { setCookie($(this).attr("id"), 'false', 1); } else { setCookie($(this).attr("id"), 'true', 1); } return false; }); </code> I would also suggest looking into using <code> event.preventDefault(); </code> instead of <code> return false; </code> http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/ <code> $('.ss-show-collapse').click(function(event){ var collapse_anchor = '.'+$(this).attr("id")+' span'; show_collapse = '.ss-show'+$(this).attr("id").replace('ss-show-collapse', ''); $(show_collapse ).toggleFade('slow'); $(collapse_anchor).toggle(); if (getCookie($(this).attr("id")) == 'true') { setCookie($(this).attr("id"), 'false', 1); } else { setCookie($(this).attr("id"), 'true', 1); } event.preventDefault(); }); </code>
Having trouble setting / modifying cookies
wordpress
script type="text/javascript" is optional in HTML5 and all browsers (even old ones) recognise JavaScript without it. I am building an HTML5 site and want my script output to be consistent. However, scripts that use the WordPress enqueue function are printed with type="text/javascript". CSS is also printed with type="text/css", which is also not needed. I can't find a filter to remove those properties. Is there one?
This is hardcoded in <code> WP_Scripts-&gt;do_item() </code> method ( source ) and probably same for styles. So it cannot be filtered. As alternative you can extend class with modified version of this method and replace instance in global <code> $wp_scripts </code> variable.
Is there a filter for enqueue script to strip the type="text/javascript" property
wordpress
Hey i tried using wordpress threaded comment feature but didn't work coz of custom theme. I have tried wp threaded comments plugin it works like a charm but unfortunately it has a conflict with the FV community news plugin, It shows a reply button on the community news area/widget. So i tried to do it manually... no luck. can anyone suggest me or point meto somewhere i can get some data to fix this. My wordpress version is 3.0.4 cheers Current COmment . php <code> &lt;?php // Do not delete these lines if (!empty($_SERVER['SCRIPT_FILENAME']) &amp;&amp; 'comments.php' == basename($_SERVER['SCRIPT_FILENAME'])) die ('Please do not load this page directly. Thanks!'); if (!empty($post-&gt;post_password)) { // if there's a password if ($_COOKIE['wp-postpass_' . COOKIEHASH] != $post-&gt;post_password) { // and it doesn't match the cookie ?&gt; &lt;p&gt;This post is password protected. Enter the password to view comments.&lt;/p&gt; &lt;?php return; } } /* This variable is for alternating comment background */ $oddcomment = 'alt'; ?&gt; &lt;?php if ( $comments ) : ?&gt; &lt;!-- You can start editing here. --&gt; &lt;?php $urlHome = get_bloginfo('template_directory'); ?&gt; &lt;div class="box post-comments" id="comments"&gt; &lt;div class="content"&gt; &lt;h4&gt;Awesome Comments!&lt;/h4&gt; &lt;?php foreach ($comments as $comment) : ?&gt; &lt;?php $comment_type = get_comment_type(); ?&gt; &lt;?php if($comment_type == 'comment') { ?&gt; &lt;div id="comment-&lt;?php comment_ID() ?&gt;" class="fl ar"&gt; &lt;div class="pic"&gt;&lt;?php echo get_avatar( $comment, 80, $default = $urlHome . '/images/default_avatar_visitor.gif' ); ?&gt;&lt;/div&gt; &lt;div class="comm-name"&gt;&lt;a href="&lt;?php comment_author_url(); ?&gt;" target="_blank" rel="nofollow"&gt;&lt;?php comment_author(); ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;div class="comm-date"&gt;&lt;small&gt;&lt;em&gt;&lt;?php the_time('m.d.y') ?&gt;&lt;/em&gt;&lt;/small&gt;&lt;/div&gt; &lt;/div&gt; &lt;div class="fr"&gt; &lt;div class="box2 &lt;?php echo $oddcomment; ?&gt;"&gt; &lt;?php comment_text() ?&gt; &lt;/div&gt;&lt;!--/box2 --&gt; &lt;/div&gt; &lt;div class="fix"&gt;&lt;/div&gt; &lt;?php $oddcomment = ( empty( $oddcomment ) ) ? 'alt' : ''; ?&gt; &lt;?php } /* End of is_comment statement */ ?&gt; &lt;?php endforeach; // end for each comment ?&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;div class="content"&gt; &lt;h3 id="trackbacks"&gt;Trackbacks&lt;/h3&gt; &lt;ol class="trackbacksol"&gt; &lt;?php //Displays trackbacks only foreach ($comments as $comment) : ?&gt; &lt;?php $comment_type = get_comment_type(); ?&gt; &lt;?php if($comment_type != 'comment') { ?&gt; &lt;li&gt;&lt;?php comment_author_link() ?&gt;&lt;/li&gt; &lt;?php } endforeach; ?&gt; &lt;/ol&gt; &lt;/div&gt;&lt;/div&gt; &lt;?php endif; ?&gt; &lt;?php if ('open' == $post-&gt;comment_status) : ?&gt; &lt;div id="respond" class="box post-comments"&gt; &lt;div class="content"&gt; &lt;h4&gt;Leave Your Response&lt;/h2&gt; &lt;?php if ( get_option('comment_registration') &amp;&amp; !$user_ID ) : ?&gt; &lt;p&gt;You must be &lt;a href="&lt;?php echo get_option('siteurl'); ?&gt;/wp-login.php?redirect_to=&lt;?php echo urlencode(get_permalink()); ?&gt;"&gt;logged in&lt;/a&gt; to post a comment.&lt;/p&gt; &lt;?php else : ?&gt; &lt;div class="fl"&gt; &lt;?php if ( is_user_logged_in() ) {?&gt; &lt;div class="pic"&gt;&lt;img src="&lt;?php bloginfo('template_directory'); ?&gt;/images/default_avatar_visitor.gif" alt="" /&gt;&lt;/div&gt; &lt;? } else { ?&gt; &lt;p&gt;Your Name: &lt;/p&gt; &lt;p style="margin-top:9px;"&gt;Your Email: &lt;/p&gt; &lt;p style="margin-top:12px;"&gt;Website: &lt;/p&gt; &lt;p style="margin-top:15px;"&gt;Comments: &lt;/p&gt; &lt;? } ?&gt; &lt;/div&gt; &lt;div class="fr"&gt; &lt;form action="&lt;?php echo get_option('siteurl'); ?&gt;/wp-comments-post.php" method="post" id="commentform"&gt; &lt;fieldset class="message"&gt; &lt;?php if ( $user_ID ) : ?&gt; &lt;p&gt;Logged in as &lt;a href="&lt;?php echo get_option('siteurl'); ?&gt;/wp-admin/profile.php"&gt;&lt;?php echo $user_identity; ?&gt;&lt;/a&gt;. &lt;a href="&lt;?php echo get_option('siteurl'); ?&gt;/wp-login.php?action=logout" title="Log out of this account"&gt;Log out &amp;raquo;&lt;/a&gt;&lt;/p&gt; &lt;?php else : ?&gt; &lt;div&gt; &lt;input name="author" id="author" type="text" value="" /&gt; &lt;/div&gt; &lt;div&gt; &lt;input name="email" id="email" type="text" value="" /&gt; &lt;/div&gt; &lt;div&gt; &lt;input name="url" id="url" type="text" value="" /&gt; &lt;/div&gt; &lt;?php endif; ?&gt; &lt;div class="textarea"&gt; &lt;textarea name="comment" id="comment" cols="" rows=""&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;div class="submit"&gt; &lt;input name="submit" id="submit" type="image" src="&lt;?php bloginfo('template_directory'); ?&gt;/images/btn-submit.gif" value="Send" class="btn" /&gt; &lt;/div&gt; &lt;div class="notice"&gt;* Name, Email, Comment are Required&lt;/div&gt; &lt;input type="hidden" name="comment_post_ID" value="&lt;?php echo $id; ?&gt;" /&gt; &lt;?php do_action('comment_form', $post-&gt;ID); ?&gt; &lt;/fieldset&gt; &lt;/form&gt; &lt;?php endif; // If registration required and not logged in ?&gt; &lt;/div&gt; &lt;div class="fix"&gt;&lt;/div&gt; &lt;/div&gt; &lt;!--/content --&gt; &lt;/div&gt; &lt;!--/box --&gt; &lt;?php endif; // if you delete this the sky will fall on your head ?&gt; </code>
Does it not work because theme is old or simply coded in incompatible way? There is this article in Codex that might be relevant - Migrating Plugins and Themes to 2.7/Enhanced Comment Display . Otherwise I'd take a look at some modern theme (like Twenty Ten) and see how is it properly coded for current WordPress version.
Unable to thread comments because of custom comments.php file
wordpress
It seems there must be a plugin for this, but I can't find it. I'd like to enable a jQuery slider in a post, using the images I've added to the gallery for that post. Does anyone know of a plugin? And if not, what would be the smartest way to implement this? Again it's important that it calls from that posts gallery - using the native WordPress gallery. Thanks in advance!
I have written a couple tutorials on how to make a dynamic jQuery featured post slider with Wordpress, here is my best one which is the most popular post on my site, in case you're interested in trying it out. http://new2wp.com/pro/part-3-making-a-dynamic-wordpress-jquery-featured-post-slider-tutorial-finale/
How to best create a jQuery Slider to display a native wordpress gallery?
wordpress
Im trying to get the next and previous attachment by the user its currently displaying, this is what I have and it works great except it gets all of the attachments instead of just the ones from a specific user. <code> &lt;p&gt; &lt;?php $attachment_size = apply_filters( 'twentyten_attachment_size', 900 ); echo wp_get_attachment_image($post-&gt;ID, array( $attachment_size, 9999) ); // filterable image width with, essentially, no limit for image height.?&gt; &lt;/p&gt; &lt;div id="next-prev-links"&gt;&lt;div class="previmg"&gt;&lt;?php previous_image_link(); ?&gt;&lt;/div&gt;&lt;p id="previmgtxt" class="imgtxt"&gt;&lt;?php previous_image_link(false, 'Previous Photo'); ?&gt;&lt;/p&gt; &lt;div class="nextimg"&gt; &lt;?php next_image_link(); ?&gt;&lt;/div&gt;&lt;p id="nextimgtxt" class="imgtxt"&gt;&lt;?php next_image_link(false, 'Next Photo'); ?&gt;&lt;/p&gt;&lt;/div&gt; </code>
Hi @Jeremy Love: Good question! And it's a good question because there do not appear to be any hooks to allow you to write code to filtering by author. Sadly that means to copy their copy to make your own functions so you can make the required 1 line change (in this case, it's <code> 'post_author' =&gt; $post-&gt;post_author, </code> ). Here are functions you should be able to use: <code> function yoursite_previous_image_link($size = 'thumbnail', $text = false) { yoursite_adjacent_image_link(true, $size, $text); } function yoursite_next_image_link($size = 'thumbnail', $text = false) { yoursite_adjacent_image_link(false, $size, $text); } function yoursite_adjacent_image_link($prev=true,$size='thumbnail',$text=false) { global $post; $post = get_post($post); $attachments = array_values(get_children( array( 'post_author' =&gt; $post-&gt;post_author, 'post_parent' =&gt; $post-&gt;post_parent, 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'order' =&gt; 'ASC', 'orderby' =&gt; 'menu_order ID' ))); foreach ( $attachments as $k =&gt; $attachment ) if ( $attachment-&gt;ID == $post-&gt;ID ) break; $k = $prev ? $k - 1 : $k + 1; if ( isset($attachments[$k]) ) echo wp_get_attachment_link($attachments[$k]-&gt;ID, $size, true, false, $text); } </code>
Getattachment next and previous by author only
wordpress
I have a custom post types called publications . I want to retrieve all the pages and publications . (I'm also filtering by taxonomy, but that's not what is creating the problem) <code> $args= array( 'post_type'=&gt;array('publications', 'page') ); query_posts($args); </code> The above only returns pages, not publications. If I remove 'page' from the array and leave <code> 'post_type'=&gt;array('publications') </code> then the publications are returned. Its seems like I cannot query more than I post type at a time, contrary to what the codex explains here: http://codex.wordpress.org/Template_Tags/query_posts#Type_.26_Status_Parameters . I've tried 'post_type' = 'any' with the same results; only the pages are returned. Using WP_Query also yielded the same results. Am I doing something wrong or is this a bug in WP 3.1 rc3?
Hi @Bundarr: Testing the following basic example as a standalone file it looks like it works as expected and not as you are reporting: <code> &lt;?php include '../wp-load.php'; header('Content-type: text/plain'); $q = new WP_Query(array( 'post_type'=&gt;array('publications', 'page') 'posts_per_page' =&gt; -1, )); echo "SQL: {$q-&gt;request}\n"; foreach($q-&gt;posts as $post) { echo "{$post-&gt;post_name} - {$post-&gt;post_type}\n"; } </code> So, I can only assume that you have some plugins or theme code that is somehow blocking? Or maybe it is as simple as missing a <code> 'posts_per_page' =&gt; -1 </code> argument and thus only displaying a limited number and making it seem like it's not working? With <code> 'posts_per_page' </code> the query would look like this (-1 means 'no limit'): <code> $q = new WP_Query(array( 'post_type'=&gt;array('publications', 'page') 'posts_per_page' =&gt; -1, )); </code>
Why can't I query more than 1 post type at a time?
wordpress
I just started using vimpress . I can write posts by typing in Vim <code> :BlogNew </code> and send them by typing: <code> :BlogSend </code> I think a lot of Wordpress developers may be using the plugin. So my question is Is it possible to list and create custom post types with Vimpress?
simple and short. up to vimpress latest version 0.91 which was developed at 2007-07-13 no you can't.
Is it possible to list and create custom post types with Vimpress?
wordpress
Hey guys, thanks in advance for your help. I've done my research and I'm a bit stumped with this... I'm building a Wordpress website for a client and it is going to have an e-store. I'm using wp-ecommerce. All of the store pages are loading with a javascript error: http://www.thecollectiveclothingco.com/products-page/t-shirts/ <code> jQuery("form.product_form").livequery is not a function [Break On This Error] jQuery("form.product_form").livequery(function(){ </code> After some extensive google-age, I believe I've diagnosed the issue as a script conflict. In other words, either WP or the plugin itself is serving up jquery, and I'm also including it for some other things on the site. When I delete my jquery script call, the issue goes away and the store works fine. But I need that jquery... I've read about using WP enqeue to fix the issue: <code> function my_init_method() { if (!is_admin()) { wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js'); wp_enqueue_script( 'jquery' ); } } add_action('init', 'my_init_method');php wp_head(); </code> I believe I've done this right, but does not seem to be fixing anything. Any ideas? Thanks again. EDIT: Alright, I figured it out... it was the enqueue script that fixed things. I wp(head); had to come before the deregister and enqueue part. I must have read the documentation wrong. Here's what I added to my header: <code> &lt;?php wp_head(); wp_deregister_script('jquery'); wp_enqueue_script('jquery', MYURL .'http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js', FALSE, '1.4.4'); ?&gt; </code>
There are currently two copies of jQuery loaded on site: In header there is jQuery bundled with WordPress, likely requested by some plugin. In footer there is jQuery from Google CDN, likely added by your code? Obviously this is one too many. There are couple of ways to handle it: If you are fine with using bundled copy you need to register/enqueue your scripts and declare <code> jquery </code> in dependencies, see in Codex: <code> wp_register_script() </code> , <code> $deps </code> argument. You can re-register jQuery to Google CDN, still good idea to register your script with it as dependency. Your code seems fine except this at end <code> php wp_head(); </code> , <code> php </code> makes no sense, and <code> wp_head() </code> call should be in theme.
Wordpress Jquery Confliction with Plugin
wordpress
Is it possible to two way sync a post type between multiple sites on a multisite install? For example if someone makes a change to an entry under post type "inventory" on Site A how can I make that reflect on Site B automatically and vice versa? I am thinking that there are two main possible way of doing this, neither of which I'm sure can easily be done. 1) A plugin hooks into the edit_post so when a change is made the plugin edits the sister entry in the other blog's database table. 2) Anytime Site B views or edits an "inventory" post type it is reading it from Site A's database table.
I don't know what you mean by sync users. Users are global in the network and can be assigned to any blogs. "both their public website and backend both use their own multisite blog. " This doesn't make sense. Can you clarify?
Two-way synchronizing of a post type among multisite blogs
wordpress
I'm using the following code to retrieve posts: <code> &lt;?php $featuredPosts = new WP_Query(); $featuredPosts-&gt;query('showposts=5&amp;cat=3'); while ($featuredPosts-&gt;have_posts()) : $featuredPosts-&gt;the_post(); ?&gt; &lt;h1&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt; &lt;div class="meta"&gt; By &lt;?php the_author() ?&gt; &lt;/div&gt; &lt;div class="storycontent"&gt; &lt;?php the_excerpt(); ?&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; </code> Do I need to use <code> wp_reset_query() </code> If I have to use it where should I place it?
Hi @janoChen: Simple answer: no. What follows is what the PHP code for the function <code> wp_reset_query() </code> from <code> /wp-includes/query.php </code> in WordPRess v3.0.4 as well as the functions subsequently called. You can see that it's primarily about in modifying global variables. When you use <code> new WP_Query($args) </code> you will be assigning the return value from values to a local variable so, unless you are doing something so complex that you'd already know the answer to this question for then no, you don't need to call <code> wp_reset_query() </code> : <code> function wp_reset_query() { unset($GLOBALS['wp_query']); $GLOBALS['wp_query'] =&amp; $GLOBALS['wp_the_query']; wp_reset_postdata(); } function wp_reset_postdata() { global $wp_query; if ( !empty($wp_query-&gt;post) ) { $GLOBALS['post'] = $wp_query-&gt;post; setup_postdata($wp_query-&gt;post); } } function setup_postdata($post) { global $id, $authordata, $day, $currentmonth, $page, $pages, $multipage, $more, $numpages; $id = (int) $post-&gt;ID; $authordata = get_userdata($post-&gt;post_author); $day = mysql2date('d.m.y', $post-&gt;post_date, false); $currentmonth = mysql2date('m', $post-&gt;post_date, false); $numpages = 1; $page = get_query_var('page'); if ( !$page ) $page = 1; if ( is_single() || is_page() || is_feed() ) $more = 1; $content = $post-&gt;post_content; if ( strpos( $content, '&lt;!--nextpage--&gt;' ) ) { if ( $page &gt; 1 ) $more = 1; $multipage = 1; $content = str_replace("\n&lt;!--nextpage--&gt;\n", '&lt;!--nextpage--&gt;', $content); $content = str_replace("\n&lt;!--nextpage--&gt;", '&lt;!--nextpage--&gt;', $content); $content = str_replace("&lt;!--nextpage--&gt;\n", '&lt;!--nextpage--&gt;', $content); $pages = explode('&lt;!--nextpage--&gt;', $content); $numpages = count($pages); } else { $pages = array( $post-&gt;post_content ); $multipage = 0; } do_action_ref_array('the_post', array(&amp;$post)); return true; } </code> -Mike
Is it necessary to use wp_reset_query() in a WP_Query call?
wordpress
I would like to try little web apps with WordPress. Just to accept some values for few fields and present the output using AJAX. What are all the necessary modifications on WordPress? So, far I've tried some plugins like exec-php. But, I am in need of a better advice/suggestion.
Natively WordPress posts are subset of HTML (even more like semi-HTML - paragraph tags can be implied and added on output, but not stored). As result it really really doesn't like to store or process active code in post's content. This applies both to internal logic in PHP and front-end logic of post editor (it actively tries to strip some things like iframes, when switching to visual editor, etc). Basically you have two options: Loosen restrictions on what can be input and sotred in post content - like Exec-PHP you mention in question. Store active code elsewhere (in custom fields for example) and use shortcode in post content to call it.
How to run JS, PHP and etc. inside WP post?
wordpress
I want to add a slide side ways jquery to my website, I tried the following code, but seems not to be working Jquery code:- <code> &lt;script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js" type="text/javascript"&gt;&lt;/script&gt; &lt;script src="http://tab-slide-out.googlecode.com/files/jquery.tabSlideOut.v1.3.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function(){ $('.slide-out-div').tabSlideOut({ tabHandle: '.handle', pathToTabImage: 'images/contact_tab.gif', imageHeight: '122px', imageWidth: '40px', tabLocation: 'left', speed: 300, action: 'click', topPos: '200px', leftPos: '20px', fixedPosition: false }); }); &lt;/script&gt; </code> Div &amp; CSS code: <code> &lt;style type="text/css"&gt; .slide-out-div { padding: 20px; width: 250px; background: #ccc; border: 1px solid #29216d; } &lt;/style&gt; &lt;div class="slide-out-div"&gt; &lt;a class="handle" href="#"&gt;Content&lt;/a&gt; &lt;h3&gt;Contact me&lt;/h3&gt; &lt;p&gt;Hello &lt;/p&gt; &lt;p&gt;Welcome to my Blog&lt;/p&gt; &lt;/div&gt; </code> When I tried the above code into my header file, and the div code in the footer file, The DIV box appears to be slided outside but doesn't goes inside , the jquery is not working and the image contact_tab.gif is not displayed and my google maps on my website doesn't loads, I know this is because of wrong integration of jquery but I don't know how to integrate it with wordpress themes
I think the main problem is that you need to use a no-conflict wrapper when calling tab slideout. However, rather then simply point out the problem i'm going to cover some things you should be doing to make this script work "The WordPress Way" ..(ie. using an enqueue and hooking onto an appropriate hook to make that enqueue). First, we need an appropriate action and there's a couple we can use front-side. The hook i'll use is <code> wp_print_scripts </code> , because as you might have guessed it's for enqueuing scripts. <code> add_action( 'wp_print_scripts', 'enqueue_slideout' ); function enqueue_slideout() { wp_enqueue_script( 'jquery-slideout', 'http://tab-slide-out.googlecode.com/svn/trunk/jquery.tabSlideOut.v2.0.js', array('jquery'), '2.0', false ); } </code> I went and dug up the location of the most recent version, 1.3 is a good year older than the most recent 2.0, so i've updated the path to point at a more recent version. jQuery is loaded as a dependancy inside the enqueue, so you don't need to be doing any extra includes for jQuery, the enqueue will take care of that for you(regardless of whether your jQuery script has been re-registered to pull from Google - as many WP users choose to do). Next, we'll hook onto <code> wp_head </code> and output the script to setup the slideout tab using a no-conflict wrapper that fires when the document is ready(most scripts will work fine like this, though not all).. <code> add_action( 'wp_head', 'setup_slideout_tabs' ); function setup_slideout_tabs() { ?&gt; &lt;script type="text/javascript"&gt; jQuery(document).ready(function($){ $('.slide-out-div').tabSlideOut({ tabHandle: '.handle', pathToTabImage: '&lt;?php bloginfo('stylesheet_directory'); ?&gt;/images/contact_tab.gif', imageHeight: '122px', imageWidth: '40px', tabLocation: 'left', speed: 300, action: 'click', topPos: '200px', leftPos: '20px', fixedPosition: false }); }); &lt;/script&gt; &lt;?php } </code> You should note i've added in a little PHP to point the image path at the current theme's folder, so do ensure you have an image named <code> contact_tab.gif </code> in your theme's image folder, ie. <code> wp-content/themes/YOUR_THEME/images/contact_tab.gif </code> or update the image path appropriately. Add the CSS you posted before into your theme's stylesheet, there's really no need to output it inline, and the stylesheet is going to be getting loaded anyway, so it makes sense to just stick it in there. In the end, you should have something that looks like this.. Hope that helps...
Jquery integration with my theme
wordpress
I have finally!! got this thing I've tried about 12 times to make and 12 different ways, but finally got it to work,... sort of. I made a custom metabox for uploading and attaching images to posts, and it doesn't require you to use the horrible thickbox media uploader built into WP. I hate that thing. No, what I've done is just a group of inputs (title, description, file), which you can also duplicate, to add additional attachments if you want. So you fill in the fields, select an image to upload, and save draft or publish the post. Once there are attachments added to a post, the metabox will display the input fields, along with a preview image of the attached image for each attachment you added. The title and description fields are used to generate the file meta data, nothing is saved as the post_meta, that I know of. That's currently all that I have gotten working so far. I need to make it so that when you save/publish a post, inturn upload/create the attachment files, it will create the three image sizes as the default wp uploader would, thumbnail, medium, large, and keeping the full size image too. If that's possible somehow. If not, I would like to otherwise use add_image_size() to create/define new custom sizes, and generate them that way instead, upon uploading. I'm not sure which function is the most ideal to use in this case, maybe the image_make_intermediate_size() function would be better, or wp_create_thumbnail() or wp_crop_image()... who knows!! I cannot figure out how to go about doing that, if I need to run the wp_handle_upload() function for each one, or maybe something involving the wp_generate_attachment_metadata() function. It's confusing to me since the 3 image sizes are to be associated as variants of the same attachment, and how to go about doing that. I have scoured the web, read the source of every wp media/upload/image related file, and played with just about every function there is for the media upload stuff and cannot find how WP creates the 3 image sizes anywhere, or how to do it myself. In wp-includes/media.php the image_resize() function looks like it would be best since it's exactly what it should be. I just can't figure out for the life of me what the hell I'm missing or have tried doing but did wrong to make the image thumbnails. Here's my working function that does the wp_handle_upload() stuff and things, but it also needs to create the 100px thumb, and make a resize version of the image that is max-width like 500px, and saved as new files of the uploaded one. <code> function update_attachment(){ global $post; wp_update_attachment_metadata( $post-&gt;ID, $_POST['a_image'] ); if( !empty( $_FILES['a_image']['name'] )) { //New upload require_once( ABSPATH . 'wp-admin/includes/file.php' ); $override['action'] = 'editpost'; $url = wp_handle_upload( $_FILES['a_image'], $override ); // $medium = image_make_intermediate_size( $uploaded_file['url'], 500, 400, true ); // $thumb = = image_make_intermediate_size( $uploaded_file['url'], 100, 100, true ); if ( isset( $file['error'] )) { return new WP_Error( 'upload_error', $file['error'] ); } $array_type = wp_check_filetype $allowed_file_types = array('image/jpg','image/jpeg','image/gif','image/png'); $name_parts = pathinfo( $name ); $name = trim( substr( $name, 0, - ( 1 + strlen( $name_parts['extension'] )) )); $type = $file['type']; $file = $file['file']; $title = $_POST['a_title'] ? $_POST['a_title'] : $name; $content = $_POST['a_desc'] $post_id = $post-&gt;ID; $attachment = array( 'post_title' =&gt; $title, 'post_type' =&gt; 'attachment', 'post_content' =&gt; $content, 'post_parent' =&gt; $post_id, 'post_mime_type' =&gt; $type, 'guid' =&gt; $url['url'] ); // Save the data $id = wp_insert_attachment( $attachment, $_FILES['a_image'][ 'file' ]/*, $post_id - for post_thumbnails*/); if ( !is_wp_error( $id )) { $attach_meta = wp_generate_attachment_metadata( $id, $uploaded_file['url'] ); wp_update_attachment_metadata( $attach_id, $attach_meta ); } update_post_meta( $post-&gt;ID, 'a_image', $uploaded_file['url'] ); } } </code> Anyone able to help me finally fix this so it works proper would be loved. I've spent so many ridiculous countless hours numerous different times trying to develop this thing and the documentation sucks, and there's not really any good posts anywhere on how to do it. Thanks
Hi @jaredwilli: Dude! Valiant effort, and nice work. All-in-all it could be a great addition to WordPress. You were so close, but you had somewhere between 5 and 10 little failed assumptions or code that looks like you started it but didn't get back to it because it wasn't working. I reworked your function only as much as I needed to correct it. The solution follows, and I'll leave the side-by-side comparison to your or someone less burned-out. :) <code> function update_attachment() { global $post; wp_update_attachment_metadata( $post-&gt;ID, $_POST['a_image'] ); if( !empty( $_FILES['a_image']['name'] )) { //New upload require_once( ABSPATH . 'wp-admin/includes/file.php' ); $override['action'] = 'editpost'; $file = wp_handle_upload( $_FILES['a_image'], $override ); if ( isset( $file['error'] )) { return new WP_Error( 'upload_error', $file['error'] ); } $file_type = wp_check_filetype($_FILES['a_image']['name'], array( 'jpg|jpeg' =&gt; 'image/jpeg', 'gif' =&gt; 'image/gif', 'png' =&gt; 'image/png', )); if ($file_type['type']) { $name_parts = pathinfo( $file['file'] ); $name = $file['filename']; $type = $file['type']; $title = $_POST['a_title'] ? $_POST['a_title'] : $name; $content = $_POST['a_desc']; $post_id = $post-&gt;ID; $attachment = array( 'post_title' =&gt; $title, 'post_type' =&gt; 'attachment', 'post_content' =&gt; $content, 'post_parent' =&gt; $post_id, 'post_mime_type' =&gt; $type, 'guid' =&gt; $file['url'], ); foreach( get_intermediate_image_sizes() as $s ) { $sizes[$s] = array( 'width' =&gt; '', 'height' =&gt; '', 'crop' =&gt; true ); $sizes[$s]['width'] = get_option( "{$s}_size_w" ); // For default sizes set in options $sizes[$s]['height'] = get_option( "{$s}_size_h" ); // For default sizes set in options $sizes[$s]['crop'] = get_option( "{$s}_crop" ); // For default sizes set in options } $sizes = apply_filters( 'intermediate_image_sizes_advanced', $sizes ); foreach( $sizes as $size =&gt; $size_data ) { $resized = image_make_intermediate_size( $file['file'], $size_data['width'], $size_data['height'], $size_data['crop'] ); if ( $resized ) $metadata['sizes'][$size] = $resized; } $attach_id = wp_insert_attachment( $attachment, $file['file'] /*, $post_id - for post_thumbnails*/); if ( !is_wp_error( $id )) { $attach_meta = wp_generate_attachment_metadata( $attach_id, $file['file'] ); wp_update_attachment_metadata( $attach_id, $attach_meta ); } update_post_meta( $post-&gt;ID, 'a_image', $file['url'] ); } } } </code> Hey, why not splurge and get yourself a copy of PhpStorm ? You could have easily solved this yourself, you were sooo close, if you could have just traced through the code like I now can. If you do, don't waste your time on the very buggy XDEBUG and instead download Zend Debugger . P.S. This is my former answer. I posted this before I realized what exactly Jared was asking. It is correct, but not related to his question. :) I think what you are looking for is <code> add_image_size() </code> : <code> add_image_size( $size_id, $width, $height, $crop ); </code> For example: <code> add_image_size('headshot', 130, 150); add_image_size('large-headshot', 260, 300); </code> By setting this WordPress will create those sizes automatically. What that what you needed?
How does WP media uploader create the 3 different sized images, and how can I duplicate it
wordpress
Assuming I know the image attachment ID, how can I get the post permalink to which is attached (if any) ?
Roughly this: <code> $parent = get_post_field( 'post_parent', $id); $link = get_permalink($parent); </code>
Get the post attached to a image attachment
wordpress
I want to use <code> next_post_link </code> and <code> prev_post_link </code> to return only the next post in my custom taxonomy of a custom post type. I have a custom post type called "work_posts" which has the taxonomy "work_categories" assigned. The category I want to show is called 'all'. I looked up <code> get_adjacent_post </code> in the "link-template.php" which has a few filters which should make it possible to make such a query but my SQL is not good enough to make the right query. The hooks are: <code> get_{$adjacent}_post_join </code> <code> get_{$adjacent}_post_where </code> <code> get_{$adjacent}_post_sort </code> if I log a query in the join hook I get: <code> INNER JOIN wp_term_relationships AS tr ON p.ID = tr.object_id INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id AND tt.taxonomy = 'category' AND tt.term_id IN (3) </code> how do I modify this to only show posts from my custom taxonomy?
Take a look at http://wordpress.org/extend/plugins/ambrosite-nextprevious-post-link-plus/ Its a plugin that adds extra missing functionality to next_post_link and prev_post_link functions.
next_post_link on custom taxonomy
wordpress
Right now, I'm using <code> get_posts </code> to retrieve cusstom posts types with a custom taxonomy assigned to it in order to generate static content like this: <code> &lt;?php /** * Template Name: Front Page * @package WordPress * @subpackage Prominent * @since Prominent 1.0 */ get_header(); ?&gt; &lt;div class="shadow-top"&gt; &lt;!-- Shadow at the top of the slider --&gt; &lt;/div&gt; &lt;div id="intro"&gt; &lt;div class="container"&gt; &lt;div id="slider-wrapper"&gt; &lt;div id="slider"&gt; &lt;?php // Create custom loop ?&gt; &lt;?php $custom_posts = get_posts('post_type=page_content&amp;page_sections=Slider (Front Page)'); ?&gt; &lt;?php foreach( $custom_posts as $post ) : setup_postdata( $post ); ?&gt; &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt; &lt;?php endforeach; ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/div&gt; &lt;div class="shadow-slider"&gt; &lt;!-- Shadow at the bottom of the slider --&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- #slider-wrapper --&gt; &lt;/div&gt;&lt;!-- .container --&gt; &lt;/div&gt;&lt;!-- #featured --&gt; &lt;div class="shadow-bottom"&gt; &lt;!-- Shadow at the bottom of the slider --&gt; &lt;/div&gt; &lt;div id="tagline"&gt; &lt;div class="container"&gt; &lt;?php $page_id = $post-&gt;ID; // 123 should be replaced with a specific Page's id from your site, which you can find by mousing over the link to edit that Page on the Manage Pages admin page. The id will be embedded in the query string of the URL, e.g. page.php?action=edit&amp;post=123. $page_data = get_page( $page_id ); // You must pass in a variable to the get_page function. If you pass in a value (e.g. get_page ( 123 ); ), Wordpress will generate an error. $content = apply_filters('the_content', $page_data-&gt;post_content); // Get Content and retain Wordpress filters such as paragraph tags. Origin from: http://wordpress.org/support/topic/get_pagepost-and-no-paragraphs-problem $title = $page_data-&gt;post_title; // Get title ?&gt; &lt;div class="content0"&gt; &lt;h2&gt;&lt;?php echo $content; // Output Content ?&gt;&lt;/h2&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- .container --&gt; &lt;/div&gt;&lt;!-- #content-bottom --&gt; &lt;div id="content"&gt; &lt;div class="container"&gt; &lt;div class="mainbar"&gt; &lt;?php // Create custom loop $custom_posts = get_posts('post_type=page_content&amp;page_sections=Content (Front Page)'); ?&gt; &lt;?php foreach( $custom_posts as $post ) : setup_postdata( $post ); ?&gt; &lt;div class="content-block"&gt; &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;p&gt;&lt;?php the_content(); ?&gt;&lt;/p&gt; &lt;/div&gt;&lt;!-- .content-block --&gt; &lt;?php endforeach; ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/div&gt;&lt;!-- #mainbar --&gt; &lt;/div&gt;&lt;!-- .container --&gt; &lt;/div&gt;&lt;!-- #content-bottom --&gt; &lt;?php get_footer(); ?&gt; </code> What is better practice in this case? To use query_posts, WP_Query, or get_posts?
Hi @janoChen: If you have a choice, go with <code> WP_Query </code> . Both of the other functions ( <code> query_posts() </code> and <code> get_posts() </code> ) call <code> WP_Query </code> indirectly. The former is designed to allow you to modify the main query after the standard query has already been run, for example when you want a second loop. But <code> query_posts() </code> affects global variables and can have side-effects. If possible use WP_Query instead and your code will be more robust. As for <code> get_posts() </code> , it's just a wrapper around <code> WP_Query </code> with some potentially unexpected defaults so you might as well call <code> WP_Query </code> directly and avoid those issues.
Is it better practice to use query_posts, WP_Query, or get_posts to create various custom loops within a Page?
wordpress
What would cause this error: Fatal error: Class 'ZipArchive' not found in /home/test/dummyurl.com/wp-content/themes/mytheme/upload-zip.php on line 14 PHP Version is 5.3.1 Does WP have a built in function I should use instead? Like perhaps the "unzip_file" function line 525 of ./wp-admin/includes/file.php"? <code> function openZip($file_to_open) { global $target; $zip = new ZipArchive(); //This is line 14 $x = $zip-&gt;open($file_to_open); if($x === true) { $zip-&gt;extractTo($target); $zip-&gt;close(); unlink($file_to_open); } else { die("There was a problem. Please try again!"); } } </code>
It means your PHP installation doesn't have the Zip library . You can install it by recompiling PHP with the <code> --enable-zip </code> option, or install the PECL package .
Fatal error: Class 'ZipArchive' not found
wordpress
i'm using wp_list_categories like so: <code> &lt;?php //list terms in a given taxonomy using wp_list_categories (also useful as a widget if using a PHP Code plugin) $taxonomy = 'news_cat'; $orderby = 'name'; $show_count = 0; // 1 for yes, 0 for no $pad_counts = 0; // 1 for yes, 0 for no $hierarchical = 1; // 1 for yes, 0 for no $title = ''; $args = array( 'taxonomy' =&gt; $taxonomy, 'orderby' =&gt; $orderby, 'show_count' =&gt; $show_count, 'pad_counts' =&gt; $pad_counts, 'hierarchical' =&gt; $hierarchical, 'title_li' =&gt; $title ); ?&gt; &lt;ul class="categories fl"&gt; &lt;?php wp_list_categories( $args ); ?&gt; &lt;/ul&gt; </code> which works great. it outputs as follows: <code> &lt;ul class="categories fl"&gt; &lt;li class="cat-item cat-item-5"&gt; &lt;a href="http://hhh.wp/news_cat/cat-1" title="View all posts filed under cat 1"&gt;cat 1&lt;/a&gt; &lt;/li&gt; &lt;li class="cat-item cat-item-6"&gt; &lt;a href="http://hhh.wp/news_cat/cat-2" title="View all posts filed under cat 2"&gt;cat 2&lt;/a&gt; &lt;/li&gt; &lt;li class="cat-item cat-item-7"&gt; &lt;a href="http://hhh.wp/news_cat/cat-3" title="View all posts filed under cat 3"&gt;cat 3&lt;/a&gt; &lt;/li&gt; &lt;li class="cat-item cat-item-8"&gt; &lt;a href="http://hhh.wp/news_cat/cat-4" title="View all posts filed under cat 4"&gt;cat 4&lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; </code> problem is i don't want an absolute path, just a relative one... i need the href to read as <code> /news_cat/cat-1 </code> thanks in advance.
Hi @matt ryan: Simplest way to do what you want is to use PHP output buffering . I haven't tested it yet but this should work: <code> ob_start(); wp_list_categories( $args ); $html = ob_get_clean(); echo str_replace(get_bloginfo('wpurl'),'',$html); </code> UPDATE You could also using the <code> 'wp_list_categories' </code> hook like this: <code> add_action('wp_list_categories','mysite_wp_list_categories'); function mysite_wp_list_categories( $output ) { return str_replace( get_bloginfo('wpurl'),'', $output ); } </code>
wordpress wp_list_categories
wordpress
I don't know whats wrong going on with my website, this is the second redirection problem going on, Whenever I add a new post, After adding title, When I try to add the content, My own websites home-page appears next to the content box, in a red bordered box, and a page tries to load, this page keeps on loading, nothing comes, the url of loading page is "http://mywebsite.com/wp-admin/post-new.php"
As stackexchange-url ("t31os") said, first thing you should do is disable all plugins, see if wp-admin/post-new.php works fine then, and re-enable them one by one, see which one is causing trouble. I would start with the plugin to change the admin theme, since this is the closest one to the admin dashboard.
Add new post redirection
wordpress
Say I have a custom post type called "Performers". This gets populated with different bands/performers. These posts have a featured image as well as custom fields (mp3 file, facebook link, myspace link, etc). I have another custom post type called "Events". When I create a new Event post, I would like the option to have a drop box to select one of the bands from the "Performers" custom post type. This will insert all data from the specific Band/Performer into the Event post (custom fields, featured image, etc.). What is the best method for inserting/injecting this sort of loop from the "Event" admin?
Currently the best way I know to handle that is the Posts 2 Posts plugin : http://wordpress.org/extend/plugins/posts-to-posts/ Here's an example showing how to set up the custom post types (if you already have them it's more for other's benefit who might be reading this) as well as the function call to <code> p2p_register_connection_type() </code> needed by the plugin to set up the post relationships. This can can go in your theme's <code> functions.php </code> file or in a <code> .PHP </code> file for a plugin you might be writing: <code> add_action('init','event_performer_init'); function event_performer_init() { register_post_type('event', array( 'label' =&gt; 'Events', 'public' =&gt; true, 'show_ui' =&gt; true, 'query_var' =&gt; 'event', 'rewrite' =&gt; array('slug' =&gt; 'events'), 'hierarchical' =&gt; true, //'supports' =&gt; array('title','editor','custom-fields'), ) ); register_post_type('performer', array( 'label' =&gt; 'Performers', 'public' =&gt; true, 'show_ui' =&gt; true, 'query_var' =&gt; 'performer', 'rewrite' =&gt; array('slug' =&gt; 'performers'), 'hierarchical' =&gt; true, //'supports' =&gt; array('title','editor','custom-fields'), ) ); if ( function_exists('p2p_register_connection_type') ) p2p_register_connection_type( 'event', 'performer' ); global $wp_rewrite; $wp_rewrite-&gt;flush_rules(false); // This only needs be done first time } </code> Then within your theme's template file <code> single-event.php </code> you can add code like the following to display information about each Band (I showed the basics here; I'll leave for you to fill in all the details and/or to ask other more specific questions here on the WordPress Answers site such as if you need to know how to get the featured image, etc.) <code> &lt;?php if (count($performers = p2p_get_connected($post-&gt;ID))) { foreach($performers as $performer_id) { $performer = get_post($performer_id); echo 'The Band: ' . apply_filters('the_title',$performer-&gt;post_title); echo 'Facebook Link: ' . get_post_meta($post-&gt;ID,'facebook_link',true); } } ?&gt; </code>
How to insert content from another Custom Post type into Post?
wordpress
im trying to redirect the loggedin user to a page i created on the backend, i want to use my index to do so so, i added a <code> do_action </code> wrapped in an if statement <code> is_user_loggedin() </code> to call my function. here's the function: <code> function my_redirect() { global $bp; if ( $bp-&gt;current_component == $bp-&gt;root_domain ) { bp_core_redirect($bp-&gt;current_component == MY_CUSTOM_SLUG ); } } </code> but it's not working. The page shows when you navigate to it, but it wont redirect when viewing the root page (index). Here's whats in the index.php <code> &lt;?php if ( is_user_logged_in() ) : ?&gt; &lt;?php do_action( 'my_redirect'); ?&gt; &lt;?php endif; ?&gt; </code> Thanks ahead of time :)
I think what you're trying to do here is create a custom hook. You should just do this to make it work correctly: <code> &lt;?php if ( is_user_logged_in() ) my_redirect(); ?&gt; </code> There's no need to make it an action if you can use the function directly in your template. Actions are primarily used when you want to alter the behavior of core or you don't want to alter an already existing template. Since you're creating your own template anyway, just call the function directly to reduce overhead. I would do this before get_header() or any characters are rendered or you will receive a PHP error.
2 small questions: How to redirect to a created page & show that pages title in wp, bp
wordpress
I am currently using a plug-in called Wishlist member. It allows you to create membership levels in WordPress. I want to be able to display different content on a page depending on the membership level of the viewing user. Something like this - <code> &lt;?php global $current_user; get_currentuserinfo(); if ($current_user-&gt;user_level == 10 ) { ?&gt; Admin Stuff (In my case I left this blank) &lt;?php } else { ?&gt; Stuff Seen By Visitors &lt;?php } ?&gt; </code> But not just for the admin. I have found that this plug-in create creates these for each member level "wpm_access[1296320588]" and "wpm_level[1296320588]". Any ideas on how I could check the current user against this? Thanks!
there is a lot of discussion about this in wishlisMembers support forum but the developers over there ignore it. Any way try this: <code> // get the current user level from WP more important is global $user. $user = wp_get_current_user(); // Get user levels from WishlistMembers $levels = WLMAPI::GetUserLevels($user-&gt;ID); //then run the check for the level you want like this: if(in_array('silver', $levels)){ // PRINT OUT THE silver LEVEL stuff here } elseif (in_array('gold', $levels)){ // PRINT OUT THE gold LEVEL stuff here } </code> Simple.
Conditional Tags for Membership Levels when using Wishlist Member Plugin?
wordpress
I've read several topics about this and different ppl have different views on the best practice. In terms of WP, how do I store data to DB the safest way? This is one insert I'm using now: <code> $result = $wpdb-&gt;insert($table_name , array( 'arena' =&gt; $galleryData['arena'], 'year' =&gt; substr($galleryData['season'], 2), 'copyright' =&gt; $galleryData['copyright'], 'description' =&gt; $galleryData['description'], 'path' =&gt; $galleryData['path'], 'fk_brand_id' =&gt; $galleryData['brand'] ), array( '%s', '%d', '%s', '%s', '%s', '%d' )); </code> Reading a book, another way of inerting data is doing this: <code> $sanitized_sql = $wpdb-&gt;prepare(“ ’INSERT INTO my_plugin_table SET field1 = %1$d, field2 = %2$s, field3 = %3$s’, 32, ‘Aaron Brazell’, ‘Washington, D.C’); $wpdb-&gt;query( $sanitized_sql ); </code> Do I still need to sanitize data using <code> wp_kses </code> or <code> mysql_real_escape_string </code> ? I'm just confused on what method is the better for safely storing data to DB. I found one answer here: stackexchange-url ("stackexchange-url So should I or should I not sanitize data before input?
No the sanitization is already done. Well the mysql_real_escape_string is done, it's considered bad form to filter html on input. I personally think doing it on output kinda breaches DRY. If you did in WordPress I highly suspect somewhere else will do it again resulting in double html entities encoding. Also by the way, wpdb::insert is basically just a wrapper for wpdb::prepare.
What is the best way to sanitize data?
wordpress
I am adding a meta box in the create post/page interface and I want to get the ID of the post being edited/created so I can dynamically display the value of the input field. From the wordpress codex http://codex.wordpress.org/Function_Reference/add_meta_box : <code> /* Prints the box content */ function myplugin_inner_custom_box() { // Use nonce for verification wp_nonce_field( plugin_basename(__FILE__), 'myplugin_noncename' ); // The actual fields for data entry echo '&lt;label for="myplugin_new_field"&gt;' . __("Description for this field", 'myplugin_textdomain' ) . '&lt;/label&gt; '; echo '&lt;input type="text" id= "myplugin_new_field" name="myplugin_new_field" value="whatever" size="25" /&gt;'; } </code> How do I pass the ID to <code> myplugin_inner_custom_box() </code> ? So I can use the following within it: <code> // Get the value of the meta key that is associated to the page $as_meta_value = get_post_meta( $post_id, 'as_link_to_image', true ); </code> and replace the <code> whatever </code> value with the value of the meta key in the input field.
Try <code> get_the_ID() </code> or <code> global $post; $post-&gt;ID </code> .
Get post ID from the Create post/page admin interface?
wordpress
I want to know the correct way to load existing scripts in <code> wp-includes/js/jquery/ </code> Example I want to load <code> jQuery UI Tabs </code> What I have done for now <code> function sample_exists_code() { echo '&lt;script type="text/javascript" src="'. CONSTANTS_JS .'/jquery.js"&gt;&lt;/script&gt;'."\n"; echo '&lt;script type="text/javascript" src="'. CONSTANTS_JS .'/jquery-ui.js"&gt;&lt;/script&gt;'."\n"; } add_action('admin_head', 'sample_exists_code'); </code> and this code working fine to load the UI tabs. But when I try use this code and it's not working <code> function sample_exists_code() { wp_enqueue_script('jquery'); wp_enqueue_script('jquery-ui-tabs'); } add_action('admin_head', 'sample_exists_code'); </code> Let me know the correct way to call the existing scripts. Update : <code> // load existings js and template css. function sample_admin_js_head() { wp_enqueue_script('jquery-ui-tabs', null, array('jquery-ui-core','jquery'), null, false); echo '&lt;link rel="stylesheet" type="text/css" href="' . CONSTANTS_STYLES . '/style.css" /&gt;' . "\n"; } // load up the menu page function sample_add_page() { $optionpage = add_theme_page(__('Theme Options'), __('Theme Options'), 'edit_theme_options', 'sample', 'sample_do_template'); add_action( "admin_print_scripts-$optionpage", 'sample_admin_js_head' ); } add_action('admin_menu', 'sample_add_page'); </code>
Hi @haha: <code> 'admin_init' </code> is definitely an\ workable way to load scripts but you might also want to take a look at this blog post and consider using the <code> "admin_print_scripts-{$page}" </code> hook instead which can allow you to only load on your page when you need it and not burden the other admin pages: How To: Load Javascript With Your WordPress Plugin Here's code from the blog post, albeit modified a bit: <code> $your_page = add_management_page('myplugin','myplugin',9,__FILE__, 'yourplugin_admin_page'); add_action("admin_print_scripts-{$your_page}",'yourplugin_jquery_tabs_loader'); function yourplugin_jquery_tabs_loader() { // what your plugin needs in its &lt;head&gt; } </code>
How to load default scripts included with WordPress correctly?
wordpress
My question is how do I customize the default WordPress login and register page without editing WP's core files. I'm thinking more along the lines of a functions.php code. Can anyone help me out by finding a tutorial or something? Remember, I don't want to edit the WP core files. Thanks!
Here's my functions.php that you can copy the functions. My CSS is admittedly thrown together fast and could be neater. I'm in a hurried launch phase right now. But you can use the functions. The first adds css to your head of the login page to override the styles. The later two functions change the url and title attribute of the logo link. // LOGIN - custom style function my_login_style() { echo ' #login { background:none; border:0; box-shadow:0; -moz-box-shadow: none; /* Firefox */ -webkit-box-shadow: none; /* Safari, Chrome */ box-shadow: none; /* CSS3 */ } #nav { background:none; } form { -moz-box-shadow: 0 4px 18px #0b0b0b; -webkit-box-shadow: 0 4px 18px #0b0b0b; box-shadow: 0 4px 18px #0b0b0b; } #login form#loginform, #login form#registerform, #login form#lostpasswordform { border: 1px solid #fff; } #login h1 { margin-bottom: 10px; } #login h1 a { width:300px; height:85px; margin: 0 auto 31px; } #login form#loginform #user_login, #login form#loginform #user_email, #login form#registerform #user_login, #login form#registerform #user_email, #login form#lostpasswordform #user_login, #login form#loginform #user_pass, #login form#loginform #openid_identifier { border: 1px solid #aaa; } #login form .submit input { background: #2bab44 url("zhttp://www.domain.com/site/themes/mytheme/img/login-button-gradient8.png") left top repeat-x !important; border: 1px solid #008717 !important; text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.3); padding: 5px 20px; } #login form .submit input:hover { background: url("http://www.my.com/site/themes/my/img/login-button-gradient7.png") left -24px repeat-x !important; border: 1px solid #2b8c35 !important; text-shadow: -1px -1px 0 rgba(0, 0, 0, 0.3); } #login form .submit input:active { padding: 5px 20px; /*reqd here for some reason */ } body.login p#nav a { color: #888 !important; text-shadow:none; font-weight:normal; letter-spacing:0; } body.login p#nav a:hover { color: #88eb86 !important; text-decoration: underline; } .login #backtoblog a { display:none; } #login #login_error { font-size: 13px; font-weight: normal; text-shadow: none; margin: -11px auto 0; padding: 12px; width: 275px; background: #ffb5b4; border: 1px solid #db5858; -moz-border-radius: 10px !important; border-radius: 5px; } #login .message { font-weight: normal; color: #bbb; text-shadow: none; } #user_pass, #user_login, #user_email { background: #fff; } '; } add_action('login_head', 'my_login_style'); //// LOGIN - function to change link of logo on login page function my_login_custom_site_url($url) { return get_bloginfo('siteurl'); //return the current wp blog url } add_filter("login_headerurl","my_login_custom_site_url"); //// LOGIN - function to change link title of logo on login page (remove's WordPress' slogan) function my_login_header_title($message) { return False; /*return the description of current blog */ } add_filter("login_headertitle","my_login_header_title");
How to customize wordpress login/register pages?
wordpress
Based on this stackexchange-url ("post"), I'm hoping to create good categories now, that I won't have to change much later. Can you change a category name later, without having to go back and re-categorize all articles? Using the category "Information Technology" as a challenging example, would you call it: a. IT b. I.T. c. InfoTech d. InformationTechnology e. Information Technology (in other words, is shorter better? any downside of long category names? any problem with a space in the category?)
1.: Yes (Slugs differ then, but no need for you to re-categorize each post) 2.: As you wrote: "Information Technology". As a rule of thumb, Category Names should be between 2 and 26 characters, the actual length depends on your site and your needs as there is no hard nor soft limit to category length and there is no "ideal" or "perfect" category length. This needs to be decided individual based on preference and site content, context and the the current time. See as well stackexchange-url ("your previous question").
Length of Category Names
wordpress
How do I customize how my theme shows up in the list of available themes in the Admin console, under the "Appearance" -> "Themes" section. I need to change stuff like the theme name, author, and description.
Hi @Farinha: You need to create a <code> screenshot.png </code> and store it in the theme directory. See the directory for the TwentyTen theme: That of course looks like this: UPDATE To update the theme name, author, and description you modify the header of the style.css file. Take the one from TwentyTen as an example; everything but <code> Theme Name: </code> is optional: <code> /* Theme Name: Twenty Ten Theme URI: http://wordpress.org/ Description: The 2010 theme for WordPress is stylish, customizable, simple, and readable -- make it yours with a custom menu, header image, and background. Twenty Ten supports six widgetized areas (two in the sidebar, four in the footer) and featured images (thumbnails for gallery posts and custom header images for posts and pages). It includes stylesheets for print and the admin Visual Editor, special styles for posts in the "Asides" and "Gallery" categories, and has an optional one-column page template that removes the sidebar. Author: the WordPress team Version: 1.1 Tags: black, blue, white, two-columns, fixed-width, custom-header, custom-background, threaded-comments, sticky-post, translation-ready, microformats, rtl-language-support, editor-style */ </code>
Customize how a Wordpress theme looks like in the Theme Selector
wordpress
I am in trouble, I need help. Whenever I edit any theme code in my dashboard/appearance/editor and try to save it, the file is not saved and it automatically directs me to the homepage. I don't know why is this happening. I cleared the cache through the W3-Total Cache plugin. A few hours before I did the same process, it was working perfectly. But now some problem is there with WordPress. I also tried this in a different browser, but the same things happens. I am using the latest version of WordPress.
I experienced an issue similar to this several months ago. I was using a plugin to kill query strings from the URL for SEO purposes. Long story short the plugin was killing search pages and admin pages as well. As Chris_O mentioned the redirection plugin I encountered a similar redirection issue when track modify posts is enabled. The plugin is smart enough to realize when you edit a post or page and will set up a redirect if the post or page's permalink has changed. However, when creating a new page this feature will create a redirect back to the root because the page has never existed before. More found here (http://www.blakeimeson.com/wordpress-redirection-plugin-home-page-redirect-problem-bug/ and http://tulsawebresults.com/solution-wordpress-redirection-plugin-error ).
Redirecting to home-page when saving any edited code
wordpress
I try to change the main loop in such a way: I have a meta key for displaying featured items, that should be shown only on the home page of the a blog. I pull them in a code separate from the main loop, something like - <code> $leading = get_posts('showposts=5&amp;meta_key=_pull_leading3&amp;meta_value=on'); foreach ($leading as $post) : setup_postdata($post); //some code to show posts data endforeach; </code> Then in the main loop, I want to show only posts that are not assigned as featured, so I alter the main loop with query_posts : <code> query_posts('posts_per_page=7&amp;paged='.$paged.'&amp;meta_key=_pull_leading3&amp;meta_value=off'); </code> Till here everything is ok. But, I also want that if I go to any other older pages, I will get the featured posts again, if they should be there naturally via the regular order. In this case, since I use the meta values, I don't get them. If I try something like this - <code> if (is_home() &amp;&amp; $paged == '0') { //$paged value is 0 on 1st page and not 1 ! query_posts('posts_per_page=7&amp;paged='.$paged.'&amp;meta_key=_pull_leading3&amp;meta_value=off'); } else { query_posts('posts_per_page=7&amp;paged='.$paged); } </code> Then on page #2 I do get the posts as needed, but i is repeating part of the posts that were on page #1 (home page) (Since in homepage loop I showed only posts that are not featured, so since that part of the posts already shown there, and now should be excluded from page #2). How can I alter the main loop in a way that the main page will show the posts that are not featured, and that the other $paged pages will show posts in a native way, no matter if they are featured or not, and without repeating posts from the previous page? I really hope I succeed to explain my issue... Many thanks, Maor
I think this will do what you want. But I still wonder whether sticky posts wouldn't have been better... <code> if (is_home() &amp;&amp; $paged == '0') { //$paged value is 0 on 1st page and not 1 ! query_posts('posts_per_page=7&amp;paged='.$paged.'&amp;meta_key=_pull_leading3&amp;meta_value=off'); } else { // recreate the home page "loop" to figure out which posts to exclude $excluded = array_map( create_function('$post', 'return $post-&gt;ID;' ), get_posts('numberposts=7&amp;meta_key=_pull_leading3&amp;meta_value=off') ); query_posts( array( 'posts_per_page' =&gt; 7, 'paged' =&gt; $paged-1, // since we already excluded the first page 'post__not_in' =&gt; $excluded) ); } </code>
Modify main loop query for paged and meta key
wordpress
I'm adding this filter when the condition is true. Can I add another function on the same filter when the 2nd condition is true or will the last one cancel out the previous one? <code> if(get_option('my_nofollow_flag'){ add_filter('wp_insert_post_data', 'save_add_nofollow' ); } if(get_option('my_second_option'){ add_filter('wp_insert_post_data', 'another_function' ); } </code>
Hi @Scott B: Absolutely. That's part of the design of the system, you can add as many as you need (other plugins do.) The only issue is if you might need to address which one runs first and that's when you may have to set the priority. In the below example the third one would run first and the second one would run last: <code> add_filter('wp_insert_post_data','norm_priority_func'); // 10=default priority add_filter('wp_insert_post_data','run_last_funcn', 11 ); add_filter('wp_insert_post_data','run_first_func', 9 ); </code> Of course when you have needs to set priorities you can find it may cause conflict with other plugins that set a priority higher or lower. Typical places where this happens is when you want a hook to run either before or after all others. Are 0 and 100 sufficient priorities? Not if another plugin used -1 and 101; see the quandry? Anyway, that's usually not an issue but when it is, it is.
add_filter multiple times with different addon functions?
wordpress
How can i change my front end menu depending on if the user is logged in or not? For Example: View 1: user is not logged in menu is : home , about us, testimonials View 2: user is logged in menu is : dashboard, my profile, support Thanks in advance.
Hi @rxn: Define two menus and serve them based on if they are logged in or not which you can do in your theme's <code> functions.php </code> file: <code> if (is_user_logged_in()){ wp_nav_menu( array( 'menu' =&gt; 'Logged In Menu', 'container_class' =&gt; 'logged-in-menu', 'theme_location' =&gt; 'logged-in' )); } else { wp_nav_menu( array( 'menu' =&gt; 'Visitor Menu', 'container_class' =&gt; 'visitor-menu', 'theme_location' =&gt; 'visitor' )); }; </code> You'll also need to register their theme locations which you can do in your theme's <code> functions.php </code> file as well: <code> register_nav_menus( array( 'logged-in' =&gt; __( 'Logged-in Menu Area', 'yourtheme' ), 'visitor' =&gt; __( 'Visitor Menu Area', 'yourtheme' ), )); </code> And you'll have to assign those menus to their menu locations in the admin, like so:
change front end menu depending on user login
wordpress
Researching various shopping cart solutions for a WordPress based eCommerce website. Based on research, it seems that two plugins stand out: shopplugin.net phpurchase.com Can anyone share their experiences with these or offer some good alternatives? The list of requirements is too long to include here, but the store will be shipping goods (not digital products) and the ability to have a robust marketing/promotional campaign integrated into the shopping experience is important, as is financial reporting. Product recommendations, coupons, sale prices/discounts, email marketing and a customer database would all be nice features to have. I don't like WP-ecommerce or most of the other free options and the budget for software is as much as $1,000 (alternatively looking at shopify.com, a non-WP product). Thanks in advance!
WooCommerce all the way: http://www.woothemes.com/woocommerce/
Shopping Cart Integration -- Experiences with Popular eCommerce Solutions
wordpress
I have been trying to work out just where in the massive jungle of Wordpress include classes the usermeta table is joined onto the users table and if so, how does it work? The one confusing thing about the usermeta table to me is that it is using key/value fields for the database fields and not actual values like first_name or last_name. How does Wordpress know which fields to pull out by default and are there hooks, actions and filters for adding and retrieving data from the usermeta field?
Hi @Dwayne: I'm not 100% what you are asking, it seems like several questions? But here goes: <code> $meta_value = get_user_meta($user_id, $key, $single); </code> For example: <code> $first_name = get_user_meta($user_id, 'first_name', true); </code> As for adding hooks I think this answer might be what you are looking for? <a href="stackexchange-url How To Add Custom Form Fields To The User Profile Page? UPDATE Based on some follow up comments I'll add: The function <code> get_user_metavalues($user_ids) </code> from <code> /wp-includes/user.php </code> will return an array of user data arrays. The function <code> get_userdata() </code> retrieves user values using <code> get_user_metavalues($user_ids) </code> from <code> /wp-includes/pluggable.php </code> and returns a user data object. User Meta is managed through the generic metadata functions found in <code> /wp-includes/meta.php </code> so if you are looking for a SQL <code> JOIN </code> between wp_users and wp_usermeta you are not likely to find one. That file includes these functions: <code> add_metadata($meta_type,$object_id,$meta_key,$meta_value,$unique=false) update_metadata($meta_type,$object_id,$meta_key,$meta_value,$prev_value='') delete_metadata($meta_type,$object_id,$meta_key,$meta_value='',$delete_all=false) get_metadata($meta_type,$object_id,$meta_key='',$single=false) update_meta_cache($meta_type,$object_ids) </code>
In what part of the Wordpress core does the users table and usermeta table get joined?
wordpress
Is WordPress adding anchor tags automatically? I'm really puzzled, this is the code: home.php <code> &lt;div class="post-bottom"&gt; &lt;?php if ( count( get_the_category() ) ) : ?&gt; &lt;span class="cat-links"&gt; &lt;?php printf( __( 'Posted in %2$s', 'twentyten' ), 'entry-utility-prep entry-utility-prep-cat-links', get_the_category_list( ', ' ) ); ?&gt; &lt;/span&gt; &lt;span class="meta-sep"&gt;|&lt;/span&gt; &lt;?php endif; ?&gt; &lt;?php $tags_list = get_the_tag_list( '', ', ' ); if ( $tags_list ): ?&gt; &lt;span class="tag-links"&gt; &lt;?php printf( __( '&lt;span class="%1$s"&gt;Tagged&lt;/span&gt; %2$s', 'twentyten' ), 'entry-utility-prep entry-utility-prep-tag-links', $tags_list ); ?&gt; &lt;/span&gt; &lt;span class="meta-sep"&gt;|&lt;/span&gt; &lt;?php endif; ?&gt; &lt;span class="comments-link"&gt;&lt;?php comments_popup_link( __( 'Leave a comment', 'twentyten' ), __( '1 Comment', 'twentyten' ), __( '% Comments', 'twentyten' ) ); ?&gt;&lt;/span&gt; &lt;?php edit_post_link( __( 'Edit', 'twentyten' ), '&lt;span class="meta-sep"&gt;|&lt;/span&gt; &lt;span class="edit-link"&gt;', '&lt;/span&gt;' ); ?&gt; &lt;/div&gt;&lt;!-- .entry-utility --&gt; </code> this is the final output: EDIT: Output Source Code: <code> &lt;div class="post-bottom"&gt; &lt;span class="cat-links"&gt; Posted in &lt;a href="http://localhost/wpa/category/uncategorized/" title="View all posts in Uncategorized" rel="category tag"&gt;Uncategorized&lt;/a&gt; </code> Image: The Posted in part has link color and behaves like a link but with no pointer. EDIT2 Weird I deleted <code> the_excerpt() </code> and it seemed to fix the problem. But still can't understand what happens: <code> &lt;div class="posted-on"&gt;&lt;?php twentyten_posted_on(); ?&gt;&lt;/div&gt; &lt;p&gt;&lt;?php the_excerpt(); ?&gt;&lt;/p&gt; &lt;div class="post-bottom"&gt; &lt;?php if ( count( get_the_category() ) ) : ?&gt; </code>
Hi @janoChen: The function <code> get_the_category_list() </code> in <code> /wp-includes/category-template.php </code> adds the anchors that you are asking about. You can find it on line 175 in WordPress v3.0.4. I also notice that you posted what looks like an object inspector from Chrome or Safari. Sometimes when the code that is output is not valid HTML because of what can be contained and what cannot the object inspector will show the DOM view which differs from "View Source" . You can inspect the source and see if it is different from the object inspector?
Anchor tag in the entry-utility section ( the Posted in...part) appears from nowhere?
wordpress
I found a code scrap on the internet which uses <code> if($user_id) { </code> instead of <code> if ( is_user_logged_in() ) { </code> to check if the user is logged in. I would assume that the first would be slightly faster because it's not running a function, but can anyone verify that this would always work?
Well it wouldn't always work unless you global $user_id. is_user_logged_in will however work without that extra line of code. The speed improvement is most likely so small it's less than the speed improvement between single and double quotes and not even worth thinking about. Also $user_id variable may disappear in a new version and would promptly break your code, were as is_user_logged_in will be about for ages even if they decide to deprecate it.
$user_id vs. is_user_logged_in()
wordpress
I'm going back and reworking categories and tags on some older posts. So I'm going back in time, to say for example page 4 of my posts. I know there are search filters, which might help, but let's follow through with this scenario. I'm on page 4, and update the first post on that page. Now, is there a fast way to get back to page 4 to update the second post on that page? If I've changed a lot of tags or categories, I don't want to hit the browser back key five to ten times. Any shortcut I don't see in this case?
Open post to edit in new browser tab/window so that page X remains in original tab/window?
How to get back to same page of post-list - after updating a post
wordpress
I'm using the_time function to print the current date on my site. The problem is, that it's returning post or page creation times on pages other than the front page. Can I force it to print the current time on all views?
the_time() function is a WordPress built-in function to display the time of the post creation. So if you want to display the current date and time you need to use php function date something like this: <code> &lt;?php // Assuming today is March 10th, 2001, 5:16:18 pm, and that we are in the // Mountain Standard Time (MST) Time Zone $today = date("F j, Y, g:i a"); // March 10, 2001, 5:16 pm $today = date("m.d.y"); // 03.10.01 $today = date("j, n, Y"); // 10, 3, 2001 $today = date("Ymd"); // 20010310 $today = date('h-i-s, j-m-y, it is w Day'); // 05-16-18, 10-03-01, 1631 1618 6 Satpm01 $today = date('\i\t \i\s \t\h\e jS \d\a\y.'); // it is the 10th day. $today = date("D M j G:i:s T Y"); // Sat Mar 10 17:16:18 MST 2001 $today = date('H:m:s \m \i\s\ \m\o\n\t\h'); // 17:03:18 m is month $today = date("H:i:s"); // 17:16:18 // and echo it out echo $today; ?&gt; </code> Hopes this helps.
How to call the_time current?
wordpress
I am trying to hook 'wpmu_new_blog' in a plugin so I can copy the widget settings from one blog to the new blog that is being created. Does anyone know if there are WordPress functions to accomplish this, or should I just use straight SQL? Thanks, Dave
I don't think there is anything specifically for this. You might want to look at the plugin code to find calls to <code> get_option() </code> and see what keys they are using, then browse the DB table <code> wp_options </code> with phpMyAdmin (or whatever) and grab the associated values. Without specific support from the plugin this can be iffy since there may be other context-dependent info in there that you don't want on the new site.
Copy widget settings from one blog to another
wordpress
I downloaded various themes on net and I found on <code> functions.php </code> they write something like this Example to remove inline comment style. <code> function demo_remove_recent_comments_style() { add_filter( 'show_recent_comments_widget_style', '__return_false' ); } add_action( 'widgets_init', 'demo_remove_recent_comments_style' ); </code> Question Why we not write only this without a <code> function() </code> <code> add_filter( 'show_recent_comments_widget_style', '__return_false' ); </code> Let me know
It is not always required technically but it is good practice to follow for multiple reasons: Code is more organized by keeping hook-related stuff together The more precise conditions when it runs - the better for performance It is easier to unhook function, that performs multiple add _, then unhook each add _ individually. The order of adding functions matters when not specifying priority. The child theme (if used) is processed before parent theme and it can lead to confusing stuff with hooks if add _ and remove _ are performed inline. Of course in some specific examples (yours does fit) it does seem overly verbose to write out all of that just to manipulate single item on single hook. Myself I use couple of my own (and somewhat messy functions) - <code> add_filter_return() </code> and <code> add_action_with_arguments() </code> to lower amount of wrapping when working with hooks.
It's okay if I do not write add_action()
wordpress
I just placed this in my <code> functions.php </code> (I'm using Wordpress 3.0.4): <code> function new_excerpt_more($more) { global $post; return '&lt;a href="'. get_permalink($post-&gt;ID) . '"&gt;Read the Rest...&lt;/a&gt;'; } add_filter('excerpt_more', 'new_excerpt_more'); </code> But my post is still displaying <code> … Continue reading </code> Any suggestions?
Hi @janoChen: Your theme (or a plugin) is overriding your filter. Try increasing the priority like this: <code> add_filter('excerpt_more', 'new_excerpt_more',11); </code> Or like this: <code> add_filter('excerpt_more', 'new_excerpt_more',20); </code> And if that doesn't work try: <code> add_filter('excerpt_more', 'new_excerpt_more',100); </code>
I can't modify the 'Continue reading...' link of the_excerpt
wordpress
Wordpress states the following: An excerpt is a condensed description of your blog post and refers to the summary entered in the Excerpt field of the Administration > Posts > Add New SubPanel. The excerpt is used to describe your post in RSS feeds and is typically used in displaying search results. The excerpt is sometimes used in displaying the Archives and Category views of your posts. Use the Template Tag the_excerpt() to display the contents of this field. Note that if you do not enter information into the Excerpt field when writing a post, and you use the_excerpt() in your theme template files, WordPress will automatically display the first 55 words of the post's content. I wrote a post of 164 words. And placed this into my posts page: <code> &lt;div class="mainbar"&gt; &lt;?php // Create custom loop $custom_posts = get_posts('post_type=page_content&amp;page_sections=Content (Front Page)'); ?&gt; &lt;?php foreach( $custom_posts as $post ) : setup_postdata( $post ); ?&gt; &lt;div class="content-block"&gt; &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt; &lt;?php the_excerpt(); ?&gt; &lt;/div&gt;&lt;!-- .content-block --&gt; &lt;?php endforeach; ?&gt; &lt;?php wp_reset_query(); ?&gt; &lt;/div&gt;&lt;!-- #mainbar --&gt; </code> I'm still seeing 164 words in that post. EDIT: This is what I've written in the post: <code> Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat. Lorem ipsum dolor sit amet, consectetuer adipiscing elit, sed diam nonummy nibh euismod tincidunt ut laoreet dolore magna aliquam erat volutpat. Ut wisi enim ad minim veniam, quis nostrud exerci tation ullamcorper suscipit lobortis nisl ut aliquip ex ea commodo consequat </code> . I tried exceeding 55 words in other post and it is the same story. Any suggestions?
Hi @janoChen: Are you sure that code it running and not some other code? I just traced through the code and the only way it's going to do that is if you have a plugin or code in your theme that is hooking one of the following hooks: <code> 'the_excerpt' </code> , <code> 'get_the_excerpt' </code> , <code> 'wp_trim_excerpt' </code> or possibly removed the <code> 'get_the_excerpt' </code> hook that calls <code> wp_trim_excerpt() </code> . What plugins or other code to you have installed?
the_excerpt is not limiting my post page to 55 words?
wordpress
I search on this site and found many stackexchange-url ("answers") for this question. Most of them is not working on my theme. Here is a one solution I found and it's working according to my need. <code> function wp_nav_menu_no_ul() { $options = array( 'echo' =&gt; false, 'container' =&gt; false, 'theme_location' =&gt; 'primary' ); $menu = wp_nav_menu($options); echo preg_replace(array( '#^&lt;ul[^&gt;]*&gt;#', '#&lt;/ul&gt;$#' ), '', $menu); } </code> This code will remove <code> ul </code> at beginning and the end of <code> wp_nav_menu() </code> . So in my theme I just write <code> &lt;ul class="primary-nav"&gt; &lt;?php wp_nav_menu_no_ul(); ?&gt; &lt;/ul&gt; </code> But the problem is coming again when I do not add or activate any menu via admin. <code> http://domain.com/wp-admin/nav-menus.php </code> Question : How do I remove the <code> &lt;div&gt;&lt;ul&gt;**&lt;/ul&gt;&lt;/div&gt; </code> whether the menu is active or not. Let me know Finally I got it worked :) <code> functions.php </code> <code> function wp_nav_menu_no_ul() { $options = array( 'echo' =&gt; false, 'container' =&gt; false, 'theme_location' =&gt; 'primary', 'fallback_cb'=&gt; 'default_page_menu' ); $menu = wp_nav_menu($options); echo preg_replace(array( '#^&lt;ul[^&gt;]*&gt;#', '#&lt;/ul&gt;$#' ), '', $menu); } function default_page_menu() { wp_list_pages('title_li='); } </code> <code> header.php </code> <code> &lt;ul class="primary-nav"&gt; &lt;?php wp_nav_menu_no_ul(); ?&gt; &lt;/ul&gt; </code>
The function wp_nav_menu takes an argument of fallback_cb which is the name of the function to run if the menu doesn't exist. so change you code to something like this: <code> function wp_nav_menu_no_ul() { $options = array( 'echo' =&gt; false, 'container' =&gt; false, 'theme_location' =&gt; 'primary', 'fallback_cb'=&gt; 'fall_back_menu' ); $menu = wp_nav_menu($options); echo preg_replace(array( '#^&lt;ul[^&gt;]*&gt;#', '#&lt;/ul&gt;$#' ), '', $menu); } function fall_back_menu(){ return; } </code> you can even remove the container from the menu and do other stuff with some more arguments sent to the wp_nav_menu function Hope this helps.
How do I remove UL on wp_nav_menu?
wordpress
Hello I would like to know if there is a way to pull the contents of comments on a post to a separate page from wordpress. currently this is what i have, i'd like to replace with a function to pull the comments instead of pulling the link to the comments. <code> &lt;?php // Include Wordpress define('WP_USE_THEMES', false); require('./blog/wp-load.php'); ?&gt; &lt;div&gt; &lt;p style="font-size:18px;color:white;font-wieght:700;"&gt;Recently Asked Questions&lt;/p&gt; &lt;?php query_posts('showposts=3'); ?&gt; &lt;?php while (have_posts()): the_post(); ?&gt; &lt;div id="faq"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title() ?&gt;&lt;/a&gt;&lt;br /&gt; &lt;?php the_time('F jS, Y') ?&gt; &lt;?php the_excerpt(); ?&gt; &lt;?php comments_popup_link(); ?&gt; To see the answer to the question click &lt;a href="&lt;?php the_permalink() ?&gt;"&gt;here&lt;/a&gt;.&lt;br /&gt;&lt;br /&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; </code> Any help is appreciated, thank you.
add to your loop and replace it with the the_permalink() function something like this: <code> &lt;?php // Include Wordpress define('WP_USE_THEMES', false); require('./blog/wp-load.php'); ?&gt; &lt;div&gt; &lt;p style="font-size:18px;color:white;font-wieght:700;"&gt;Recently Asked Questions&lt;/p&gt; &lt;?php query_posts('showposts=3'); ?&gt; &lt;?php while (have_posts()): the_post(); ?&gt; &lt;div id="faq"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title() ?&gt;&lt;/a&gt;&lt;br /&gt; &lt;?php the_time('F jS, Y') ?&gt; &lt;?php the_excerpt(); ?&gt; &lt;?php comments_popup_link(); ?&gt; &lt;?php comments_template( '', true ); ?&gt; &lt;br /&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; </code>
how to pull wordpress post comments to a external page
wordpress
I want to extract the first oEmbed url inserted on the content of a post in order to put in a meta tag from the header, or elsewhere as a way to style it differently from the rest of the content.
I assume that you're only interested in the first URL that actually succeeds at discovering actual oembed data. The oembed system processes all links it finds, but not every link will have oembed going for it, obviously. The filter you'll want to use is embed_oembed_html and it gets the HTML cached by oembed, the url, any attributes on the embed, and the post_ID, which is important for your code. <code> add_filter('embed_oembed_html', 'my_function',10,4); function my_function( $cache, $url, $attr, $post_ID ) { global $my_previous_post_id; if ($my_previous_post_id != $post_ID) { // post ID changed, so this is the first oembed for the post // do something with $url $my_previous_post_id = $post_ID; } return $cache; // it's important that you return the $cache value as-is } </code> Now, the whole oembed system is running at the same time as shortcodes do: during the_content filter call. So if you want to grab stuff for the header, you'll have to start the main Loop in the header, run the_content filter over the get_the_content() value, then call rewind_posts() to rewind the query back to the start for the actual main Loop later on in the page. This sort of behavior causes problems with plugins (like Nextgen gallery) that do stupid things when you run a loop in the header. There's no working around it, but the fact is that those plugins are fundamentally broken and you can't correct their problems. I get this sort of report with SFC-Share and SFC-Like all the time (because they pull content out to put in the header too). Nothing you can do about it, frankly.
Extract the first oembed url inserted on the content of a post
wordpress
Is it possible to insert links in Wordpress's wysiwyg editor that will convert to pretty permalinks when enabled? i.e. the links would be this without pretty permalinks: /?p=13 But with permalinks on, it would become this: /mypagename/ I'm thinking I'd have to use a shortcode to do that right? Something that would use the ID and wp_list_pages() for pages at least... just thinking about a way to get links in content to work when permalinks are on and off. Thanks osu
Here is example of simple shortcode that will take ID as argument and echo permalink for it: <code> function link_from_id($atts) { if( isset($atts['id']) ) return get_permalink( (int)$atts['id'] ); } add_shortcode('link', 'link_from_id'); </code> Usage: <code> [link id=1] </code> PS by the way non-pretty permalinks will keep working just fine if you enable pretty mode later and, if I remember right, will be redirected to canonical pretty version.
Adding page links to content that automatically convert to pretty permalinks?
wordpress
This seems like it should be easy to do, but I've not been able to find or work out a solution. I'm using the Starkers theme and Wordpress 3.0.4, and my site auto-generates its navigation as per normal. I would like however the navigation to only show the top level pages , i.e. not display links to any pages that are children of other pages. This is the code I am currently using. <code> &lt;?php wp_nav_menu( array( 'container' =&gt; 'nav', 'fallback_cb' =&gt; 'starkers_menu', 'theme_location' =&gt; 'primary' ) ); ?&gt; </code> I would like to hide the child links programmatically, but I am prepared to use CSS if someone can instead advise how to assign specific classes to the child links. Thanks in advance for any help. **edit 2** I've tracked down the actual function I am using, called starkers_menu (below). However adding depth to this, or even removing the other exclusions and just using depth doesn't work either: <code> function starkers_menu() { echo '&lt;nav&gt;&lt;ul&gt;'; wp_list_pages('depth=1&amp;exclude=4,19&amp;title_li='); echo '&lt;/ul&gt;&lt;/nav&gt;'; } </code>
Had you tried <code> depth </code> argument (see <code> wp_nav_menu() </code> documentation)? Also do I understand right that you do not setup menu manually and let theme generate it with custom callback that you have in your code? Update Same answer - try <code> depth </code> argument, only this time in <code> wp_list_pages() </code> call in <code> starkers_menu() </code> function. It should work, unless that function is never processed and not available at the time of menu running. Do you use latest version of theme?.. If not consider updating.
Only show top-level links in site navigation
wordpress