question
stringlengths
0
34.8k
answer
stringlengths
0
28.3k
title
stringlengths
7
150
forum_tag
stringclasses
12 values
I see that there are hooks for manipulating WP_Query before it gets its posts (parse_query, pre_get_posts), but I can't seem to find any hooks for after the WP_Query object is populated. I have a custom table for my plugin-specific post-associated meta data that I would like to fetch from after a WP_Query object is populated.
As you haven't stated what you are trying to achieve and have just mentioned you need to fetch associated data. You have two options to query your custom table: You need to do a custom query separately using the post id from the post object while iterating over the posts. Modify the joins of main WordPress query, so WordPress fetches the data from your custom table already associated with their respective posts. The example below demonstrates first method. <code> &lt;?php function populate_posts_data( $posts, $query ) { global $wpdb; if ( !count( $posts ) ) return $posts; // posts array is empty send it back with thanks. while ( $posts as $post ) { // query to get custom post data from custom table $query = "SELECT * FROM {$wpdb-&gt;prefix}my_plugin_table WHERE post_id={$post-&gt;ID}"; $results = $wpdb-&gt;get_results( $query ); } return $posts; } add_filter( 'the_posts', 'populate_posts_data' ); ?&gt; </code> For the second method you will need to look at posts_where, posts_join, posts_groupby and posts_orderby filters. As an example you can have a look at the @scribu's sortable custom column's example .
Hook/action after WP_Query gets posts to query custom tables for post-related meta
wordpress
I have featured images switched on in my theme: <code> add_theme_support('post-thumbnails'); set_post_thumbnail_size(256,128, true); add_image_size('icon', 128, 128, true); </code> but the Featured Image box isn't showing up anywhere when I edit a page. What's confusing is that the exact same theme, the same set of plugins and approximately the same data is working fine on another site. Is there some config setting that might prevent the Featured Image feature from working?
Have you checked the "Featured Image" check-box within the "Screen Options" drop down menu beneath "Howdy, your username"? If that's not the case, we can look into it even further. Update: WordPress MU users: Try going into "Network Admin", then click on settings, then enable image upload box, and save.
Featured Image meta box not showing up
wordpress
Anyone can recognize the current Wordpress backend, but I don't want that. I want to change it using my own design and I want to have a seamless navigating experience for my users. How can I change the dashboard appearance? I googled a lot of posts and questions, and it seems like you can only change the CSS of most things and some people were using hooks to add their own code and what not.
I use a custom include file that I created to modify the dashboard. Some of the hooks and filters are commented out by default but most of the stuff is here to remove menus, change wp logos, remove meta boxes, remove dashboard widgets, etc... <code> &lt;?php /* File: cleanup-dashboard.php Description: Clean up and customize the dashboard Author: Chris Olbekson Author URI: http://c3mdigital.com */ //Dashboard Action Hooks add_action( 'admin_init', 'c3m_admin_style' ); add_action( 'admin_init', 'c3m_remove_dashboard_meta' ); add_action( 'admin_init', 'c3m_remove_post_meta' ); add_action( 'admin_menu', 'c3m_remove_admin_menus' ); add_action( 'admin_menu', 'c3m_remove_admin_submenus' ); add_filter( 'admin_user_info_links', 'c3m_user_greeting' ); add_action( 'admin_head', 'c3m_custom_logo' ); add_action( 'login_head', 'c3m_custom_login_css' ); add_action( 'login_head', 'c3m_custom_login_logo' ); add_filter( 'admin_footer_text', 'c3m_remove_footer_admin' ); add_action( 'init', 'c3m_change_post_object_label' ); add_action( 'admin_menu', 'c3m_change_post_menu_label' ); add_filter( 'admin_body_class', 'c3m_admin_body_class' ); //Dashboard CSS function c3m_admin_style() { wp_enqueue_style( 'c3m_admin_css', get_bloginfo( 'stylesheet_directory' ) . '/_/admin/c3m-admin.css', false, '1.0', 'all'); } //Removes the dashboard widgets function c3m_remove_dashboard_meta() { remove_meta_box('dashboard_incoming_links', 'dashboard', 'normal'); remove_meta_box('dashboard_plugins', 'dashboard', 'normal'); remove_meta_box('dashboard_primary', 'dashboard', 'normal'); remove_meta_box('dashboard_secondary', 'dashboard', 'normal'); remove_meta_box('dashboard_incoming_links', 'dashboard', 'normal'); remove_meta_box('dashboard_quick_press', 'dashboard', 'side'); // remove_meta_box('dashboard_recent_drafts', 'dashboard', 'side'); remove_meta_box( 'dashboard_recent_comments', 'dashboard', 'normal' ); } function c3m_remove_post_meta() { // remove_meta_box( 'commentstatusdiv', 'page', 'normal' ); // remove_meta_box( 'commentstatusdiv', 'post', 'normal' ); // remove_meta_box( 'commentsdiv', 'page', 'normal' ); // remove_meta_box( 'commentsdiv', 'post', 'normal' ); // remove_meta_box( 'authordiv', 'page', 'normal' ); // remove_meta_box( 'authordiv', 'post', 'normal' ); // remove_meta_box( 'trackbacksdiv', 'post', 'normal' ); // remove_meta_box( 'trackbacksdiv', 'page', 'normal' ); // remove_meta_box( 'postcustom', 'post', 'normal' ); // remove_meta_box( 'postcustom', 'page', 'normal' ); // remove_meta_box( 'slugdiv', 'post', 'normal' ); // remove_meta_box( 'slugdiv', 'page', 'normal' ); //remove_meta_box( 'excerptdiv', 'post', 'normal' ); // remove_meta_box( 'page_choicediv', 'post', 'normal' ); // remove_meta_box( 'page_choicediv', 'sponsor_ad', 'normal' ); } //Remove top level admin menus //Remove top level admin menus function c3m_remove_admin_menus() { remove_menu_page( 'edit-comments.php' ); remove_menu_page( 'link-manager.php' ); remove_menu_page( 'tools.php' ); // remove_menu_page( 'plugins.php' ); // remove_menu_page( 'users.php' ); // remove_menu_page( 'options-general.php' ); } //Remove sub level admin menus function c3m_remove_admin_submenus() { remove_submenu_page( 'themes.php', 'theme-editor.php' ); remove_submenu_page( 'themes.php', 'themes.php' ); remove_submenu_page( 'edit.php', 'edit-tags.php?taxonomy=post_tag' ); remove_submenu_page( 'edit.php', 'edit-tags.php?taxonomy=category' ); // remove_submenu_page( 'themes.php', 'nav-menus.php' ); // remove_submenu_page( 'themes.php', 'widgets.php' ); // remove_submenu_page( 'plugins.php', 'plugin-editor.php' ); // remove_submenu_page( 'plugins.php', 'plugin-install.php' ); // remove_submenu_page( 'users.php', 'users.php' ); // remove_submenu_page( 'users.php', 'user-new.php' ); // remove_submenu_page( 'options-general.php', 'options-writing.php' ); // remove_submenu_page( 'options-general.php', 'options-discussion.php' ); // remove_submenu_page( 'options-general.php', 'options-reading.php' ); // remove_submenu_page( 'options-general.php', 'options-discussion.php' ); // remove_submenu_page( 'options-general.php', 'options-media.php' ); // remove_submenu_page( 'options-general.php', 'options-privacy.php' ); // remove_submenu_page( 'options-general.php', 'options-permalinks.php' ); } //This Adds an extra body class to a custom post type editor screen to target with css function c3m_admin_body_class( $classes ) { global $wpdb, $post; $post_type = get_post_type( $post-&gt;ID ); if ( is_admin() &amp;&amp; ( $post_type == 'sponsor_ad' ) ) { $classes .= 'post_type-' . $post_type; } return $classes; } //Replaces Howdy with Welcome pretty self explanitory function c3m_user_greeting( $greet_msg ) { $greet_msg = str_replace( 'Howdy,','Welcome', $greet_msg); return $greet_msg; } //Admin Header Logo this replaces the WordPress logo with your own function c3m_custom_logo() { echo ' &lt;style type="text/css"&gt; #header-logo { background-image: url('.get_bloginfo('template_directory').'/images/logo_wnd_small.png) !important; width:98px; } &lt;/style&gt; '; } //Admin Footer Logo Same as above but for the footer function c3m_remove_footer_admin() { echo '&lt;div id="wlcms-footer-container"&gt;'; echo '&lt;a target="_blank" href="http://c3mdigital.com"&gt;&lt;img style="width:80px;" src="'.get_bloginfo('template_directory').'/images/developer-logo.png" id="wlcms-footer-logo"&gt;Custom WordPress Development&lt;/a&gt;'; echo '&lt;/div&gt;&lt;p id="safari-fix"'; } //Login Screen CSS Custon css to replace the WP logo on the login screen function c3m_custom_login_css() { echo '&lt;link rel="stylesheet" type="text/css" href="'.get_bloginfo('template_directory').'/_/admin/c3m-login.css" /&gt;'; } //Login Screen Logo this incjects your logo css into the login css page function c3m_custom_login_logo() { echo '&lt;style type="text/css"&gt; h1 a { background-image:url('.get_bloginfo('template_directory').'/images/logo_wnd_new.png) !important; margin-bottom: 20px; height:100px; } &lt;/style&gt; &lt;script type="text/javascript"&gt; function loginalt() { var changeLink = document.getElementById('login').innerHTML; changeLink = changeLink.replace("http://wordpress.org/", "' . site_url() . '"); changeLink = changeLink.replace("Powered by WordPress", "' . get_bloginfo('name') . '"); document.getElementById('login').innerHTML = changeLink; } window.onload=loginalt; &lt;/script&gt; '; } //This changes the name of Posts to something different function c3m_change_post_menu_label() { global $menu; global $submenu; $menu[5][0] = 'Post Boxes'; //$menu[10][0] = 'Files'; $submenu['edit.php'][5][0] = 'Post Boxes'; $submenu['edit.php'][10][0] = 'Add Post Box'; //$submenu['edit.php'][15][0] = 'Status'; echo ''; } //Changes the label for the posts we changed above function c3m_change_post_object_label() { global $wp_post_types; $labels = &amp;$wp_post_types['post']-&gt;labels; $labels-&gt;name = 'Post Boxes'; $labels-&gt;singular_name = 'Add New Post Box'; $labels-&gt;add_new = 'Add Post Box'; $labels-&gt;add_new_item = 'Add Post Box'; $labels-&gt;edit_item = 'Edit Post Box'; $labels-&gt;new_item = 'Post Box'; $labels-&gt;view_item = 'View Post Box'; $labels-&gt;search_items = 'Search Post Boxes'; $labels-&gt;not_found = 'No Post Boxes found'; $labels-&gt;not_found_in_trash = 'No Post Boxes found in Trash'; } //Post Edit Columns Customizes the post edit columns by adding the featured image as a thumbnail and shows the excert // Add to admin_init function add_filter( 'manage_edit-post_columns', 'add_new_post_columns'); add_filter( 'manage_edit-post_columns', 'unset_the_defaults'); add_action( 'manage_posts_custom_column', 'testimonial_custom_column', 10, 2); add_action( 'manage_posts_custom_column', 'testimonial_source_column', 10, 2); function unset_the_defaults($defaults) { unset($defaults['author']); //unset($defaults['title']); return $defaults; } function add_new_post_columns($dfaults) { $dfaults['page_choice'] = 'Displayed On'; $dfaults['article_source'] = 'Source'; $dfaults['post_box_excerpt'] = 'Post Box Excerpt'; $dfaults['post_box_image'] = 'Post Box Image'; return $dfaults; } function testimonial_custom_column($column_name, $post_id){ $taxonomy = $column_name; $post_type = get_post_type($post_id); $terms = get_the_terms($post_id, $taxonomy); if (!empty($terms) ) { foreach ( $terms as $term ) $post_terms[] ="&lt;a href='edit.php?post_type={$post_type}&amp;{$taxonomy}={$term-&gt;slug}'&gt; " .esc_html(sanitize_term_field('name', $term-&gt;name, $term-&gt;term_id, $taxonomy, 'edit')) . "&lt;/a&gt;"; echo join('', $post_terms ); } else echo '&lt;i&gt;No Display Page Set. &lt;/i&gt;'; } function testimonial_source_column($column_name, $post_id) { global $post; global $prefix; if ($column_name == 'article_source') { echo get_post_meta($post_id, $prefix.'article-source', TRUE); } elseif ($column_name == 'post_box_image') { if ( get_post_meta($post_id, $prefix.'post_box_image', TRUE) ) { echo '&lt;img src="' .get_post_meta($post_id, $prefix.'post_box_image', TRUE). '" style="max-width:40%; max-height:40%;" /&gt;'; } else echo 'No Post Box Image Set'; } elseif ($column_name == 'post_box_excerpt') echo substr($post-&gt;post_excerpt, 0, 150) . '...'; } </code>
How can I change the dashboard appearance?
wordpress
I'm trying to html5ize a Genesis child theme. So far I've figured out how to replace the Doctype via hook but am having trouble figuring out how i can change the divs to sections and articles without touching the core files. Can anyone point me in the right direction?
You could create all your own templates in a child theme but the core engine does contain the HTML tags and ids. For me this is the problem with Theme Frameworks (Unless your willing to totally commit to them). The code quality is outstanding but it's just too much work to roll things your own way. Just to remove the the genesis and studio press links in the footer you have to write a function remove 2 filters and add an action. To replace all the divs with your HTML5 tags your going to have to have to write your own functions for <code> genesis_site_title() </code> <code> genesis_before_content_sidebar_wrap() </code> <code> genesis_after_content_sidebar_wrap() </code> <code> genesis_before_content() </code> <code> genesis_after_content() </code> <code> genesis_sidebar() </code> <code> genesis_before_sidebar_widget_area() </code> and others Then do <code> remove_actions </code> and <code> add_filter </code> depending on the situation. You can use the visual markup chart to help with your efforts.
Wordpress Genesis Child Theme Filter divs
wordpress
Is there a way to delete a Post From Front-End and it's attachments permanently? This is a snippet that moves the post to the trash can, but it doesn't remove attached images (they remain on the server) and it doesn't remove the post permanently? Could someone please help? <code> &lt;?php $url = get_bloginfo('url'); if (current_user_can('edit_post', $post-&gt;ID)){ echo '&lt;a class="delete-post" href="'; echo wp_nonce_url("$url/wp-admin/post.php?action=delete&amp;post=$id", 'delete-post_' . $post- &gt;ID); echo '"&gt;Delete post&lt;/a&gt;'; } ?&gt; </code>
Try: <code> &lt;?php if (current_user_can('edit_post', $post-&gt;ID)) echo "&lt;a href='" . wp_nonce_url("/wp-admin/post.php?action=delete&amp;amp;post=$id", 'delete-post_' . $post-&gt;ID) . "'&gt;Delete post&lt;/a&gt;" ?&gt; </code> You can decide when to empty the WordPress trash by adding this code to the wp-config.php file in your WordPress root directory. <code> define('EMPTY_TRASH_DAYS', 1 ); </code> The 1 in the code signifies you want to empty the trash everyday. If you set to 0, the trash functionality will be disabled. Finally, WordPress doesn't delete images when they are no longer attached to a page. See this ticket for an explanation: http://core.trac.wordpress.org/ticket/12108 Gist being that media files may be used by other posts as well, which is why they must be deleted in the media library. If we changed it so that deleting a file from a post deleted it altogether from the system, it would break the existing behavior and cause a lot of unintentional deletions. If you want to go against that rational, you can add this to your functions.php: <code> function delete_post_children($post_id) { global $wpdb; $ids = $wpdb-&gt;get_col("SELECT ID FROM {$wpdb-&gt;posts} WHERE post_parent = $post_id AND post_type = 'attachment'"); foreach ( $ids as $id ) wp_delete_attachment($id); } add_action('delete_post', 'delete_post_children'); </code> Also see Upload Janitor if you want to go the plug-in route for deleting unattached images.
Delete Post From Front-End and attachment permanently
wordpress
I have a client who uses PDF files for their newsletter, I don't think that this is a good idea personally, but it's not negotiable. They have a news page where they put real time news and they'd like to add a sidebar to this page where there would be links to download these PDF files which would update automatically when they add them to the media library. So that the page doesn't over populate we've agreed that only the 12 most recent newsletters should be shown, that's 1 for each month of the year. They have no plans to add media of any other type without it being attached directly to posts or pages, so I figure that just a list of the 12 most recent unattached media files should suffice. Is there a way that this can be done using say a custom loop or WP_query object? I really have no idea how to go about starting this. I've done all sorts of workarounds in all sorts of ways regarding custom loops and sidebars so that's not the issue, what I really need to know is if there is an option for the loop to only display unattached media, or some WordPress function that lists media. I can't really give any examples or snippets of my code because I haven't started anything yet. EDIT: Okay, figured it out. Okay, I found a pretty straight forward sort of solution. It's not perfect because it's taking excessive amounts of steps per newsletter but it works exactly how I want it to. This is what I've got sitting in my sidebar: <code> &lt;?php query_posts('category_name=newsletter&amp;number_of_posts=12'); if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; // From here down I found on a site which I'll cite below. &lt;?php $args = array( 'post_type' =&gt; 'attachment', 'numberposts' =&gt; null, 'post_status' =&gt; null, 'post_parent' =&gt; $post-&gt;ID ); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $attachment) { echo '&lt;li&gt;'; the_attachment_link($attachment-&gt;ID, false); echo '&lt;/li&gt;'; } } ?&gt; &lt;?php endwhile; endif; ?&gt; &lt;?php wp_reset_query; ?&gt; </code> I made a category called Newsletter and the only thing I put in each post is a title and attach a PDF, the title doesn't even carry through, but it's necissary to publish the post. Finally, here is the link to the source for that code. I love these guys.
You could also use 'post_parent' => 0. All unattached attachments are assigned 'post_parent' = 0. Here is where I found that. I'm sure that there is a more authoritative resource somewhere, but this worked for me. :)
How would I go about listing only unattached media in say a sidebar?
wordpress
i'm hoping i'd find some help in regards to inserting ads into wordpress default rss feeds (i do not use feedburner) <code> &lt;?php function insertAds($content) { $content = $content.'&lt;hr /&gt;&lt;a href="http://www.wprecipes.com"&gt;Have you visited WpRecipes today?&lt;/a&gt;&lt;hr /&gt;'; return $content; } add_filter('the_excerpt_rss', 'insertAds'); add_filter('the_content_rss', 'insertAds'); ?&gt; </code> Source here But i read that the_excerpt_rss and the_content_rss is kind of deprecated. Can anyone advise me on the present hooks to use? Thanks
Take a look at the_content_feed as a replacement for the_content_rss.
Inserting ads into wordpress default rss feeds
wordpress
Here is my function: <code> function insert_img_rel_attrib( $html, $id, $caption, $title, $align, $url ) { $postID = ??? $rel = "&lt;a rel='shadowbox[".$postID."]'"; if ($url) {$html = str_replace("&lt;a",$rel,$html);} return $html; } add_filter( 'image_send_to_editor', 'insert_img_rel_attrib', 10, 6 ); </code> How do I get the current post ID? I've tried the obvious, <code> global $wp_query; $postID = $wp_query-&gt;post-&gt;ID; </code> etc.
This should work within your function: <code> get_post_field( 'post_parent', $id ) </code>
How to retrieve the postID in a "image_send_to_editor" hook function?
wordpress
I currently have this, <code> &lt;?php $meta = get_post_meta(get_the_ID(), 'rw_agentPhone', true); echo "office:"; echo $meta; // if you want to show ?&gt; </code> Which is fine provided there is a value for rw_agentPhone, but if the profile has no value entered it still displays office:, how can I rewrite this so that office: only dispalys if there is a value for rw_agentPhone. I know this is basic php but I just haven't been able to crack this.
This is very basic. Invest some time in a PHP tutorial. It’s fun! :) Anyway … <code> &lt;?php $meta = get_post_meta( get_the_ID(), 'rw_agentPhone', TRUE ); // get_post_meta() returns an empty string if it doesn’t find anything. // We just test for this. If the string is not empty, we print it out. '' != $meta and print "office: $meta"; ?&gt; </code>
Show label for value only when value exists, basic php
wordpress
I'm using the WordPress database and back end to administer the news for my band's website and everything is working great however I'd like to disable the front end of WordPress itself. I have the WordPress installation installed in <code> /wordpress/ </code> and obviously the admin section is under <code> /wordpress/wp-admin/ </code> . What would be the best way to restrict someone from accessing the rather *un*setup WordPress site itself without affecting the admin section? If anything, I could simply redirect to the website's proper home page ( <code> domain.com/ </code> ).
To make sure only the front end redirects to <code> domain.com </code> , make a theme that uses the PHP header() function. Create a folder called redirect or something. Add two files to the folder: <code> style.css </code> and <code> index.php </code> (necessary for a valid WP theme) In <code> style.css </code> , add something like this: /* Theme Name: Redirect Description: Redirects the front end to domain.com */ In <code> index.php </code> add this: header( "Location: http://domain.com " ); Upload the folder to the themes directory and then activate it in the admin UI.
Disable front end to use as CMS only?
wordpress
Can you recommend a tutorial or a plugin in wordpress that lets you achieve a similar gallery, like this http://www.whitehouse.gov/photos-and-video/photogallery/may-2011-photo-day Large Preview then at the bottom a thumbnails then an album. I also like cooliris because it supports fetching images from facebook and flikr. Another feature I like about it is its sharing options, you can easily share those images in facebook. The only thing I don't like is its interface, its not fully customizable, the arrows left and right are hardly to be seen, the animation is too techno for my project. I need a gallery where thumbnails where thumbnails can easily be browse, and it also has an album so its organize. It would be a plus if you have an option to pull images from flikr or facebook and you can share them via facebook or twitter. Let me know if you know a software that is close to my description. Thanks so much!
You would have to create custom templates, but your reference page is fully achievable using the NextGen Gallery plugin.
Image gallery plugin
wordpress
I am trying to code in more consistent manner and would like to know what is the difference between WP: template_directory vs TEMPLATEPATH.
@tanktery <code> template_directory </code> is the URL of the active theme's directory. Before version 2.6 of WordPress it was a local path. <code> TEMPLATEPATH </code> is also the URL of the active theme's directory. Before version 2.6 <code> TEMPLATEPATH </code> was used but now it is recommended to use <code> &lt;?php bloginfo('template_directory'); ?&gt; </code> . Hope this helps!
What is the difference between WP: template_directory vs TEMPLATEPATH
wordpress
I have several sub-categories set up. Everything displays properly as far as nesting (see below) when creating a new post. Category 1 --Sub Category 1 --Sub Category 2 --Sub Category 3 Category 2 etc After I select a sub-category, then go back and edit a post, the sub category that I check shows up like this (note how it's not nested under Category 1): (checkmark) Sub Category 2 Category 1 --Sub Category 1 --Sub Category 3 Category 2 etc Is this a bug in WordPress 3.1.2? Can someone tell me how to fix it? I don't remember it doing this when I was running 3.0.5 (but there's a chance it could have).
This "feature" has been in WP for quite a while. You can disable it by installing this small plugin: http://wordpress.org/extend/plugins/category-checklist-tree/
Why aren't sub-categories nested after creating post in the WP Admin?
wordpress
I am developing a installable theme in wordpress I have created a contact form and called that form in footer but I want to create a widget that should be theme based mean i dont want any plugin.I can create a widget but for this i need to put the file in plugin folder that I don't want that should be completely theme based . I want this because if I want to change the position of contact form like from footer to sidebar so for this I need to make this contact form widget that can be drag and drop in footer and sidebar. I have searched this also on Internet but all are based on plugin directory so that Its not my requirement because it will activate whenever plugin will be activate but I need widget should activate whenever theme will be activate Please provide me help or your suggestion I shall be very thankful to you Thanks
A contact form is pure plugin stuff. It has to survive a theme switch. Put it into a plugin and prepare your stylesheet for the common possible positions.
how to create theme based widget that can be drop in sider bar or footer
wordpress
I have a custom taxonomy, and would like to force the user to select at least one term from that taxonomy when creating a post in the WordPress admin back-end. Is this possible?
No. This is not completely possible. One solution would be to swap out the default UI on /wp-admin/post.php &amp; /wp-admin/post-new.php. You can provide the user with radio buttons or a select box. This will work relatively well, but can not be 100% trusted. There is still the possibility that a user could remove all terms via quick edit in /wp-admin/edit.php.
How to enforce the selection of at least one term from a custom taxonomy?
wordpress
I was wondering that if you do an AJAX call on an admin page and I wanted to see if the user had the capability to edit a page, would that info be sent along the call or do I need to manually sent that data?
You don't need to send any additional data, since the user cookies (which are used for authentication) will be sent by default. You have access to all the WP functions, including current_user_can().
Does an AJAX call on the Admin Side Automatically include the User Data/Capabilities?
wordpress
I installed a new WP site on local machine with wamp server. When a new user registers it gets the "registration successful" message but a mail with the password is never sent. Also checked the junk folder. What can be the cause?
Probably your local setup since Wamp does NOT come with mail server. But you can configure the STMP settings of PHP to point to another server in your LAN which runs an SMTP server, or to the SMTP server of your ISP. this thread has an example of how to set it up: http://www.wampserver.com/phorum/read.php?2,31302,70969
Mail isn't sent after local site registration
wordpress
I'm planning to follow this tutorial in order to allow my subscribers to add images to comments (actually a custom post type called "Replies"). Wordpress filters <code> &lt;img&gt; </code> tags by default (except for the admin). Will my Wordpress site be vulnerable to Cross-Site Scripting (XSS) if I allow img HTML tags in my comment section?
Many evil things can be done by including an image. The question is how well WordPress filters them. To give you an idea: File names should be checked properly. The actual image data can contain javascript. Also, EXIF data could contain javascript.
Will my Wordpress site become vulnerable to Cross-Site Scripting (XSS) if I allow img tags in the comments area?
wordpress
I am excluding comments from specific categories. However, when I try to exclude more than one, it doesn't work. This works: <code> &lt;?php if (!in_category('7')) comments_template(); ?&gt; </code> This does not work: <code> &lt;?php if (!in_category('7 , 9')) comments_template(); ?&gt; </code> or <code> &lt;?php if (!in_category('7')) comments_template(); ?&gt; &lt;?php if (!in_category('9')) comments_template(); ?&gt; </code>
I would suggest using category slugs instead of ids. Please try something like this: <code> if ( ! in_category( array( 'bunnies', 'tacos', 'banana-pirates' ) ) ) { comments_template(); } </code>
How do I specify more than one category?
wordpress
This is happening in more than one section of our website, but in different yet similar ways. Scenario One: We have a URL structure like this... mydomain.com/some-category/?subject=Some+Subject I'm trying to get pagination properly working. I urlencode() the space and get the +, but it doesn't matter if I use a space or a + ...Wordpress always tries to do this... mydomain.com/some-category/page/2/?subject=SomeSubject ...instead of this... mydomain.com/some-category/page/2/?subject=Some+Subject WordPress is removing the space/+ for some reason. We haven't figured out why just yet. Any help is greatly appreciated. Scenario Two: I have predefined slugs that are identical matches to our part codes in our e-commerce system. We have custom-built plugins that associate pages to the e-commerce system by way of the slug matching the part code in our system. In turn, it generates nicely formatted (and automatic) ordering tables for checkout. Wordpress is removing any "+" that I include in the slug, which may have been part of our part codes. Is there any way to get Wordpress to quit screwing around with our URLs and let us do what we want to? We prefer to think for ourselves, rather than have Wordpress tell us how to think.
You can hook into WordPress’ slug algorithm and create your own slugs. For an example look into my plugin Germanix URL . I’m not sure if WordPress can accept requests with an <code> + </code> without further tweaking tough. If just want to allow the slug without much coding, install Germanix and create a second plugin with this code: <code> &lt;?php # -*- coding: utf-8 -*- /* Plugin Name: Germanix plus + */ add_filter( 'germanix_translit_list', 'remove_plus_from_transliteration', 10, 1); add_filter( 'germanix_lower_ascii_regex', 'allow_plus_on_regex', 10, 1); function remove_plus_from_transliteration( $utf8 ) { unset ( $utf8['+'] ); return $utf8; } function allow_plus_on_regex( $regex ) { # $regex['pattern'] =&gt; '~([^a-z\d_+.-])~'; // was this $regex['pattern'] = '~([^a-z\d_+.-])~'; // now this return $regex; } remove_filter( 'editable_slug', 'urldecode' ); </code> I haven’t tested this now but it should work. :)
Modify Wordpress to not replace + (plus) characters from URLs?
wordpress
let's say I have 100 categories and each has 10 custom fields for it self,for example : category Computer : Cpu - Hard - Ram - ... category TV : resolution - inch - usb support - ... ... now I want the editor only can see related custom fields to post(ex. computer) , I don't want them to see like 1000 custom fields and tries to find the related custom field to fill in, it will take for ever ! I'm making my own theme and can do what ever change that is needed !! I couldn't find any plugin for this ! thanks in advance .
Try using magic fields . It will let you create a custom panel for each category, where you can specify just the custom fields needed for that category. It allows you to present it all in a very user friendly way as well, as well as manuy, many, many other cool things. The plugin will change your life if you do this sort of thing often, using wordpress as CMS!
Wordpress Custom Fields by category
wordpress
I am trying to hook in to automatically sign-in the user after registration. (using a GravityForms registration form). None of the hooks seem to be working. I've tried: gform_user_registered, user_register, a filtered 'update_user_metadata'.... Why would this not kill the script after a registration happens? <code> add_action("user_register", "my_auto_login"); function my_auto_login($user_id) { die('x'); } </code> Login after registration seems like it should not be that complicated.
Use the Gravity forms gform_user_registered hook. It fires after the registration and will return the $user_id. <code> function my_auto_login( $user_id ) { wp_set_auth_cookie( $user_id, false, is_ssl() ); wp_redirect( admin_url( 'profile.php' ) ); exit; } add_action( 'gform_user_registered', 'my_auto_login' ); </code>
Registration Hooks don't appear to be working
wordpress
I would like to get the last term that was searched, but when not in the search.php page. For that, I know, I could use get_search_query() function, but if user clicks on a post for example, so he is now in the single item and that function will retrieve an empty string. I want to preserve that search phrase and get it on other page. Any ideas? Thanks
Best solution would be to store the search phrase on the client-side via local storage or, where not available, in a cookie.
Get search term not on searh results page?
wordpress
Ok so i have added a custom field into the users edit profile page where they can add a link to a url of an image they want. I am currently using this for contribitors and above but i also have a small little profile box on my site that gets a users avatar from gravatar. I used the code from before but changed it around to get the current signed on users authorpic or get the gravatar. See code below <code> $profilepic = get_user_meta('author_pic'); $imgtagbeg = ('&lt;img style="height:52px; width:52px" src="'); $imgtagend = ('"/&gt;'); if ($profilepic) echo $imgtagbeg,$profilepic,$imgtagend; else echo get_avatar( $user_email, '52', $default = 'http://www.gravatar.com/avatar.php?gravatar_id=$md5&amp;size=80&amp;default=$default' ); </code> What i want to do is if the current user signed in has a avatar linked in his profile field then use that instead of gravatar. But if the author does have a gravatar and has left the field blank in the profile use that or get the default gravatar Update: What about something like this <code> $userpic = '&lt;img src="link/to/author_pics/$userid.png"'; if ($userpic) echo $userpic; else echo get_avatar( $user_email, '52', $default = 'http://www.gravatar.com/avatar.php?gravatar_id=$md5&amp;size=80&amp;default=$default' ); </code> Instead of relying on a user field just upload an image to a directory and use there userid as the filename then load it else use gravatar. Would that work. UPDATE 2: <code> $userpiccur = wp_get_current_user(); $userpicloc = 'http://avatars.mydomain.com/'; $userpictyp = '.png'; $userpicurl = $userpicloc . $userpiccur-&gt;user_login . $userpictyp; $header_response = get_headers($userpicurl, 1); $userpicbeg = '&lt;img style="height:52px; width:52px" src="http://avatars.mydomain.com/'; $userpicend = '.png"/&gt;'; if ( strpos( $header_response[0], "404" ) !== false ) echo $userpicbeg,$userpiccur-&gt;user_login,$userpicend; else echo get_avatar( $user_email, '52', $default = 'http://www.gravatar.com/avatar.php?gravatar_id=$md5&amp;size=80&amp;default=$default' ); </code>
Ok so i got it working like i want. Now all i have to do is figure out if i want a user to be able to upload there own image or not. <code> &lt;? $userpiccur = wp_get_current_user(); $userpicloc = 'http://avatars.mydomain.com/'; $userpictyp = '.png'; $userpicurl = $userpicloc.$userpiccur-&gt;user_login.$userpictyp; $userpicbeg = '&lt;img class="avatar avatar-52 photo" style="height:52px; width:52px" src="'; $userpicend = '"/&gt;'; if (@fopen($userpicurl, "r")) echo $userpicbeg,$userpicurl,$userpicend; else echo get_avatar( $user_email, '52', $default = 'http://www.gravatar.com/avatar.php?gravatar_id=$md5&amp;size=80&amp;default=$default' ); ?&gt; </code>
get_user_meta Short Profile Section
wordpress
I have a client who's site will be making heavy use of custom post types to configure their site. But I'm between a rock and a hard place for their requested home page. In reality, the home page will be a stack of specific "pages" within WordPress. Basically, there will be pages for: Intro , Blog , About Us , Portfolio , and Contact Us . They'll all be stacked on top of one another so you can scroll from one page to another. My first instinct was to just use a page (called Home ) and embed a shortcode that accepts page slugs and outputs the proper order (i.e. <code> [pageOrder]intro, blog, about-us, portfolio, contact-us[/pageOrder] </code> ). The page would use a custom page template to lay things out, control the loop, and add navigation to the left side of the page. But that all seems klunky. My ideal solution would be to create a custom post type (called Stack ) that allows the end user to position the pages with drag-drop and have the CPT take care of layout and navigation and such. The problem with my ideal solution is settings. WordPress allows you to select a page for the default home page of the site. But it's tied to a post type of page , and I'm not sure where to hook in to modify that so that users could also select a Stack as the default home page. So, where do I hook in to in order to add a CPT to the dropdown of available pages for the default home page?
Thanks to @toscho for the useful answer, but it felt a bit hackish to me, so I poked around a bit and figured out I could add a filter instead: <code> function wpa18013_add_pages_to_dropdown( $pages, $r ){ if('page_on_front' == $r['name']){ $args = array( 'post_type' =&gt; 'stack' ); $stacks = get_posts($args); $pages = array_merge($pages, $stacks); } return $pages; } add_filter( 'get_pages', 'wpa18013_add_pages_to_dropdown', 10, 2 ); </code> Update After adding the above code I was, indeed, able to use a custom post type as the home page, but WordPress would redirect the permalinks because it wasn't a "page" post type. So <code> http://localhost/test </code> would redirect to <code> http://localhost/test/stacks/home-stack </code> , which wasn't what I wanted. Adding this action, though, fixed that and queries my custom post type along with pages for the home page: <code> function enable_front_page_stacks( $query ){ if('' == $query-&gt;query_vars['post_type'] &amp;&amp; 0 != $query-&gt;query_vars['page_id']) $query-&gt;query_vars['post_type'] = array( 'page', 'stack' ); } add_action( 'pre_get_posts', 'enable_front_page_stacks' ); </code>
How do you use a CPT as the default home page?
wordpress
I have declared a scheduled event in a plugin like this : <code> function shedule_email_alerts() { if ( !wp_next_scheduled( 'send_email_alerts_hook' ) ) { wp_schedule_event(time(), 'hourly', 'send_email_alerts_hook'); } } </code> Then i wanted to change the frequency to 'daily', by doing so, replacing the original function with : <code> function shedule_email_alerts() { if ( !wp_next_scheduled( 'send_email_alerts_hook' ) ) { wp_schedule_event(time(), 'daily', 'send_email_alerts_hook'); } } </code> But it seems that my event is still fired every hour. I use the Core control plugin to monitor CRON tasks and it still shows as 'once per hour'
Ok, I could solve the problem by using <code> wp_clear_scheduled_hook() </code> I commented out my schedule declaration and added <code> wp_clear_scheduled_hook('send_email_alerts_hook') </code> at the end. Then deactivate - reactivate my plugin, which removed my scheduled hook. Then removed <code> wp_clear_scheduled_hook() </code> and uncommented my code, now the schedule was set properly. Found the tip here .
How can I change the frequency of a scheduled event?
wordpress
The function <code> get_current_site() </code> that's in my themes' footer.php file doesn't return the 'site name' property as specified in the docs (and expected in the theme). The purpose of the function is to return all details about the parent site on a multi-site setup. The only return values I am getting are the blog_id and path. eg: <code> &lt;?php print_r(get_current_site());?&gt; </code> Returns: <code> stdClass Object ( [id] =&gt; 1 [domain] =&gt; www.mydomain.co.uk [path] =&gt; / [blog_id] =&gt; 1 ) </code>
Try using <code> get_current_site_name() </code> to insure you get the site name so something like this: <code> echo get_current_site_name(get_current_site()); </code>
get_current_site() not returning site name
wordpress
I've given the task of moving several well established blogs from wordpress.com into an independent hosting using Wordpress. Wordpress.com uses a special parser for taking stuff like this: <code> [youtube=http://youtu.be/JN3n34dS] </code> and converting this to a YouTube embed (for example, this happens with other links too, such as Google Maps, etc). Is there a systematic way to convert all those links to normal embeds? Thanks!
you could use phpMyAdmin to do a search&amp;replace on the wordpress database for the old youtube embed string and then replace with the new one. Should be possible since the syntax is similar enough. edit: to add stackexchange-url ("from this other stackexchange question"): Search RegEx is a good plugin to be able to search and replace with Grep through all posts and pages. With that, you can change your shortcodes to the default Embeds « WordPress Codex that self-hosted Wordpress uses, which in its simplest form is just the URL. Or use WordPress › Viper's Video Quicktags « WordPress Plugins and search/replace to convert to that form of shortcode.
Convert Wordpress.com embed links to normal embeds
wordpress
Is there a way to disable image attachment links trought a filter in functions.php or something ? I know it's possible to do it manually when you add an image to a post but I want to disable this functionality by default. UPDATE What I want to do is set the "Link URL" option to "none" and remove / hide it from the upload attachement screen. Is there a solution to hook into the "media-upload" "pop-in" ? Thanks by advance.
If anybody is interested in do the trick, my solution is this: <code> function remove_media_link( $form_fields, $post ) { unset( $form_fields['url'] ); return $form_fields; } add_filter( 'attachment_fields_to_edit', 'remove_media_link', 10, 2 ); </code>
Disable image attachment links
wordpress
For single posts and pages, I would like to add certain <code> rel </code> attributes to all the images on the contained therein added with the "Add Image" functionality on the edit screen. The attribute would be <code> rel="lightbox[post id]" </code> What function would I filter to accomplish this most effectively?
image_send_to_editor <code> function insert_img_rel_attrib( $html, $id, $caption, $title, $align, $url, $size, $alt ) { /* Run your magic on the image $html to insert rel attrib */ return $html; } add_filter( 'image_send_to_editor', 'insert_img_rel_attrib' ); </code>
Best way to programatically add "rel" attributes to page and post images
wordpress
I figured out how to exclude the current post from displaying in my single-post view sidebar, but now I want to exclude parent categories and display only children. Any ideas how to do this? Much obliged!! <code> &lt;div id="sidebar" class="grid_4"&gt; &lt;div class="item portfolio"&gt;&lt;hr&gt;&lt;/hr&gt; &lt;h4&gt;Similar Items&lt;/h4&gt; &lt;?php if ( is_single() ) { $cats = wp_get_post_categories($post-&gt;ID); if ($cats) { $first_cat = $cats[0]; $args=array( 'cat' =&gt; $first_cat, //cat__not_in wouldn't work 'post__not_in' =&gt; array($post-&gt;ID), 'showposts'=&gt;8, 'caller_get_posts'=&gt;1 ); $my_query = new WP_Query($args); if( $my_query-&gt;have_posts() ) { echo ''; while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt; &lt;?php if (in_category('15')) continue; ?&gt; &lt;div ID="similarentry"&gt;&lt;ul&gt; &lt;li ID="similarthmb"&gt;&lt;?php get_the_image( array( 'custom_key' =&gt; array( 'thumbnail' ), 'default_size' =&gt; 'thumbnail', 'width' =&gt; '119', 'height' =&gt; '75', 'link_to_post' =&gt; true ) ); ?&gt;&lt;/li&gt; &lt;li ID="similarttl"&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark" title="Permanent Link to &lt;?php the_title_attribute(); ?&gt;"&gt;&lt;?php the_title() ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;&lt;/div&gt; &lt;?php endwhile; } //if ($my_query) } //if ($cats) wp_reset_query(); // Restore global post data stomped by the_post(). } //if (is_single()) ?&gt; &lt;/div&gt;&lt;/div&gt; </code>
I spent almost two months building and debugging Total Widget Control to do exactly this for all of a sites widgets. Bear with me as I strip the code out of Total Widget Control and try to make it usable for you. <code> global $wp_query $twc_menu_item_object = $wp_query-&gt;object_id; //is the object id of the current page. $objects['menu-item-object'] = ''; //the object id of the tax to display under if ( taxonomy_exists($twc_menu_item_object) &amp;&amp; isset($objects['menu-item-object']) ) { foreach ($objects['menu-item-object'] as $menu_id =&gt; $menu_type) { if ( $menu_type != $twc_menu_item_object ) continue; if ( !cat_is_ancestor_of( $menu_id, $object_id ) ) continue; return true; } } return false; </code>
How to exclude parent category but show child categories?
wordpress
Is there any plugin where users can comment with Facebook or Twitter or OpenID...
I use disqus on my site and it works quite well.
A plugin where users can comment with Facebook or Twitter or OpenID
wordpress
Ok so i have added a custom field inside of the WordPress edit profile field where a contributor and above can add a custom image if they do not use gravatar. Now i am trying to write a if else statement and this is what i have <code> &lt;? $hasauthorpic = (the_author_meta('author_pic')); if (function_exists('get_avatar')) { echo get_avatar( get_the_author_email(), '80' );} else {echo '?&gt;&lt;img class="avatar avatar-80 photo"&gt;&lt;? $hasauthorpic ?&gt;&lt;/img&gt;&lt;? ';} ?&gt; </code> What i want to try and do is if the user does have a gravatar use it unless they have specified a link to there profile pic. Or have the author_pic become higher priority even if user has gravatar. EDIT: <code> &lt;? $authorpic = the_author_meta('author_pic'); $gravatar = get_avatar( get_the_author_email(), '80' ); if ($authorpic); elseif (function_exists('get_avatar')) echo ($gravatar); ?&gt; </code> OK so i tried the code below and that did not quite work. Maybe because i am putting this into a single-whatever.php file. The above is what i have managed to get but the only problem is when it shows it shows both the avatar and author pic link so i know i still need to add the <code> &lt;img&gt; </code> tags but that will be easy later. The one thing i did read is that your cant put a <code> true </code> on <code> the_author_meta </code> so i need help. If you can come up with a code to hook into the gravatar stuff then ill take it. In other words if you have a code that i can place in my functions.php file thatll work to i and i would prefer that. the field name is <code> author_pic </code> UPDATE: This is my final write up with the provided code from below <code> &lt;?php $authorpic = get_the_author_meta('author_pic'); $imgtagbeg = ('&lt;img style="height:80px; width:80px" src="'); $imgtagend = ('"/&gt;'); if ($authorpic) echo $imgtagbeg,$authorpic,$imgtagend; else echo get_avatar( get_the_author_email(), '80' ); ?&gt; </code>
You need to use get_the_author_meta() instead of the_author_meta() <code> &lt;?php $authorpic = get_the_author_meta('author_pic'); if ($authorpic) echo $authorpic; else echo get_avatar( get_the_author_email(), '80' ); ?&gt; </code>
If Else Gravatar Author Picture
wordpress
Say I want to add this link: http://localhost/taiwantalk2/user-login/ Which is a Page with a template called page user-login.php : <code> &lt;?php /** * Template Name: bbPress - User Login * * @package bbPress * @subpackage Theme */ // No logged in users bbp_logged_in_redirect(); // Begin Template get_header(); ?&gt; </code> I used to just paste the url of the site (using template_directory) plus the slug (/user-login). The problem is that I have to stick with he same slug (/user-login). Is there any other alternative?
From what I understand, you want a URL to your page, that will work even if you change the page slug? You can do this by linking to the default permalink for that particular page, for example http://localhost/taiwantalk2/?page_id=139 . This URL will always work even if your permalinks are updated. WordPress handles the redirects for you.
Is there any way to display the link of a Wordpress page without relying in its slug (or full path)?
wordpress
I have no problem doing this in a comment, as an administrator: <code> &lt;b&gt;bold test&lt;/b&gt; &lt;i&gt;italics test&lt;/i&gt; &lt;u&gt;underline test&lt;/u&gt; &lt;font color="#ff9900"&gt; color test&lt;/font&gt; </code> But the subscribers can't underline, add color to words nor add images. Is it that only the admin can use more HTML tags than those suggested under the comment form? <code> &lt;a href="" title=""&gt; &lt;abbr title=""&gt; &lt;acronym title=""&gt; &lt;b&gt; &lt;blockquote cite=""&gt; &lt;cite&gt; &lt;code&gt; &lt;del datetime=""&gt; &lt;em&gt; &lt;i&gt; &lt;q cite=""&gt; &lt;strike&gt; &lt;strong&gt; </code> How to enable the subscribers to add color to text, and add images?
The tags that are allowed in comments are stored in the <code> $allowedtags </code> global variable . You can try adding elements to that list (the key is the tag name, the value is an array of allowed attributes). If you have problems with the timing you can play with the <code> CUSTOM_TAGS </code> global variable .
Expanding the allowed HTML tags in comments?
wordpress
I have a class inside a file that i <code> include_once() </code> from the functions.php of my theme. The class can be used as stand alone plugin, or integrated in a theme. Inside the class i want to fill a class variable (inside the <code> __construct() </code> function) with the native wordpress function <code> get_plugin_data() </code> . Fun as it is, i get the following error: Call to undefined function <code> get_plugin_data() </code> Am I asking for the plugin data too late, or what else might be my problem? Thanks!
get_plugin_data() is only defined in the administration section. What info did you need to get from the plugin's header that you would need to display in the theme? If the answer is none, I would suggest that you place a conditional call in your constructor. Something like: <code> if ( is_admin() ) { $var = get_plugin_data(); } </code>
Call to undefined function `get_plugin_data()`
wordpress
I'm currently extending my pagination plugin, after a hint by @toscho. So the plugin will now use the same filters, hooks and arguments as the native wordpress pagination functions. My problem is that the different wp functions name their arguments ... different. Example: This is how you change the text for the "Next" link. <code> wp_link_page() </code> = <code> 'nextpagelink' </code> <code> paginate_links() </code> = <code> 'next_text' </code> After retrieving the input in the class, I <code> wp_parse_args( $args, $this-&gt;defaults ); </code> my arguments and then <code> extract </code> them. Problem: When I now allow both <code> 'nextpagelink' </code> &amp; <code> 'next_text' </code> as valid arguments, how would i deal with them? Which would I check first? Do I need to set some priority, so one overrules (if both are set) the other? Example: This example shows my dilemmas: Which one has the higher priority? How can I avoid deciding? It's really long code just for deciding what to do with 2 vars. Code: <code> if ( $nextpagelink &amp;&amp; $next_text ) { // CASE 1: both are set // which one should I take now? } elseif ( $nextpagelink ) { // CASE 2: only one is set - should this one override the next one? // set something } elseif ( $next_text ) { // CASE 3: only one is set - should this be overridden by the previous one? // set } else { // CASE 4: none is set - apply default // set default } </code>
<code> wp_link_pages() </code> and <code> paginate_links() </code> work in different contexts: The first on a single paginated page, the latter on an archive. So <code> is_archive() </code> should be your criterion to decide which text you use, or better: which filter you use in <code> apply_filters() </code> .
How to deal with equal & similar arguments for a function?
wordpress
I had the site on oldsite.com but was using the database at newsite.com, everything was working great. I moved the site to newsite.com, now when I try adding a new post using a custom post type, it disappears, I am still able edit older posts, of the same custom post type. I checked the db when I create a new post nothing is saved, when I make changes to existing posts the change is saved. Not sure where to look next. Thanks this is in my functions.php http://pastebin.com/n5baM3R8
Try re-generating the permalinks structure. And check that you have the correct urls in the general options (WPURL and URL)
Switched server & domain name, now custom post types won't save
wordpress
What favicon plugin should I use in order to define favicons for Wordpress when I run in multi-site mode. Uploading favicon.ico files is not an option for multi-site wordpress instances. I am looking for something simple that will not pollute the generated pages with hidden advertising. EDIT: Looking to be able to define favicons on a per site basis. Different favicons for different sites.
Now I am successfully using All In One Favincon Plugin.
Favicon plugin for WordPress running in network mode (multisite)?
wordpress
I basically want to create a table (preferably AJAXified) that lets the user enter a line of information, and be able to add new lines of information, and delete selected ones. I've found stackexchange-url ("this post") and stackexchange-url ("this post"). The design side looks very straightforward, but I want to know about the functionality. How do I go about adding the field contents to the database and summoning them back up? How do I get that page "plugged in" to Wordpress as a whole? I have literally no idea where to start. I'm coming from the perspective of someone who's confident in HTML &amp; CSS, and fairly so with JS/jQuery, but basically just hacks up PHP code that he finds around. Any help would be appreciated, even up to telling me that it's beyond me right now, and to go play with X plugin. FWIW, I was considering doing this with a custom post type, or the Magic Fields plugin, but I wanted a more user-friendly experience. Many thanks!
I pretty much started in the same place as you a while back, and have created something similar. Here's what I think you need to know. 1) Work out how to create your basic hello world first and foremost. A simple plugin will consist of a few comments at the top of a PHP file dropped into your plugins directory. Notice the variable calling the class which gets it moving. Constructor of the class calls add_top_level_menu, when this is clicked on (see $function variable) the display_page() function gets kicked off starting to build out your page. <code> &lt;?php /* Plugin Name: Your plugin name Description: Description Version: 1.0 Author: You.com Author URI: http://your.com */ $myplugvariable = new yourpluginname(); class yourpluginname() { function __construct(){ add_action( 'admin_menu', array( &amp;$this, 'add_top_level_menu' ) ); } function add_admin_scripts(){ //adds javavascript files for this plugin. wp_enqueue_script('my-script-name', WP_PLUGIN_URL . '/' . dirname(plugin_basename(__FILE__)) . '/js/javascript.js', array('jquery'), '1.0'); wp_localize_script('my-script-name', 'MyScriptAjax', array('ajaxUrl' =&gt; admin_url('admin-ajax.php'))); } function add_top_level_menu() { // Settings for the function call below $page_title = 'Plugin Name'; $menu_title = 'Plugin Name'; $menu_slug = 'plugin-name'; $function = array( &amp;$this, 'display_page' ); $icon_url = NULL; $position = ''; // Creates a top level admin menu - this kicks off the 'display_page()' function to build the page $page = add_menu_page($page_title, $menu_title, $this-&gt;capability, $menu_slug, $function, $icon_url, 10); // Adds an additional sub menu page to the above menu - if we add this, we end up with 2 sub menu pages (the main pages is then in sub menu. But if we omit this, we have no sub menu // This has been left in incase we want to add an additional page here soon //add_submenu_page( $menu_slug, $page_title, $page_title, $capability, $menu_slug . '_sub_menu_page', $function ); } function display_page() { if (!current_user_can($this-&gt;capability )) wp_die(__('You do not have sufficient permissions to access this page.')); //here comes the HTML to build the page in the admin. echo('HELLO WORLD'); } } ?&gt; </code> 2) Once you've created internal functions to return your data, whatever that may be. (use global wordpress data functions, e.g. $wpdb-> get_results($sql). 3) AJAX inside the admin is a bit different to how you normally use it. All wordpress AJAX calls hook into admin-ajax.php. I found this: http://www.garyc40.com/2010/03/5-tips-for-using-ajax-in-wordpress/#js-global quite good at explaining things. 4) If you are creating tables: something like the below will do the work for you. search for dbDelta in the codex. <code> function plugin_install() { global $wpdb; $table_name_prefix = "plugin-name"; $table_name = $wpdb-&gt;prefix . "plugin_name"; $sql = "CREATE TABLE " . $table_name . " ( id mediumint(9) NOT NULL AUTO_INCREMENT, post_id mediumint(9) NOT NULL, score mediumint(9) NOT NULL );"; require_once(ABSPATH . 'wp-admin/includes/upgrade.php'); dbDelta($sql); } </code>
Any guides on creating custom admin pages?
wordpress
For example, in portfolio section I want to have 3 images that are positioned always in the same place in all the posts. I know there is a plugin that does this but I need to accomplish this without a plugin.
The best advice is to use the plugin. I can't think of any reason to rebuild functionality that already works well and exists. If you absolutely need this functionality in the theme, you can include the code from the plugin into your theme by removing the header in the plugin's main file and requiring it in your theme's functions.php file. Please bear in mind that this is NOT considered as "best practice" and there are a couple of other steps that you will need to take to really make this work well: Change the name of all the functions. Adding a prefix like "myplugin_" to all functions should work well. Also, you will want to use this custom prefix on all global variables, class names, settings, localization slugs and anything else that WordPress might "see". This will avoid clashes in the event that the actual plugin is ever installed. load_plugin_textdomain() ahould be changed to load_theme_textdomain(). plugins_url() will need to be changed to get_template_directory_uri(). paths will need to be addressed. At the end of the day, I would strongly urge you to allow your theme to support the plugin and degrade gracefully if the plugin is not installed.
How to add multiple featured images to post/page without a plugin
wordpress
Some of my clients don't have CPanel access to their WordPress, so I have to copy and paste from the built-in editor to pull out the PHP. Is there a way within that admin interface to grab all the PHP files? I don't have FTP acces.. gr...
You should demand access to ftp or the command line, working without is is crippling and to be blunt, silly.
Download PHP and CSS from the Wordpress admin page without FTP
wordpress
When you develop a site on wordpress you may want to create posts/pages with the same name, something that wordpress does not allow by default. Use cases: <code> example.com/en/contact example.com/fr/contact example.com/en/support/contact </code> I am currently using WPML plugin in order to create multilanguage sites and I encountered this limitation in wordpress. How can I solve this problem? Do you know any tricks or plugins that would allow me to deal with this problem.
When you develop a site on wordpress you may want to create posts/pages with the same name, something that wordpress does not allow by default. This is statement is not true. WordPress will allow you to set up pages with the "directory" structure that you specified right out of the box. I was just able to do this on my test installation. I created a page with slug "en" and then created a child page named "taco". Next I created a page named "fr" and added a child to this page named "taco". Both taco pages have the slug of "taco". There may be an issue with the plugin that you are using. Have you tried this without the plugin installed?
How to create posts or pages with the names in wordpress?
wordpress
I'm trying to create an advertisement block to be placed on a single post (single.php) such that the div class or id is left aligned and the post content wrapped around it. I checked the single.php and this is the only piece of code I notice is what displays the post. <code> &lt;div class="entry entry-content"&gt; &lt;?php the_content(); ?&gt; &lt;?php wp_link_pages( array( 'before' =&gt; '&lt;div class="page-link"&gt;' . __( 'Pages:', 'themejunkie' ), 'after' =&gt; '&lt;/div&gt;' ) ); ?&gt; </code> I tried adding the code both above the 'entry-content' div and also after the_content, but with both methods it either displays the div either at the beginning or at the end of the post content. Can someone tell me which files to look into in order to add this?
You have to put your advertisement block just before <code> &lt;?php the_content(); ?&gt; </code> in a separate div-layer and add some css to it. E.g. single.php <code> &lt;div class="entry entry-content"&gt; &lt;div class="advertisement"&gt; &lt;p&gt;Your advertisement&lt;/p&gt; &lt;/div&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; </code> CSS <code> div.advertisement { float: left; width: 150px; padding: 0px 10px 10px 0px; } </code>
Adding a div class or id inside the_content()
wordpress
I'm updating a plugin of mine and am have a hard time figuring out the "best way" to build in a specific bit of functionality. The plugin allows users to associate images from their media library to any term of any taxonomy. I'm currently working on creating functions that users can add to their themes and plugins to get the data stored by the plugin. The code I have so far can be viewed here: https://github.com/mfields/Taxonomy-Images/blob/master/public-filters.php The functionality presented in this file enables users to get the image of the term currently being queried (for taxonomy archive views) and another function is basically a wrapper for core function <code> get_terms() </code> which will return all terms of a given taxonomy while adding the image id to each term object. I would like to add a third function to the file before release. This would be a wrapper for <code> get_the_terms() </code> and would return all terms associated with the global post object that have images. I was thinking about modeling the <code> get_the_terms() </code> function after the <code> get_terms() </code> function which has built in caching for the image files. But I'm a bit afraid of what would happen when this function was used in the loop in any archive template. Basically the workflow would go something like this: Get all image/term associations (0 queries). Get terms associated with the global post: <code> get_the_terms() </code> (0 queries). Query for all images associated with the terms (3 queries). This is done by creating a list of all image ID's and passing them to <code> get_posts() </code> via the <code> include </code> parameter. IMHO this is fine to do in single views (single.php, page.php, etc.) but what would happen if a user was to use this function in the loop in an archive views? You will need to multiply 3 queries (produced by <code> get_posts() </code> ) by the value of the posts-per-page setting (10 in a default WordPress installation). So now we're at 30 total queries. It gets kinda ugly fast! Especially if users want images from more than one taxonomy displayed. 2 taxonomies per post would add 60 to what WordPress needs to do! Basically there are a few paths to take moving forward and I would like to know what you would do in a situation like this. Do not build the functionality at all. Build the function and educate users that a caching plugin should be installed if they use get_the_terms() in archive views. Build the function + create another function that will cache all images before an archive template is loaded. This process would involve something like: After the <code> $posts </code> array has been generated (but before the template has been loaded), loop over all posts in the array calling get_the_terms() each iteration for every public taxonomy. The output of all term objects would be stored in a new array. Then, I could determine which images are associated with each term of every taxonomy and pass the image IDs to <code> get_posts() </code> in one shot. This would allow all image info to be cached for use in the template in 3 queries instead of 30, 60 or 90. IMHO 3 seems like a logical way to go, but I'm not really sure if it would be an anti optimization or not. Please let me know your thoughts about this!
I'd say your third option is the way to go. Incidentally, why did you roll your own static cache in <code> taxonomy_image_plugin_get_associations() </code> instead of using the built-in WP_Cache API for that? Is there a reason <code> wp_cache_get </code> wouldn't work here? Seems like using the WP object cache would optimize better when people do have caching plugins turned on.
How to organize and cache additional data associated with terms?
wordpress
I have never used the child theme function. so I am curious if it is possible to use this function to create a mobile version or no? I know that there are mobile plugins for this but I was curious if can use a child there for this
I don't see why it wouldn't be possible. I use a switch plugin to display a totally different theme for mobile. A child theme is a totally different theme. The dependencies on the parent theme should still work, as they are WP functions built in. Give it a try with a super simple child theme so you don't waste too much time. Just set up the style.css, use the import rule, but do something simple and drastic like changing a really obvious colour. See if it works.
use child theme for mobile version
wordpress
I've created a custom widget and placed it in functions.php. You can see the widget here: http://pastebin.com/3uWpeaFx (I've also created a similar widget that grabs a random image; it's included with the pastebin.) The widget allows users to plug in up to ten blocks of text/HTML, stores them in an array in JS, and displays one at random using JS. These are super simple widgets that are based on the default text widget that ships with WP. (I'm no PHP expert, so there's probably a more elegant way to create them, but they're simple to use, which is what the client needed.) The problem I'm having is this: Using more than one Random Text widget, even on multiple different sidebars displayed on different pages, causes all but the original to return 'undefined'. The text that you put in the box seems to store properly, and is editable through the WP admin interface; but when it comes to displaying it on the front-end, it doesn't echo the text properly. I'm sure it's something simple that I'm missing in the widget...any clues? Thanks!
No parent necessary: the difference between a not-working widget and a working widget was this: <code> $text1 = apply_filters( 'widget_text1', $instance['text1'], $instance ); </code> vs: <code> $text1 = apply_filters( 'widget_text1', empty($instance['text1']) ? '' : $instance['text1'], $instance, $this-&gt;id_base); </code> I realized putting multiple Random Text widgets on the same page, their titles worked, but their text content did not. So I copied the properties (empty($instance...etc.) from the title to each of the text instances. The widgets themselves were instantiated, but the text areas weren't. At least, that's what I think was happening. I don't know enough PHP to know for sure. If anybody has insight as to why the second version works and the first doesn't, I'd be happy to hear it. :)
Custom random quote widget breaks when used in multiple sidebars
wordpress
I am having trouble with my rewrite rules with my new nginx install. If I access the image manually like here, incredible.devpreview.co/wp-content/blogs.dir/2/files/2011/05/stockvault-colorful-illustration108811.jpg It shows up But WordPress is looking for it here incredible.devpreview.co/files/2011/05/stockvault-colorful-illustration108811.jpg Here is what is in my nginx config file. <code> server { listen 80; server_name www.devpreview.co; rewrite ^/(.*) http://devpreview.co/$1 permanent; } server { listen 80; server_name devpreview.co *.devpreview.co; access_log /var/www/devpreview.co/logs/access.log; error_log /var/www/devpreview.co/logs/error.log; location / { root /var/www/devpreview.co/public/; index index.html index.htm index.php; if (!-e $request_filename) { rewrite ^.+/?(/wp-.*) $1 last; rewrite ^.+/?(/.*\.php)$ $1 last; rewrite ^(.+)$ /index.php?q=$1 last; } } location ~* ^.+\.(html|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js)$ { root /var/www/devpreview.co/public/; rewrite ^/.*(/wp-.*/.*\.(html|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js))$ $1 last; rewrite ^.*/files/(.*(html|jpg|jpeg|gif|png|ico|css|zip|tgz|gz|rar|bz2|doc|xls|exe|pdf|ppt|txt|tar|mid|midi|wav|bmp|rtf|js))$/wp-includes/ms-files.php?file=$1 last; expires 30d; break; } </code>
The Nginx Multisite method outlined below has been tested and will work for subdomain Multisite installs and will also work with the domain mapping plugin. To simplify the process of making future changes the server files are organized into 3 separate files. The first is nginx.conf which holds the basic configuration and tells the server where to find the vhosts. nginx.conf <code> user www-data; worker_processes 4; pid /var/run/nginx.pid; events { worker_connections 1024; # multi_accept on; } http { sendfile on; tcp_nopush on; tcp_nodelay on; server_tokens off; include mime.types; default_type application/octet-stream; index index.php index.htm index.html redirect.php; #Gzip gzip on; gzip_vary on; gzip_proxied any; gzip_comp_level 6; gzip_buffers 16 8k; gzip_http_version 1.1; gzip_disable "MSIE [1-6].(?!.*SV1)"; gzip_types text/plain text/css application/json application/x-javascript text/xml application/xml application/xml+rss text/javascript; #FastCGI fastcgi_intercept_errors on; fastcgi_ignore_client_abort on; fastcgi_buffers 8 16k; fastcgi_buffer_size 32k; fastcgi_read_timeout 120; fastcgi_index index.php; limit_req_zone $binary_remote_addr zone=one:10m rate=1r/s; ## # Virtual Host Configs ## include /etc/nginx/sites-enabled/*; } </code> The next file will be the global WordPress include and will hold all our rewrite rules. wp-multi.conf <code> error_page 404 = @wordpress; log_not_found off; location / { try_files $uri $uri/ /index.php?$args; } rewrite /wp-admin$ $scheme://$host$uri/ permanent; location ~* \.(js|css|png|jpg|jpeg|gif|ico)$ { expires max; log_not_found off; } rewrite ^/files/(.+) /wp-includes/ms-files.php?file=$1 last; location ^~ /files/ { rewrite ^.*/files/(.+)$ /wp-includes/ms-files.php?file=$1 last; } # Rewrite multisite '.../wp-.*' and '.../*.php'. if (!-e $request_filename) { rewrite ^/[_0-9a-zA-Z-]+(/wp-.*) $1 last; rewrite ^/[_0-9a-zA-Z-]+(/.*\.php)$ $1 last; } location @wordpress { fastcgi_pass php; fastcgi_param SCRIPT_FILENAME $document_root/index.php; fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param SERVER_SOFTWARE nginx; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; fastcgi_pass 127.0.0.1:9000; fastcgi_param SCRIPT_NAME /index.php; } location ~ \.php$ { try_files $uri @wordpress; fastcgi_index index.php; fastcgi_pass php; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param QUERY_STRING $query_string; fastcgi_param REQUEST_METHOD $request_method; fastcgi_param CONTENT_TYPE $content_type; fastcgi_param CONTENT_LENGTH $content_length; fastcgi_param SCRIPT_NAME $fastcgi_script_name; fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name; fastcgi_param REQUEST_URI $request_uri; fastcgi_param DOCUMENT_URI $document_uri; fastcgi_param DOCUMENT_ROOT $document_root; fastcgi_param SERVER_PROTOCOL $server_protocol; fastcgi_param GATEWAY_INTERFACE CGI/1.1; fastcgi_param SERVER_SOFTWARE nginx; fastcgi_param REMOTE_ADDR $remote_addr; fastcgi_param REMOTE_PORT $remote_port; fastcgi_param SERVER_ADDR $server_addr; fastcgi_param SERVER_PORT $server_port; fastcgi_param SERVER_NAME $server_name; fastcgi_pass 127.0.0.1:9000; } </code> The third file is our vhosts. If your using the domain mapping plugin you can include 1 line for each domain mapped site. You can also add additional static sites to this file if needed. <code> server { listen 80; #Add a server_name entry for each mapped domain server_name star.main-multisite-domain.com *.main-multisite.com; server_name mapped-domain.com www.mapped-domain.com; server_name mapped-domain-2.com www.mapped-domain-2.com; server_name mapped-domain-3.com www.mapped-domain-3.com; root /srv/www/wordpress/public; access_log /srv/www/wordpress/logs/access.log; error_log /srv/www/wordpress/logs/error.log; index index.php index.html index.htm; #The Multisite rules are in the include below include global-wp-multi.conf; } #Begin Static Non WP Sites #Repeat the vhosts below for each additional static site. Make sure you make each one a root directory server { server_name static-non-wp-domain.com www.static-non-wp-domain.com; root /srv/www/static-non-wp-domain/public; error_log /srv/www/static-non-wp-domain/logs/error.log; index index.php index.html index.htm; } </code> For further reading on using WordPress with Nginx see: WordPress Performance Server - Nginx - Debian "squeeze"
Nginx WordPress Multisite Rewrite rules
wordpress
How do I change the formatting on http://wordpress.barrycarter.info/index.php/voronoi-temperature-map/ so that (for example) the map's nearly flush with the bottom of the menubar? I don't want to edit page.php, since that'll change all pages, not just this one.
After creating the specific CSS you need to format the page how you like, you could: Create a custom page template with the CSS and assign the template this page. Create a page-{slug}.php file with the CSS, where {slug} is the page slug for this page (most likely the filename should be page-voronoi-temperature-map.php). Create a page-{ID}.php file, where if the page ID is 6, WordPress will look to use page-6.php. These three options were mentioned in the Codex, under Template Hierarchy . By using any of these 3 options, you can alter the layout for this page without affecting all the rest of your pages.
Change CSS/formatting on specific page, but not pages in general?
wordpress
I want to display this file: http://data.barrycarter.info/aprswx.txt on wordpress.barrycarter.info, but all my attempts fail because of preprocessing: http://wordpress.barrycarter.info/index.php/test-kml-fail (use "view source" to see what parts of the file WP "hides" from view).
Use a plugin like syntax highlighter evolved. http://wordpress.org/extend/plugins/syntaxhighlighter/ Or wrap it in <code> &lt;pre&gt; </code> or <code> &lt;code&gt; </code> tags.
Display KML (or other "raw data" file) nicely in WP?
wordpress
There's a "Jobs" section on my website (custom post type), with various associated taxonomies (language spoken, type of contract, location, etc.) The website also has a very big user base (about 10 000 subscribers). These users have access to a form where they chose "jobs" criterias they are interested in, in order to receive a daily email with the list of "jobs" that correspond to their criterias. I'd like to have your opinion on the best way to implement that functionality. My first approach is this : Loop through all the "subscriber" users For each user, get the criterias they have chosen (language, type of contract, city, etc.) with these criterias, make a WP_Query on all the "jobs" published that day send the results by email This function would be triggered daily thanks to wp cron. My worry is that this is perhaps a very ressource intensive way (that's a loop executing 10 000 different wp_queries in a row!) The website is hosted on a dedicated webserver (quad core with about 8Gigs of ram) Is there a more efficient way ?
Make the user query when the job is submitted and put all matching subscribers in a queue. At the end of the day run through the queue once and send the mails.
What is the most efficient way to execute recursive complex queries?
wordpress
I am using a front end script to upload images , all works fine but recently i noticed the uploaded images are not saved in proper directory. My settings are to Organize my uploads into month- and year-based folders. my folders are 2011-> 03,04,05 (march , April , may). The problem is that if i upload a file today it saves in folder 03(March). If i use wp_handle_upload then the image is saved in proper folder 05 (May) , but then the image is not shown in media library and the different sizes are not made. Code i am using is <code> $image = media_handle_upload('async-upload', ''); </code>
Look into the first lines of this function: <code> function media_handle_upload( $file_id, $post_id, $post_data = array(), $overrides = array( 'test_form' =&gt; false ) ) { $time = current_time('mysql'); if ( $post = get_post($post_id) ) { if ( substr( $post-&gt;post_date, 0, 4 ) &gt; 0 ) $time = $post-&gt;post_date; } $name = $_FILES[$file_id]['name']; $file = wp_handle_upload($_FILES[$file_id], $overrides, $time); </code> The time is taken from the post date. You could bypass <code> media_handle_upload() </code> and use <code> wp_handle_upload() </code> directly. Update I don’t have the time to write a fully working standalone example, but here is an excerpt from my theme options class. It handles uploads, generates different images sizes and an attachment id. It is called by the general save function and handles multiple uploaded files in one rush. <code> /** * Saves uploaded files in media library and the corresponding id in option field. * * @return void */ protected function handle_uploads() { if ( ! isset ( $_FILES ) or empty ( $_FILES ) ) { return; } foreach ( $_FILES as $file_key =&gt; $file_arr ) { // Some bogus upload. if ( ! isset ( $this-&gt;fields[$file_key] ) or empty ( $file_arr['type'] ) ) { continue; } if ( ! $this-&gt;is_allowed_mime( $file_key, $file_arr ) ) { set_theme_mod( $file_key . '_error', 'wrong mime type' ); continue; } // The file is allowed, no error until now and the type is correct. $uploaded_file = wp_handle_upload( $file_arr , array( 'test_form' =&gt; FALSE ) ); // error if ( isset ( $uploaded_file['error'] ) ) { set_theme_mod( $file_key . '_error', $uploaded_file['error'] ); continue; } // add the file to the media library // Set up options array to add this file as an attachment $attachment = array( 'post_mime_type' =&gt; $uploaded_file['type'] , 'post_title' =&gt; $this-&gt;get_media_name( $file_key, $uploaded_file['file'] ) ); // Adds the file to the media library and generates the thumbnails. $attach_id = wp_insert_attachment( $attachment , $uploaded_file['file'] ); $this-&gt;create_upload_meta( $attach_id, $uploaded_file['file'] ); // Update the theme mod. set_theme_mod( $file_key, $attach_id ); remove_theme_mod( $file_key . '_error' ); } } /** * Adds meta data to the uploaded file * * @param int $attach_id * @param string $file * @return void */ protected function create_upload_meta( $attach_id, $file ) { // Create meta data from EXIF fields. require_once ABSPATH . 'wp-admin/includes/image.php'; $attach_data = wp_generate_attachment_metadata( $attach_id , $file ); wp_update_attachment_metadata($attach_id, $attach_data); } </code> Some notes: <code> is_allowed_mime() </code> checks for MIME types set in <code> $fields </code> which are set in my controller. The MIME type for a favicon for example is either <code> image/x-icon </code> or <code> image/vnd.microsoft.icon </code> . <code> get_media_name() </code> may use a predefined name for the attachment (e.g. logo ). In your function you probably want to return <code> $attach_id </code> and use it in a post meta field or something similar.
media_handle_upload weird thing
wordpress
I'm thinking of doing up a couple of premium themes, and selling copies of them. I've never done anything like this before, so I have a couple of questions. I appreciate that this is mainly a forum for asking technical questions, so if anyone wants to point me in the direction of somewhere that might be more appropriate for these questions, please let me know. My main question is about copies of a theme. If I sell a copy of a premium theme, and the end result is that a person gets a zip file of my theme, is there any technical way to limit them to only using it in one installation of WordPress? Or do I just rely on the goodness of their hearts? Also, a related question: What kind of license, if any, should I include with a premium theme? Thanks.
There is no way to prevent the free distribution of your theme. You could make it harder by selling a copy that is restricted to a license key and a salted hash of the domain. But even if you put the code for this in a pre-compiled script it will be possible to get around it. Sell support, upgrades and reliability, not the naked code. For the license: PHP code which is uses WordPress functions and hooks is GPL per default by some peoples interpretation. For your stylesheets, images and standalone PHP code you can use a different license.
How do you protect a premium theme from being copied?
wordpress
Im trying to build a function which grabs the feedburner "readers" using <code> wp_remote_get() </code> . I noticed that it frequently returned a value of <code> 0 </code> . I assumed at first that it was a WordPress error (handled by <code> is_wp_error() </code> ) or a flaw with <code> wp_remote_get() </code> . Wrong of-course.. Feedburner just kept crashing, so I used a second transient to store a result (never <code> 0 </code> ) with an expiration of 7 days. The part which i cant get my head around is handling errors with <code> is_wp_error() </code> . I need to force an error so i can handle it properly, before I put it up on production. Heres an illustration: <code> $result = wp_remote_get( 'http://feedburner.google.com/api/awareness/1.0/GetFeedData?uri=' . urlencode($username) ); if ( is_wp_error($result) ) return false; </code> Whats the best way to force an error? Should i use <code> new WP_error() </code> ?
WordPress can be inconsistant as to hen is returns a <code> WP_Error </code> object and when it just returns <code> false </code> or <code> string(0) </code> when actually there was an error. I am not sure exactly what feedburner is returning to not trigger a <code> WP_Error </code> from <code> wp_remote_get() </code> - but if you know <code> wp_remote_get() </code> will return an WP_Error, I would just set <code> $result = new WP_Error( 'my-error' ); </code> This is the same object that <code> wp_remote_get() </code> will return on error.
is_wp_error() and handling errors
wordpress
I'd like to exclude a specific user account from showing up in the activity stream. I found this code that's supposed to exclude the Admin. Any clue how to exclude a specific user? (this code goes in bp-custom.php) <code> &lt;?php add_action("plugins_loaded","bpdev_init_sm_mode"); function bpdev_init_sm_mode(){ if(is_site_admin()) remove_action("wp_head","bp_core_record_activity");//id SM is on, remove the record activity hook } ?&gt; </code> Thank you.
<code> &lt;?php add_action("plugins_loaded","bpdev_init_sm_mode"); function bpdev_init_sm_mode(){ global $current_user; if(is_user_logged_in()) { get_currentuserinfo(); if("someusername" == $current_user-&gt;user_login) { remove_action("wp_head","bp_core_record_activity");//id SM is on, remove the record activity hook } } } ?&gt; </code>
Exclude User from Activity Stream in BuddyPress?
wordpress
The code below shows the active sub menu of the Main Menu. It's nearly perfect, however, I need it to show ALL subitems of these sub items, and their children. AKA unlimited depth. Thanks in advance! To further clarify here is an example: WP - Main Menu Home About News (Active Menu Item) Press Social Facebook Twitter Speeches Contact With the code currently, if I'm on News, Press, Social, Facebook, or Twitter Page, it shows the side menu: Press Social Speeches That is what I want, except that on all of those pages, "Social"'s two children (Facebook and Twitter should appear under social as well. <code> class Selective_Walker extends Walker_Nav_Menu { function walk( $elements, $max_depth) { $args = array_slice(func_get_args(), 2); $output = ''; if ($max_depth &lt; -1) //invalid parameter return $output; if (empty($elements)) //nothing to walk return $output; $id_field = $this-&gt;db_fields['id']; $parent_field = $this-&gt;db_fields['parent']; // flat display if ( -1 == $max_depth ) { $empty_array = array(); foreach ( $elements as $e ) $this-&gt;display_element( $e, $empty_array, 1, 0, $args, $output ); return $output; } /* * need to display in hierarchical order * separate elements into two buckets: top level and children elements * children_elements is two dimensional array, eg. * children_elements[10][] contains all sub-elements whose parent is 10. */ $top_level_elements = array(); $children_elements = array(); foreach ( $elements as $e) { if ( 0 == $e-&gt;$parent_field ) $top_level_elements[] = $e; else $children_elements[ $e-&gt;$parent_field ][] = $e; } /* * when none of the elements is top level * assume the first one must be root of the sub elements */ if ( empty($top_level_elements) ) { $first = array_slice( $elements, 0, 1 ); $root = $first[0]; $top_level_elements = array(); $children_elements = array(); foreach ( $elements as $e) { if ( $root-&gt;$parent_field == $e-&gt;$parent_field ) $top_level_elements[] = $e; else $children_elements[ $e-&gt;$parent_field ][] = $e; } } $current_element_markers = array( 'current-menu-item', 'current-menu-parent', 'current-menu-ancestor' ); //added by continent7 foreach ( $top_level_elements as $e ){ //changed by continent7 // descend only on current tree $descend_test = array_intersect( $current_element_markers, $e-&gt;classes ); if ( !empty( $descend_test ) ) $this-&gt;display_element( $e, $children_elements, 0, 0, $args, $output ); } /* * if we are displaying all levels, and remaining children_elements is not empty, * then we got orphans, which should be displayed regardless */ /* removed by continent7 if ( ( $max_depth == 0 ) &amp;&amp; count( $children_elements ) &gt; 0 ) { $empty_array = array(); foreach ( $children_elements as $orphans ) foreach( $orphans as $op ) $this-&gt;display_element( $op, $empty_array, 1, 0, $args, $output ); } */ /*added by alpguneysel */ $pos = strpos($output, '&lt;a'); $pos2 = strpos($output, 'a&gt;'); $topper= substr($output, 0, $pos).substr($output, $pos2+2); $pos3 = strpos($topper, '&gt;'); $lasst=substr($topper, $pos3+1); $submenu= substr($lasst, 0, -6); return $submenu; } } </code>
After no solution from the community :-/ and days of reviewing it over and over I determined I simply had to change a 2 to a 0 for unlimited depth, and now it works perfectly!
Show All Children of WordPress Menu
wordpress
I am currently running WordPress 3.1.2 on PHP 5.1.6. The minimum requirement for WordPress 3.2 is going to be PHP 5.2.4 or greater. If I keep running WordPress 3.1.2 and there is a security issue will they provide security updates for 3.1 or will I be forced to upgrade my version of PHP so that I can upgrade to WordPress 3.2?
WordPress backports security updates usually 1-3 versions back but they don't promise anything. The WordPress LTS philosophy is that LTS = " Long Term Suckage " The Long Term Suckage theory is: While I like the theory of LTS, what happens in practice is it covers up the incompetence of IT or developers because they put off small slightly painful upgrades until they get so out of date of trunk (3 years? 5 years?) and you have to go through a giant, painful, screws everybody over upgrade. -- Matt Mullenweg Like how your sysadmin doesn't want to update PHP now that it's 6 years old and 2 major branches behind. I would point my sysadmin to this thread from the RedHat mailing list from 2009 . There are 3rd party packages available so you don't have to compile from source If the version of php you need is not available in rhn you could use some 3rd party repos like rpmforge, ATrpms or the Remi Collet Repository that is specially made for mysql 5.1 and php5.2.9 under EL5. I would be more concerned about PHP 5.1 branch security issues than something that might come up with WordPress. Edit: Also found this official RedHat announcement from Jan 2011 RHEL 5 now shipping with PHP 5.3.
Will there be security updates for 3.1 once 3.2 is released?
wordpress
i'm using an rss to post plugin. The posts fetches from the RSS do not have any pictures associated with them. Is there a way to automatically assign a 'featured image' to posts from a category? Another option is that in my WP theme, with the custom field as 'thumb' I can add images/reuse same images.. is there a way to make use of this and assign a default pic to all posts from a category? Edit: Based on Martin's suggestion I installed the get image plugin. The code mentioned in the read me is this: <code> get_the_image( array( 'default_image' =&gt; 'http://www.mydomain.com/wp-content/uploads/defaultimage.png' ) ); </code> However, my theme isn't that direct. It makes use of a function in the functions.php file. <code> // Get image attachment (sizes: thumbnail, medium, full) function get_thumbnail($postid=0, $size='full') { if ($postid&lt;1) $postid = get_the_ID(); $thumb_key = get_theme_mod('thumb_key'); if($thumb_key) $thumb_key = $thumb_key; else $thumb_key = 'thumb'; $thumb = get_post_meta($postid, $thumb_key, TRUE); // Declare the custom field for the image if ($thumb != null or $thumb != '') { return $thumb; } elseif ($images = get_children(array( 'post_parent' =&gt; $postid, 'post_type' =&gt; 'attachment', 'numberposts' =&gt; '1', 'post_mime_type' =&gt; 'image', ))) { foreach($images as $image) { $thumbnail=wp_get_attachment_image_src($image-&gt;ID, $size); return $thumbnail[0]; } } else { return get_bloginfo ( 'stylesheet_directory' ).'/images/default_thumb.gif'; } } // Automatically display/resize thumbnail function tj_thumbnail($width, $height) { echo '&lt;a href="'.get_permalink($post-&gt;ID).'" rel="bookmark"&gt;&lt;img src="'.get_bloginfo('template_url').'/timthumb.php?src='.get_thumbnail($post-&gt;ID, 'full').'&amp;amp;h='.$height.'&amp;amp;w='.$width.'&amp;amp;zc=1" alt="'.get_the_title().'" /&gt;&lt;/a&gt;'; } </code> I need help in adding the get_the_image function into the one above so it checks.. If category id=120, then display mydefaultimage.png else, do the regular thing. Thanks.
if i understand your question correctly then have a go with Justin Tadlocks get the image plugin , olden but golden and does the default image per category etc.
How to add featured images to posts from a category
wordpress
I have custom post types registered and they are working fine with their normal URLs. My Custom post types have 'members' as their slug. Now I am trying to have a custom permalink for my custom post types. Here is my $wp_write-> add_rule <code> $wp_rewrite-&gt;add_rule('members/.+?/(.+)/$','index.php?post_type=pasha_members&amp;name=$matches[1]', 'top'); </code> Below is my $wp_rewrite-> rules array. <code> array( ['members/.+?/(.+)/$'] =&gt; 'index.php?post_type=pasha_members&amp;name=$matches[1]' ['category/(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$'] =&gt; 'index.php?category_name=$matches[1]&amp;feed=$matches[2]' ['category/(.+?)/(feed|rdf|rss|rss2|atom)/?$'] =&gt; 'index.php?category_name=$matches[1]&amp;feed=$matches[2]' ... ); </code> And here is the url that I am trying to access, I am not able to figure out what I am doing wrong. <code> http://wp.dev/members/city1-city2/best-compnay/ </code> When I change Permalink settings to default in Settings-> Permalink, I can access the custom post just fine using the following url. <code> http://wp.dev/?post_type=pasha_members&amp;name=best-compnay </code> Let me know if you need more information. Any help pointers are much appreciated. NOTE: I have put the add_rule in init instead of activate just for the testing. I also have put the flush_rewrite_rules in the init, its also temporarily until its fixed.
It appears that WordPress cuts off the final <code> / </code> before it starts matching the URL. So make it optional in the regex and it should work: <code> members/.+?/(.+)/?$ </code> If the city and company parts will not contain slashes it could be even more clear to use <code> [^/]+ </code> to match them ("everything up to a slash"). Then your regex would become: <code> members/[^/]+/([^/]+)/?$ </code> I created stackexchange-url ("a plugin to analyze your rewrite rules"), it is really easy to play with and debug your rules. Although you made me discover an error in it: it did not remove the final slash, so your first regex matched in my analyzer but not in the "real" WordPress. I'll update it soon!
Custom Permalinks for Custom Post Types
wordpress
Is it possible to take the blue publish button in back end of the wordpress and place it in the frontend near the post in my index.php. I need a way to publish the pending article without going to dashboard and only admin can see the publish button? <code> &lt;?php $args=array( 'post_type' =&gt; 'post', 'post_status' =&gt; 'pending', 'order' =&gt; 'ASC', 'caller_get_posts' =&gt;1, 'paged' =&gt;$paged, ); </code> Thank You all in advance for help :D
First create a function that will print the publish button : <code> //function to print publish button function show_publish_button(){ Global $post; //only print fi admin if (current_user_can('manage_options')){ echo '&lt;form name="front_end_publish" method="POST" action=""&gt; &lt;input type="hidden" name="pid" id="pid" value="'.$post-&gt;ID.'"&gt; &lt;input type="hidden" name="FE_PUBLISH" id="FE_PUBLISH" value="FE_PUBLISH"&gt; &lt;input type="submit" name="submit" id="submit" value="Publish"&gt; &lt;/form&gt;'; } } </code> Next create a function to change the post status: <code> //function to update post status function change_post_status($post_id,$status){ $current_post = get_post( $post_id, 'ARRAY_A' ); $current_post['post_status'] = $status; wp_update_post($current_post); } </code> Then make sure to catch the submit of the button: <code> if (isset($_POST['FE_PUBLISH']) &amp;&amp; $_POST['FE_PUBLISH'] == 'FE_PUBLISH'){ if (isset($_POST['pid']) &amp;&amp; !empty($_POST['pid'])){ change_post_status((int)$_POST['pid'],'publish'); } } </code> Now all of the above code can go in your theme's functions.php file and all you have to do is add <code> show_publish_button(); </code> in your loop of pending posts after each post.
Publish pending article from front end with a button?
wordpress
This is my first real delve into custom post types and taxonomies, i suppose it will all come to me in a flash of inspiration but right now i have confused myself beyond all realms of possibility and need some advice as whether im going on the right track. heres what i have: Three custom post types, namely: sale rental business all the above share 2 taxonomies (location and region) and then they have their own specific taxonomies too. Now im looking at template files for each of the Custom Post Types and also template files for the taxonomies. So of course i headed over to WP Codex and checked out custom post type templates, now if i understand correctly to template each of my custom post types i should use * archive- *name_of_post_type.php and * single- *name_of_post_type.php for when in single post view. Ok so up to here i reckon im ok, now this is where im confused, off to Codex Again this time to find out how to add a template to each of the taxonomies, codex tells me this * taxonomy- *name_of_taxonomy.php, now a couple of questions if i may: 1) am i going about this the correct way 2) is the taxonomy template a single view (ie like single.php) or a looped view, im guessing its looped like categories. 3) can i create just one template and include all taxonomies (via an if statement to shake through seperate loop files?) regards Martin
Looks like you got the hang of it. Taxonomy template is an archive of posts that share a term just like categories or tags, so if by looped view you mean archive then yes you are correct. you can create just one template that will include all taxonomies and use the get_template_part function to include the correct loop.
Custom post type and taxonomy page templates
wordpress
I'm trying to set the Post Title or Post Content as the caption in my Nivo Slider . Any ideas on how to do this?
You need to set the "title" attribute of the images to be the post title. You can do it like this: <code> title=' . get_post_title() . ' </code> You will have to modify the HTML output of the plugin, but it should not be very difficult at all.
Custom Caption on WP Nivo Slider
wordpress
For those who are curious, I'm changing the theme but this theme relies on CSS3 and HTML5 and displays very ugly in IE 8 or below. - Especially the navigation. What I want to do is keep my old theme and use it for IE users only, I assume if this can be done for a mobile site, it can for IE. Would it be easier to just get another WP installation and duplicate the content (What's the easiest way to do this?). Or is there a method, such as the mobile method to redirect users to that theme. My plan was, create a second installation with the existing theme then somehow grab the content from the main site and add and IF code redirecting IE users. Is this possible, or is there an easier/ or simpler way?
maybe you can somehow use template redirect? I'm not too clear on how it works, but it may be worth investigating. <code> function my_check_is_ie() { global $is_winIE; if ( ! $is_winIE ) return; // load template for IE include(TEMPLATEPATH . '/IE_template.php'); // or maybe? if( is_home() ) include(TEMPLATEPATH . '/IE_home.php'); elseif( is_single() ) include(TEMPLATEPATH . '/IE_single.php'); // etc. } add_action('template_redirect', 'my_check_is_ie'); </code> Edit - ok, I think I've figured it out. I haven't tested this in the wild, so make sure it works first! You'll have to make this a plugin, since once the theme is loaded it's too late to pull the theme switch... <code> &lt;?php /* Plugin Name: randomkljsaduiyerth */ global $is_winIE; if($is_winIE){ add_filter('template', 'my_switch_themes'); add_filter('stylesheet', 'my_switch_themes'); } function my_switch_themes(){ // return the name of your IE theme return 'my-IE-theme-Name-Here'; } </code> Edit2 - you could add another check for the presence of a GET variable if you wanted to let people switch via a link like: http://yourdomain.com/?IE_version <code> if( isset($_GET['IE_version']) ): // add_filter here, or better yet if you're doing a number of checks, // set a flag if any check is true and add_filter last endif; </code> you could also use cookies to store the theme preference <code> // check the cookie if( isset($_COOKIE["my_domain_cookie"]) ) // set the cookie setcookie("my_domain_cookie", "My Cookie Val", time()+60*60*24*30); </code>
Making an IE only site (Like a Mobile only site)
wordpress
Okay so the website I webmaster for http://www.detroitdungeon.com has been having some analytic issues as of lately. I have the google analytics plugin installed and it was working fine for quite sometime. All of a sudden the plugin caused IE users to crash after the page had loaded. So instead of using the plug in I decided to use the code given to me by google and I placed it in the footer of the website. Doing this caused the webpage to crash with all browsers. after the code has been placed in the footer the source code reads <code> &lt;b&gt;Parse error&lt;/b&gt;: syntax error, unexpected T_CONSTANT_ENCAPSED_STRING, expecting ',' or ';' in &lt;b&gt;/home/content/36/5385336/html/detroitdungeon/wp-content/themes/delighted_black2/footer.php&lt;/b&gt; on line &lt;b&gt;5&lt;/b&gt; </code> Here is footer.php <code> &lt;?php include('footer_content.php');$delight_mainfont = get_option('delight_mainfont');echo '&lt;div id="footcopy"&gt;&lt;span class="left"&gt;&lt;a href="http://zenverse.net/delighted-black-wordpress-theme/"&gt;Delighted Black&lt;/a&gt; designed by &lt;a href="http://yourchristianspace.com"&gt;Christian Myspace&lt;/a&gt; &amp; &lt;a href="http://www.digitaldesignzmedia.com"&gt;Designed By: Digital Designz Media Group&lt;/a&gt;&lt;/span&gt;&lt;span class="right"&gt;In conjunction with &lt;a href="http://pingler.com"&gt;Ping Services&lt;/a&gt; &lt;span style="font-family:tahoma;"&gt;|&lt;/span&gt; &lt;a href="http://frenchteacherjobs.com"&gt;French Teacher Jobs&lt;/a&gt; &lt;span style="font-family:tahoma;"&gt;|&lt;/span&gt; &lt;a href="http://mathsteacherjobs.com"&gt;Maths Teacher Jobs&lt;/a&gt; &lt;/span&gt; &lt;div class="clear"&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt; &lt;!--/page--&gt; &lt;script type="text/JavaScript"&gt;var TFN='';var TFA='';var TFI='0';var TFL='0';var tf_RetServer="rt.trafficfacts.com";var tf_SiteId="254g7d80916f3af3bbc0ac2542301cd153424f1b1aa7h16";var tf_ScrServer=document.location.protocol+"//rt.trafficfacts.com/tf.php?k=254g7d80916f3af3bbc0ac2542301cd153424f1b1aa7h16;c=s;v=5";document.write(unescape('%3Cscript type="text/JavaScript" src="'+tf_ScrServer+'"&gt;%3C/script&gt;'));&lt;/script&gt;&lt;noscript&gt;&lt;img src="http://rt.trafficfacts.com/ns.php?k=254g7d80916f3af3bbc0ac2542301cd153424f1b1aa7h16" height="1" width="1" alt=""/&gt;&lt;/noscript&gt; &lt;/body&gt;&lt;/html&gt;'; ?&gt; </code> I tried going with godaddy analytics and the same issue is happening. Any help would be GREATLY appreciated.
<code> &lt;?php include('footer_content.php');$delight_mainfont = get_option('delight_mainfont');echo '&lt;div id="footcopy"&gt;&lt;span class="left"&gt;&lt;a href="http://zenverse.net/delighted-black-wordpress-theme/"&gt;Delighted Black&lt;/a&gt; designed by &lt;a href="http://yourchristianspace.com"&gt;Christian Myspace&lt;/a&gt; &amp; &lt;a href="http://www.digitaldesignzmedia.com"&gt;Designed By: Digital Designz Media Group&lt;/a&gt;&lt;/span&gt;&lt;span class="right"&gt;In conjunction with &lt;a href="http://pingler.com"&gt;Ping Services&lt;/a&gt; &lt;span style="font-family:tahoma;"&gt;|&lt;/span&gt; &lt;a href="http://frenchteacherjobs.com"&gt;French Teacher Jobs&lt;/a&gt; &lt;span style="font-family:tahoma;"&gt;|&lt;/span&gt; &lt;a href="http://mathsteacherjobs.com"&gt;Maths Teacher Jobs&lt;/a&gt;&lt;/span&gt; &lt;div class="clear"&gt;&lt;/div&gt;&lt;/div&gt;&lt;/div&gt; &lt;!--/page--&gt; ';?&gt; &lt;script type="text/JavaScript"&gt;var TFN='';var TFA='';var TFI='0';var TFL='0';var tf_RetServer="rt.trafficfacts.com";var tf_SiteId="254g7d80916f3af3bbc0ac2542301cd153424f1b1aa7h16";var tf_ScrServer=document.location.protocol+"//rt.trafficfacts.com/tf.php?k=254g7d80916f3af3bbc0ac2542301cd153424f1b1aa7h16;c=s;v=5";document.write(unescape('%3Cscript type="text/JavaScript" src="'+tf_ScrServer+'"&gt;%3C/script&gt;'));&lt;/script&gt;&lt;noscript&gt;&lt;img src="http://rt.trafficfacts.com/ns.php?k=254g7d80916f3af3bbc0ac2542301cd153424f1b1aa7h16" height="1" width="1" alt=""/&gt;&lt;/noscript&gt; &lt;/body&gt;&lt;/html&gt; </code>
Analytics causes website to crash
wordpress
I'm writing a custom plugin that allows a particular page to have it's own sidebar with widgets. It works great so far, but what I'd like to do is generalize it more and allow the plugin to "override" the dynamic sidebar of any page (if it has a custom sidebar) without having to edit any template files. I've tried several hooks and have delved into the code a bit, but nothing stands our or works so far. To save some time I thought I'd see if anybody has any working solutions to this issue? I might be able to solve this issue, but it is straining my "after working hours" brain. If it isn't possible I'd be more than willing to have a short-code or function call that does this for me, but I'd really like to make it idiot proof and just have it work without any template changes.
<code> dynamic_sidebar() </code> calls <code> wp_get_sidebars_widgets() </code> to get the list of all sidebars and their widgets. This output is filtered through <code> sidebars_widgets </code> , so you can stackexchange-url ("modify it to add or remove widgets"). This array only contains widget IDs, so you need to register the widget instance too (it should end up in the global <code> $wp_registered_widgets </code> array). I think you can do this with <code> wp_register_sidebar_widget() </code> , but it is possible that this is older code from the time when a widget could not have multiple instances yet.
Override dynamic_sidebar() in plugin?
wordpress
I'm sure this is an inappropriate question for this SE because it's not programming related AFAIK but maybe someone here has an idea. I've been posting code into my blog for years and have had no formatting concerns. Now all of a sudden, when I copy and paste code from whatever IDE I'm working in, the LFs are stripped out. I can't imagine what may have changed. Some additional troubleshooting info: I'm pasting into the visual editor, not the HTML editor (this is how I've always done it) pasting into a PRE section doesn't help the CR/LF information is in the clipboard (when I paste into Word for example, the LFs and tabs are preserved) pasting using Paste Text has the correct LFs but strips out tabs so that's not an option pasting using Paste from Word does the same I'm using the latest WP update (as of this time) WP 3.1.2 I"m using TinyMCE, but have disabled it and that's had no effect; also WP-Syntax, no joy Can anyone suggest something else to look into to figure this out? It's killing me. I've re-read the section in the Codex just to be sure I'm not missing something obvious, but there's nothing that pops up. I've been pasting code into my blog (www.tomauger.com) for years and years now without any special plugins, just sticking it inside PRE tags and have never ever encountered this issue. What could have changed?
This almost certainly appears to be a Google Chrome issue (though the bug is still probably within WordPress, since Chrome does preserve all tabs and linebreaks when pasting into the Paste Text or Paste from Word areas, so Chrome is not itself stripping out the linebreaks.) I'm recommending we close this cause it probably doesn't belong here anyway, and I'll post a bug on Trac.
Pasting code into WordPress post - LFs being eaten
wordpress
First, Here is the full error: <code> PHP Fatal error: Call to undefined function download_url() in /path/to/wordpress/wp-admin/includes/media.php on line 562 </code> I have also posted the related functions at the bottom of my question. I am modifying a script for my company's website which allows us to automate the retrieval and uploading of content from our content provider. Due to the way they organize their XML, I need to upload the images related to the articles separately from the main body of the articles. I tried using media_sideload_image() to do this, but I recieved the error: The function (media_sideload_image()) which calls download_url and results in the error: <code> PHP Fatal error: Call to undefined function download_url() in /path/to/wordpress/wp-admin/includes/media.php on line 562 </code> As can be seen, I successfully included media.php - and the rest of my script has already been implemented on to the site, and I have not run into any other issues with accessing Wordpress files. The error would appear to be with media.php itself - which I find unusual. Any ideas on how I can resolve this problem? Alternatively, if you know of another function I can use to do this, that would also be appreciated. By all means, if you require any more details on the issue just ask. <code> /** * Download an image from the specified URL and attach it to a post. * * @since 2.6.0 * * @param string $file The URL of the image to download * @param int $post_id The post ID the media is to be associated with * @param string $desc Optional. Description of the image * @return string|WP_Error Populated HTML img tag on success */ function media_sideload_image($file, $post_id, $desc = null) { if ( ! empty($file) ) { // Download file to temp location $tmp = download_url( $file ); // Set variables for storage // fix file filename for query strings preg_match('/[^\?]+\.(jpg|JPG|jpe|JPE|jpeg|JPEG|gif|GIF|png|PNG)/', $file, $matches); $file_array['name'] = basename($matches[0]); $file_array['tmp_name'] = $tmp; // If error storing temporarily, unlink if ( is_wp_error( $tmp ) ) { @unlink($file_array['tmp_name']); $file_array['tmp_name'] = ''; } // do the validation and storage stuff $id = media_handle_sideload( $file_array, $post_id, $desc ); // If error storing permanently, unlink if ( is_wp_error($id) ) { @unlink($file_array['tmp_name']); return $id; } $src = wp_get_attachment_url( $id ); } // Finally check to make sure the file has been saved, then return the html if ( ! empty($src) ) { $alt = isset($desc) ? esc_attr($desc) : ''; $html = "&lt;img src='$src' alt='$alt' /&gt;"; return $html; } } </code> The function where I call media_sideload_image() in my code: <code> //Upload the image if it exists, and return the post_id function upload_image($post_id, $image_url) { require_once('wp-admin/includes/media.php'); $image_url = 'http://admin.gkbusiness.com/gkbusiness/files/2011/04/LOGOGKMBUS1.jpg'; media_sideload_image($image_url, $post_id); return $post_id; } </code>
You have to include /path/to/wordpress/wp-admin/includes/file.php this file also, as the media.php uses the function download_url() from that file.
PHP Fatal error: Call to undefined function download_url()
wordpress
I've assigned a specific html page (let's call it an author bio page) to each user in the 'website' field within the user admin area. How do I get that URL to display within a single page post? I'm assuming that I'm to use $curauth-> user_url but it returns a blank page.
you need to assign <code> $curauth </code> and since you are not on an author archive but on a regular page you can use get_userdata function and pass the user ID like so: <code> $curauth = get_userdata(1); //and then use echo $curauth-&gt;user_url; </code> or if you are in the loop you can use <code> the_author_link(); </code> which will Displays the author's Website URL as a link and the text for the link is the author's Profile Display name publicly as field.
Author website URL
wordpress
is there a way to add custom user meta fields (like the one in the profile.php which contain specific user data), but only an admin (or an other user with enough capabilities) can change them? Maybe I'm thinking too complicated, how would you tell your site visitors who from your users is doing which work on the site, if there are too many users (and probably often changing work) that it would be impossible too make a static page or something. Greetings, .wired // edit: you may replace "work" with position. I want to give the users a specific position. That's not the user role!
I think I get what you are saying, and if not, forgive me: just add your meta fields / metabox inside: <code> if( current_user_can( 'administrator' ) ){ // put code here } </code> *this is assuming you aren't asking how to add a metafield or metabox.
Add User meta fields, which only admin can edit
wordpress
I am sure I am missing something very straightforward, but there seems to be no way for me to upload a photo for my profile or for a user profile the will be used in place of the placeholder white on grey silhouette that my theme displays. I did Google for this, and I seem to get a bewildering array of possible plugins, but I would have thought that there was an easier way of doing this? If I must install a plugin, what is the best one? (I realize that is a difficult question, but even getting it down to a shortlist would be nice!) I am using Wordpress version 3.1.2 with the Twenty Ten theme version 1.2 I have the following plugins active: Google Analytics for WordPress version 4.1 SyntaxHighlighter version 3.1.1 Thank you in advance.
These images are called Avatars . By default, WordPress works with the Gravatar service , which hosts your avatar on one central location so you don't have to upload it to every site you comment on. It is based on your e-mail address (you see it on action on this site too). If you want to provide the functionality to load avatar images from your own site you will indeed need to load an extra plugin. Some popular plugins are: Add Local Avatar Simple Local Avatars
How do I allow users to supply a photo/image to be used instead of the grey/white silhouette?
wordpress
I tried to add thumbnail support to my theme <code> add_theme_support( 'post-thumbnails' ); set_post_thumbnail_size(133, 133, true); add_theme_support( 'post-thumbnails', array( 'post' ) ); add_theme_support( 'post-thumbnails', array( 'page' ) ); </code> So this isnt working, or at least I'm not sure how this should work, help!
This looks flawed: <code> add_theme_support( 'post-thumbnails', array( 'post' ) ); add_theme_support( 'post-thumbnails', array( 'page' ) ); </code> Do you see the post thumbnail box on pages? If so, you have just overwritten the support on posts with the second declaration. Better: <code> add_theme_support( 'post-thumbnails', array( 'post', 'page' ) ); </code>
How do you get thumbnails to show up in the admin edit post?
wordpress
Does anyone know why wordpress converts some html entities to their numeric equivalents? I've found that in some posts, where a non-breaking space <code> &amp;nbsp; </code> entity would be appropriate, wordpress uses <code> &amp;#160; </code> instead. Seems to me that using the symbolic version of the entity would be better than a numeric version. The routine that this is being done in (appears to be) ent2ncr in wp-includes/formatting.php. When I converted my blog from a single site to multi-site (different install &amp; database), the numeric entities were not converted properly (possibly due to a database difference). Had the symbolic entities been used, I doubt this would have been a problem.
In XHTML entities are not part of the DTD, and user agents are not required to support them. Exceptions: <code> &amp;amp; </code> , <code> &amp;lt; </code> , <code> &amp;gt; </code> , <code> &amp;quot; </code> and <code> &amp;apos; </code> . To keep WordPress X(HT)ML compatible numeric references are used instead.
Anyone know why wordpress converts some html entities to their numeric equivalents?
wordpress
I am learning development of plugins, I am stuck into saving the plugin options form data. I have a plugin options page, where three fields asking for number of videos, height and width are coded. When I enter the values into it, and hit on save its just saving one value, that is, number of videos. Here is my code <code> &lt;?php add_action('admin_init', 'ozh_sampleoptions_init' ); add_action('admin_menu', 'ozh_sampleoptions_add_page'); // Init plugin options to white list our options function ozh_sampleoptions_init(){ register_setting( 'ozh_sampleoptions_options', 'ozh_sample', 'ozh_sampleoptions_validate' ); } // Add menu page function ozh_sampleoptions_add_page() { add_options_page('Youtube Video Settings', 'Youtube Video Settings', 'manage_options', 'ozh_sampleoptions', 'ozh_sampleoptions_do_page'); } // Draw the menu page itself function ozh_sampleoptions_do_page() { ?&gt; &lt;div class="wrap"&gt; &lt;h2&gt;Youtube Video Setting Options&lt;/h2&gt; &lt;form method="post" action="options.php"&gt; &lt;?php settings_fields('ozh_sampleoptions_options'); ?&gt; &lt;?php $options = get_option('ozh_sample'); ?&gt; &lt;table class="form-table"&gt; &lt;tr valign="top"&gt;&lt;th scope="row"&gt;No of videos:&lt;/th&gt; &lt;td&gt;&lt;input type="text" name="ozh_sample[sometext]" value="&lt;?php echo $options['sometext']; ?&gt;" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr valign="top"&gt;&lt;th scope="row"&gt;Height:&lt;/th&gt; &lt;td&gt;&lt;input type="text" name="ozh_sample[hgt]" value="&lt;?php echo $options['hgt']; ?&gt;" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;tr valign="top"&gt;&lt;th scope="row"&gt;Width:&lt;/th&gt; &lt;td&gt;&lt;input type="text" name="ozh_sample[wid]" value="&lt;?php echo $options['wid']; ?&gt;" /&gt;&lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; &lt;p class="submit"&gt; &lt;input type="submit" class="button-primary" value="&lt;?php _e('Save Changes') ?&gt;" /&gt; &lt;/p&gt; &lt;/form&gt; &lt;/div&gt; &lt;?php } // Sanitize and validate input. Accepts an array, return a sanitized array. function ozh_sampleoptions_validate($input) { // Our first value is either 0 or 1 //$input['option1'] = ( $input['option1'] == 1 ? 1 : 0 ); // Say our second option must be safe text with no HTML tags $input['sometext'] = wp_filter_nohtml_kses($input['sometext']); $input['hgt'] = wp_filter_nohtml_kses($input['hgt']); $input['wid'] = wp_filter_nohtml_kses($input['wid']); return $input; } $myoptions = get_option( 'ozh_sampleoptions_options' ); echo 'Niraj'; echo $options['sometext']; ?&gt; </code> Its not saving height and width. I know I have to work on <code> &lt;input type='hidden' name='page_options' value='vidNO'/&gt; </code> code, but not getting it, Can anyone help me in this???
First, you really should be storing your options as an array in <code> wp_options </code> . But should you choose not to, you really should change the names of your second and third options; "height" and "width" are entirely too generic, and almost assuredly will cause conflicts. You're passing <code> name="height" </code> and <code> name="width" </code> , respectively, but I doubt that WordPress is associating "width" and "height" as options that belong to your Plugin. So, assuming your store your options as <code> plugin_plugin-slug_options </code> , which is an array: <code> &lt;?php $plugin_options = get_option( 'plugin_plugin-slug_options' ); ?&gt; &lt;tr&gt;&lt;td&gt;Number Of Videos:&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="$plugin_options[vidNO]" value="&lt;?php echo get_option('vidNO');?&gt;" &lt;?php echo get_option('vidNO'); ?&gt; /&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Height:&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="$plugin_options[height]" value="&lt;?php echo get_option('height');?&gt;" &lt;?php echo get_option('height'); ?&gt; /&gt; &lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;Width:&lt;/td&gt;&lt;td&gt;&lt;input type="text" name="$plugin_options[width]" value="&lt;?php echo get_option('width');?&gt;" &lt;?php echo get_option('width'); ?&gt; /&gt; &lt;/td&gt;&lt;/tr&gt; </code> But you really should consider using the Settings API, at least insofar as using <code> register_setting() </code> to register your options array, and <code> settings_fields() </code> to do the heavy lifting in your settings form.
Wordpress plugin form not saving data
wordpress
Hey everyone, I can't se the image of the post (it is attached through gravity form as a post-image) with this function I see the missing image icon with the title and the working link but no thumbnail image.? It is suposed to be more or less ( authors last 2 posts in the widget area) I suspect the problem is here : <code> $output .= '&lt;img src="' . wp_attachment_is_image( $post_id ) . '" alt="" /&gt;'; </code> So please help me out :D <code> function get_related_author_posts() { global $authordata, $post; $authors_posts = get_posts( array( 'orderby' =&gt; 'rand', 'author' =&gt; $authordata-&gt;ID, 'post__not_in' =&gt; array( $post-&gt;ID ), 'posts_per_page' =&gt; 2 ) ); $output = '&lt;ul class="post_related"&gt;' . "\n"; foreach ( $authors_posts as $authors_post ) { $output .= '&lt;li&gt;&lt;a href="' . get_permalink( $authors_post-&gt;ID ) . '" title="' . apply_filters( 'the_title', $authors_post-&gt;post_title, $authors_post-&gt;ID ) . '"&gt;'; $output .= '&lt;img src="' . wp_attachment_is_image( $post_id ) . '" alt="" /&gt;'; $output .= '&lt;/a&gt;&lt;/li&gt;' . "\n"; } $output .= '&lt;/ul&gt;'; return $output; } </code>
Do I understand right that you mean featured thumbnail image for a post and not just any attached image? See <code> get_the_post_thumbnail() </code> function and your usage will be something like this: <code> $output .= get_the_post_thumbnail( $authors_post-&gt;ID ); </code>
Function to call the attachment image from post
wordpress
In the TinyMCE editor that comes with WordPress there is no button to insert image from link. I know that you can do this using the upload/insert section. But let us say that I don't want to allow users to upload images but want them to be able to insert images by linking them. If I remove the upload capabilities, the upload/insert section disappears altogether. Is there already a method to do this on WordPress?
TinyMCE Advanced allows you to add several buttons including images.
How to insert image from link in TinyMCE
wordpress
I have 1 important taxonomy that contains 2 different custom post type content. I want somehow show them in same taxonomy page with both paging. Well.. i am not sure i can do that or not. Is it possible to paging 2 different CPT in same taxonomy?
You can create two separate loops with pagination - and place them in side by side div containers - with pagination links inside each div. You would include the pagination links in each div, because you might have more of one post type then the other, and therefor more pages than the other. The columns will paginate together unless you use ajax javascript to refresh the content of the div's independently - in which case you'll have to pass the correct relative page number in your call. Without the ajax, with separate columns of post types paging in tandem, your template would look like this (untested code): <code> &lt;?php /* Template Name: Side-by-Side Paginated Custom Post Types */ global $query_string; global $wp_query; get_header(); $myquery = wp_parse_args($query_string); $myquery['tax_query'] = $wp_query-&gt;tax_query; echo '&lt;div id="container"&gt;'; // Work whether query var is page or paged if ( get_query_var('paged') ) { $paged = get_query_var('paged'); } elseif ( get_query_var('page') ) { $paged = get_query_var('page'); } else { $paged = 1; } $myquery['post_status'] = 'publish'; $myquery['paged'] = '.$paged'; // Create Page Heading, including each term from the query // Allows for advanced tax query with more than one taxonomy term, such as News and Events in the same query foreach ($wp_query-&gt;tax_query-&gt;queries as $taxterm) { if ('your_taxonomy' == $taxterm['taxonomy']) { $last_term = end( array_keys( $taxterm['terms'] ) ); // Mark the last topic echo "&lt;h1&gt;"; foreach ($taxterm['terms'] as $k =&gt; $termid) { $termobj = get_term_by( $taxterm['field'], $termid, $taxterm['taxonomy'] ); echo $termobj-&gt;name; if ( $k !== $last_term ) echo ' &amp;amp; '; } echo "&lt;/h1&gt;"; } } echo '&lt;div class="left-column"&gt;'; $myquery['post_type'] = 'your_cpt_1'; echo '&lt;h2 class="sec1 title"&gt;Custom Posts 1&lt;/h2&gt;'; // Query $myquery = new WP_query( $args ); if ( $myquery-&gt;have_posts() ) : while ( $myquery-&gt;have_posts() ) : $myquery-&gt;the_post(); get_template_part( 'content', 'your_cpt_1' ); endwhile; else : endif; echo '&lt;div class="pagination"&gt;'; echo '&lt;div class="alignleft"&gt;'; previous_posts_link('Previous'); echo '&lt;/div&gt;'; echo '&lt;div class="alignright"&gt;'; next_posts_link('Next'); echo '&lt;/div&gt;'; echo '&lt;/div&gt; &lt;!-- end pagination --&gt;'; wp_reset_postdata(); echo '&lt;/div&gt; &lt;!-- div class="left-column" --&gt;'; echo '&lt;div class="right-column"&gt;'; $myquery['post_type'] = 'your_cpt_2'; echo '&lt;h2 class="sec1 title"&gt;Custom Posts 2&lt;/h2&gt;'; // Query $myquery = new WP_query( $args ); if ( $myquery-&gt;have_posts() ) : while ( $myquery-&gt;have_posts() ) : $myquery-&gt;the_post(); get_template_part( 'content', 'your_cpt_2' ); endwhile; else : endif; echo '&lt;div class="pagination"&gt;'; echo '&lt;div class="alignleft"&gt;'; previous_posts_link('Previous'); echo '&lt;/div&gt;'; echo '&lt;div class="alignright"&gt;'; next_posts_link('Next'); echo '&lt;/div&gt;'; echo '&lt;/div&gt; &lt;!-- end pagination --&gt;'; wp_reset_postdata(); echo '&lt;/div&gt; &lt;!-- div class="right-column" --&gt;'; echo '&lt;/div&gt; &lt;!-- div id="container" --&gt;'; get_footer(); ?&gt; </code>
2 custom post type paging in 1 custom taxonomy
wordpress
I am trying to add tinymce editor in my frontend from where users can post. But no luck so far. Here is the code: PHP: <code> add_action('wp_print_scripts', 'my_enqueue_scripts'); function my_enqueue_scripts() { wp_enqueue_script( 'tiny_mce' ); if (function_exists('wp_tiny_mce')) wp_tiny_mce(); } </code> Javascript: <code> jQuery(document).ready(function(){ tinyMCE.init({ mode : "textareas", theme : "simple", /*plugins : "autolink, lists, spellchecker, style, layer, table, advhr, advimage, advlink, emotions, iespell, inlinepopups, insertdatetime, preview, media, searchreplace, print, contextmenu, paste, directionality, fullscreen, noneditable, visualchars, nonbreaking, xhtmlxtras, template",*/ editor_selector :"editor" }); }); </code> HTML: <code> &lt;textarea rows="8" cols="40" name="description" id="editor" class="required"&gt;&lt;?php echo $description;?&gt;&lt;/textarea&gt; </code> Problem: Texteditor not adding to textarea. Although the tinymce js file is loading.
Well, Thanks to wp 3.3 now we have <code> wp_editor() </code> function to do that :)
How do i include tinymce editor in frontend?
wordpress
From what I have read, I have come to understand that all WordPress plugins,(including premium ones) should be GPL licensed . If this is the case, can the installation be limited to a single domain? As far as I understand, GPL allows you to reuse the code. Doesn't it? I'm asking this because I have seen some premium plugins have single site/multi site licenses. Please correct me if this question is wrong.
GPL prohibits restricting the code in any way. You can restrict the support or non GPL parts of the plugin (images/css) to a single domain but you can't restrict the GPL code to a single domain. Q&amp;A: WORDPRESS &amp; GPL MATT MULLENWEG's response to the same question:
Single Domain/Multiple Domain installation restrictions allowed for plugins?
wordpress
Currently, permalinks are set to /%postname%/. I'd like to prefix "blog" before all standard posts. I'm using several custom post types, each with their own rewrite rules in the setup. How can I setup a custom prefix for my standard WordPress posts?
did you try defining your perm structure like: /blog/%postname%/ If each one of your custom post types has its own slug defined, this should work like you are asking.
How do I set a custom base URL for standard posts?
wordpress
On the WordPress archive template I am using a custom excerpt function that includes a reference to <code> strip_shortcodes() </code> . For some reason, shortcodes are being rendered and displayed in the archive. Example: http://arisehub.org/blog/page/2/ Scroll down to "Sing a New Song with Joshua Cunningham" Notice the script code showing up. That's a shortcode reference to JW Player , showing up rendered. Here's the code I'm using for the custom excerpt function. <code> function custom_excerpt($length, $more_text) { global $post; $text = get_the_content(); $text = strip_shortcodes( $text ); $text = apply_filters('the_content', $text); $text = str_replace(']]&gt;', ']]&gt;', $text); $text = strip_tags($text, '&lt;a&gt;, &lt;p&gt;, &lt;strong&gt;, &lt;em&gt;, &lt;b&gt;'); if(!empty($length)){ $excerpt_length = apply_filters('excerpt_length', $length); } else { $excerpt_length = apply_filters('excerpt_length', 180); } if(!empty($more_text)){ $excerpt_more = apply_filters('excerpt_more', ' ' . '&amp;hellip; &lt;br /&gt;&lt;a href="'.get_permalink($post-&gt;id).'" class="more-link"&gt;'.$more_text.'&lt;/a&gt;'); } else { $excerpt_more = apply_filters('excerpt_more', ' ' . '&amp;hellip;&lt;a href="'.get_permalink($post-&gt;id).'" class="more-link"&gt;+ more&lt;/a&gt;'); } $words = preg_split('/(&lt;a.*?a&gt;)|\n|\r|\t|\s/', $text, $excerpt_length + 1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE ); if ( count($words) &gt; $excerpt_length ) { array_pop($words); $text = implode(' ', $words); $text = $text . $excerpt_more; } else { $text = implode(' ', $words); } $output = '&lt;p&gt;'.$text.'&lt;/p&gt;'; echo $output; } </code> Any ideas?
JW Player Plugin for WordPress does not register its shortcode like all other shortcodes, so <code> strip_shortcodes() </code> will not know about it and not strip it. In the code there is a note that this is because it uses argument names with a <code> . </code> in it, and WordPress does not support this. There are probably multiple ways to solve this, but I would copy the relevant line from <code> strip_shortcodes() </code> and integrate the regex from the plugin: <code> function custom_excerpt( $length, $more_text ) { global $post; $text = get_the_content(); $text = strip_shortcodes( $text ); // Strip JW Player shortcode too $text = preg_replace( '/(.?)\[(jwplayer)\b(.*?)(?:(\/))?\](?:(.+?)\[\/\2\])?(.?)/s', '$1$6', $text ); $text = apply_filters('the_content', $text); // Continue with the rest of your function ... </code>
Cannot strip JW Player shortcode?
wordpress
I want to add some custom fields to allow a user to select items from the Media library for the custom post (in the add/edit view) Is there a way to do this?
My answer will be in the form of links. The WPAlchemy meta box class supports this: http://www.farinspace.com/wpalchemy-metabox/ + tutorial http://www.farinspace.com/wordpress-media-uploader-integration/ A tutorial on how to do it, mainly javascript: http://www.webmaster-source.com/2010/01/08/using-the-wordpress-uploader-in-your-plugin-or-theme/
How do I add media to a custom post type?
wordpress
I am fairly new to WordPress, and I would like to have a list of the most recent posts in a certain category appear in a right-hand panel (I can do this with all posts, but not specific categories) I am using the Twenty Ten theme, on wordpress.com. I have found the following code, but unsure if or where this can be added: <code> &lt;ul&gt; &lt;?php $recent = new WP_Query("cat=10&amp;showposts=5"); while($recent-&gt;have_posts()) : $recent-&gt;the_post();?&gt; &lt;li&gt;&lt;a href="&lt;?php the_permalink() ?&gt;" rel="bookmark"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; </code>
The fastest way, a plugin: http://wordpress.org/extend/plugins/category-posts/
Display most recent posts in category with Twenty Ten theme widget
wordpress
Just curious if anyone knows of a plugin or a way to add sorting for Plugin searches in the Administration of a Wordpress site. I find myself searching through all kinds of plugins, ultimately just wanting to see what has the best rating or highest number of downloads. Kind of surprised Wordpress hasn't added this feature already. Anyone know of a fix?
Good question, I have noticed it and couldn't (at the time) find a plugin that fixed it. My solution: Open the Wordpress Plugin Directory page and search there - you get a lot more options. Copy the plugin title over to your site's plugin admin page and search there - then install from there. It's quicker than downloading from the Plugin Directory and reuploading, but you have to watch out because sometimes the plugin titles don't correspond to your search string (the plugin search is kind of odd that way).
Plugin search sorting for admin section - Wordpress
wordpress
The code below is the function for pagination in my wordpress blog. Presently it outputs 7 pages and then the .. last page number. How can I reduce this number so it shows only 5 pages and then ... last page number? <code> function emm_paginate_loop($start, $max, $page = 0) { $output = ""; for ($i = $start; $i &lt;= $max; $i++) { $output .= ($page === intval($i)) ? "&lt;span class='emm-page emm-current'&gt;$i&lt;/span&gt;" : "&lt;a href='" . get_pagenum_link($i) . "' class='emm-page'&gt;$i&lt;/a&gt;"; } return $output; } </code>
I believe you're using 2 custom functions one of them is emm_paginate_loop() you're showing. But i saw that settings for that custom pagination is on function emm_paginate() and specifically "gap": 'gap' - Default is 3 (int). The minimum number of pages before a gap is replaced with ellipses (...). But that only sets a minimum number...
How to reduce the number of pages in pagination
wordpress
I need to know is it possible to somehow erase the original image uploaded via Gravity form : post image - post field?! With the situation now I receive 4 images. 1 original (can be whatever user has on his PC - up to 4 MB which clutters the server) and 3 which Wordpress creates according to specifications (thumbnail, medium, large). I would like to have the ability when user uploads the "original big image" to be deleted upon upload and be left with 3 remaining in media gallery?!. It will dramatically improve the storage on my server. Cheers!
How about this: <code> add_filter( 'wp_generate_attachment_metadata', 'delete_fullsize_image' ); function delete_fullsize_image( $metadata ) { $upload_dir = wp_upload_dir(); $full_image_path = trailingslashit( $upload_dir['basedir'] ) . $metadata['file']; $deleted = unlink( $full_image_path ); return $metadata; } </code> Not 100% sure everything will work ok without the main image, but it does the trick. You wont be able to regenerate the thumbnails / sizes as the main image is required for this. Edit: I just re-read the question, I noticed you are wanting this to only happen when people upload via a form. Must be early for me, the above code will delete any attachment uploaded. I guess all you would need to do is find someway of checking if the upload was via your gravity form. Hope it helps you anyway.
Delete the original big size image after upload and leave only 3 images crunched by media gallery
wordpress
I've placed the following code in my functions.php file <code> if(!is_home()){ echo "Not Home";} if(is_home()){ echo "Home";} </code> However, no matter what page I'm on, I get "Not Home", And I'm real sure I'm on the home page, but still get "Not Home". What am I missing?
If you just place it in <code> functions.php </code> , not in a function in <code> functions.php </code> , it will be called too early. WordPress includes <code> functions.php </code> before it parses the URL and determines whether you are actually on the homepage or not. Since WordPress 3.1 there is an extra warning (only visibile if you enable <code> WP_DEBUG </code> ) if you call these too early, to prevent these confusing situations.
is_home() returns false on the home page! When is the home page NOT the home page?
wordpress
So I enabled custom excerpts on my pages with this function. <code> add_action('init', 'page_excerpts'); function page_excerpts() { add_post_type_support( 'page', 'excerpt' ); } </code> However, When I enter a data into the excerpt field I still have the content returning in the loop instead of my newly added excerpt. <code> &lt;?php the_excerpt(); ?&gt; </code> Do I need to do anything else to force the content to be pulled from the excerpt field on pages?
Perhaps try this: <code> &lt;?php global $more; $more = false; ?&gt; &lt;?php the_content('&lt;span&gt;Continue Reading&lt;/span&gt;'); ?&gt; &lt;?php $more = true; ?&gt; </code>
How do I pull excerpts from pages?
wordpress
I'm trying to create some pretty URLs for links querying multiple taxonomies. I'm using the "Taxonomy drill-down" plugin, although the main usage is now integrated @ the core it still has some helpful function for templating :) An example URL querying multiple taxonomies ( working ) would be: domain.com/?tax1=foo&amp;tax2=bar My goal is to have links like - domain.com/tax1/foo/tax2/bar - translating to the above example tax1/2 = taxonomy name foo/bar = required term I stumbled upon Examples of WP Rewrites but i think i suck with those patterns and something like: <code> $newrules['tax1/(.*)/tax2/(.*)/'] = 'index.php?tax1=$matches[1]&amp;tax2=$matches[2]'; </code> doesn't seem to work ( that's just a portion of the whole function based on the Wordpress example ) Any ideas? :)
<code> (.*) </code> matches everything, so it will "eat up" the extra characters (it is "greedy"). If the URL is <code> /tax1/foo/tax2/bar/ </code> , the first <code> (.*) </code> will be <code> foo/tax2/bar/ </code> , so nothing is left for the second match. Instead of <code> (.*) </code> you can use the "non-greedy" version <code> (.+?) </code> . This will match as much as possible, but still keep the rest in mind. You can also use the even stricter version <code> ([^/]+) </code> : this will match everything up to the next <code> / </code> - but this will not work for nested categories, so <code> /category/fruit/banana/tag/flies/ </code> will not split up in <code> fruit/banana </code> and <code> flies </code> like you might expect. If you are going to play with the rewrite rules I recommend you to install my stackexchange-url ("Rewrite analyzer plugin"). It allows you to see the current rewrite rules and play with URLs to see which rules will match.
URL rewrite rules for multiple taxonomies query
wordpress
I would like to create a navigation menu where I will be displaying two level pages. To illustrate that: Parent 1 Parent 2 Parent 3 (current) Child 1 Child 2 Child 3 Parent 4 So I would like to display all the parent pages in my navigation container but only display children pages when the user is currently on its parent page.
This is pretty easy, as WordPress sets css classes for the parent pages. Default we hide all sublists (ul) from the menu with <code> .menu ul { display: none; } </code> Then when the parent page is selected we use the css classes that are set by WordPress to show the sublists again. <code> .menu .current_page_ancestor, .menu .current_page_parent { display: block; } </code> So all you need is this in your template Template: <code> &lt;ul class="menu"&gt; &lt;?php wp_list_pages('title_li=') ?&gt; &lt;/ul&gt; </code> and this in your css file. CSS: <code> .menu ul { display: none; } .menu .current_page_ancestor &gt; ul, .menu .current_page_parent &gt; ul { display: block; } </code>
Displaying Subpages while on Parent page?
wordpress
I'm developing a plugin that I'll install for all my clients to make WordPress slightly easier to use for them. One of the things it will change is the default TinyMCE configuration. It'll add things like <code> underline </code> and <code> justifyfull </code> to the first TinyMCE row. I know I could use other plugins like TinyMCE Advanced to alter TinyMCE for my clients, but they add a lot of unneccessary bloat which is susceptible to problems during updates. I want to make this as minimalistic as possible in order to avoid update issues. I've written this simple code that mostly works great: <code> function mo_change_mce_buttons( $initArray ) { $initArray['theme_advanced_buttons1'] = 'bold,italic,underline,strikethrough,|,bullist,numlist,blockquote,|,justifyleft, justifycenter,justifyright,justifyfull,|,link,unlink,wp_more,|,spellchecker,fullscreen,wp_adv'; return $initArray; } add_filter('tiny_mce_before_init', 'mo_change_mce_buttons'); </code> This code works great except for one huge problem. It disables any TinyMCE plugins on the TinyMCE row in question ( <code> theme_advanced_buttons1 </code> ). The Vipers Video Quicktags plugin for example, which adds a YouTube-button, is removed by using the code above. How can I modify the default first TinyMCE row using simple code in my own plugin without sacrificing the possibility for other plugins to add buttons to it too?
<code> tiny_mce_before_init </code> is a filter that gets the whole TinyMCE configuration , but there are filters that act on smaller parts of it, like <code> mce_buttons </code> for only the buttons . The advantage here is that they act on arrays, so it's easy to add or remove parts from them. This is how Vipers Video Quicktags does it too. You can change your code to the following snippet to insert the buttons at the right places and not remove buttons that other plugins have added: <code> add_filter( 'mce_buttons', 'wpse17686_mce_buttons' ); function wpse17686_mce_buttons( $old_buttons ) { $new_buttons = array(); foreach ( $old_buttons as $button ) { $new_buttons[] = $button; if ( 'italic' == $button ) { $new_buttons[] = 'underline'; } if ( 'justifyright' == $button ) { $new_buttons[] = 'justifyfull'; } } return $new_buttons; } </code>
Adding TinyMCE buttons without removing plugin buttons?
wordpress
Is it possible to include or exclude specific named widgets that are assigned to a named dynamic_sidebar call? For example, if I've registered a sidebar named "my_sidebar" and the user had placed a "Links" widget into it, I want to be able to include or exclude it based on a custom setting in my theme options panel. Is this possible? Any insights much appreciated.
<code> dynamic_sidebar() </code> calls <code> wp_get_sidebars_widgets() </code> to get all widgets per sidebar. I think filtering this output is the best way to remove a widget from an sidebar. <code> add_filter( 'sidebars_widgets', 'wpse17681_sidebars_widgets' ); function wpse17681_sidebars_widgets( $sidebars_widgets ) { if ( is_page() /* Or whatever */ ) { foreach ( $sidebars_widgets as $sidebar_id =&gt; &amp;$widgets ) { if ( 'my_sidebar' != $sidebar_id ) { continue; } foreach ( $widgets as $idx =&gt; $widget_id ) { // There might be a better way to check the widget name if ( 0 === strncmp( $widget_id, 'links-', 6 ) ) { unset( $widgets[$idx] ); } } } } return $sidebars_widgets; } </code>
Call dynamic_sidebar but include/exclude named widgets?
wordpress
I'm trying to add items to the admin bar but only for users with certain capabilities, such as <code> add_movies </code> in a plugin. The problem is that, according to stackexchange-url ("@toscho") and stackexchange-url ("@TheDeadMedic"), the plugin executes its code too early in the order of operations to use <code> current_user_can </code> . I tried using <code> if ($user-&gt;has_cap('add_movies')) </code> but get <code> Fatal error: Call to a member function has_cap() on a non-object in xxx. </code> Am I missing an obvious global or is the solution more complicated?
The check will be called too early if you just write it in your plugin file like this: <code> if ( current_user_can( 'add_movies' ) ) { add_action( 'admin_bar_menu', 'wpse17689_admin_bar_menu' ); } function wpse17689_admin_bar_menu( &amp;$wp_admin_bar ) { $wp_admin_bar-&gt;add_menu( /* ... */ ); } </code> Because it will execute when your plugins is loaded, which is very early in the startup process. What you should do is always add the action, but then in the callback for the action check for <code> current_user_can() </code> . If you can't do the action, just return without adding the menu item. <code> add_action( 'admin_bar_menu', 'wpse17689_admin_bar_menu' ); function wpse17689_admin_bar_menu( &amp;$wp_admin_bar ) { if ( ! current_user_can( 'add_movies' ) ) { return; } $wp_admin_bar-&gt;add_menu( /* ... */ ); } </code>
How to show a admin bar menu item only to users with certain capabilities?
wordpress
I'm trying to create a rather large and extensive settings page with various options of very similar type. Since there will be about 20 different fields, and the differences between most of those being simply their ID, I'd like to avoid creating a separate callback for each one. Is it possible to make a callback with a variable for the settings ID of each of these fields? That way one callback can server various settings fields of the same type. I've tried using the $args parameter for add_setitngs_feild(), but sadly, it does not work. For example: <code> add_settings_field('name', 'Field Name', array($this, 'fieldCallback'), 'SettingsGrouP', 'SettingsSection', array("settingID!")); function fieldCallback($id) { echo "&lt;input id='" . $id . "'/&gt;";//etc, etc } </code> fieldCallback si being called, but the ID of the input is blank.
The last optional <code> $args </code> argument the you can pass to add_settings_fields() </code> is passed to callback. So it seems you can use same callback just fine. Hope I am right because I just stumbled onto this two minutes ago because of discussion in chat. :) PS looked through code and it's indeed relatively recent, before ~2.9 arguments weren't passed.
Add_settings_field() parameterizing callback?
wordpress
I have noticed that when I am in my Dashboard and switching from main Dashboard to for example plugins, Twitter seems to be loading something. As I am located in China where Twitter is blocked, it always takes forever for my browser to realise that Twitter cannot be loaded, and thus before the page(s) finish loading. This screenshot is for going to the plugins page, but it happens everywhere in the Dashboard. Is this normal? And can it be blocked/removed/undone?
problem not resolved, temporary solution is to add a host entry for the twitter host to point it to localhost as offered by @Dunhamzzz and explained further by @Roman and @Jan
Browser loading content from Twitter in admin area?
wordpress
I'm developping a plugin to manage a base of users and I'd like to show them in the same type of table used in other parts of the WP admin (post lists, user lists, etc.), I'd like to have the same look and the if possible the column sorting too.
You came to this in a bad time of changes. Tables in admin are being migrated from the old and scary ways to new shiny <code> List Tables API </code> using subclasses of <code> WP_List_Table </code> . Problem is - while classes are already in and being using core code, they are currently not meant for being used otherwise. Proper API for theme/plugin usage is planned, but I think it didn't make it in 3.2 version, so 3.3 (at best). Your options are: Do custom table, reuse CSS styling from core. Long run - leave as is or recode when <code> List Table API </code> is implemented and finalized. Extend appropriate <code> WP_List_Table </code> class with your own and use that. Long run - likely watch it explode at every following WP version from here until <code> List Table API </code> is implemented and finalized. For simple things I'd prefer 1 . But for complex stuff 2 is pretty much only way to go, because custom table is very hard to get right when a lot of global variables and other joys of admin side are involved.
How to use WP default post list tables in a plugin?
wordpress
I am working on a new version our site. Today I was going to put the blog on the new version. Our current website and the successor I am building are on different servers and accessed by different domain names. So what I did was import the database the blog uses into the dev site. Then I copied all the files and put them on the dev site. On the dev site I went to /blog/wp-admin and I changed the general settings so the blog URL would use the dev domain. I made NO CHANGES on the current production website server. However the current production website's blog is now broken. When I go to blog/wp-admin on the real site, the form posts to the dev server. I am not able to log into wordpress on either the dev or production site now. I do not understand how I could break anything on the production server by making changes on a completely separate server that is unrelated to the production server. So my main goals now are to: Restore the blog on production server (undo the changes I made today) and get it working again right away. Figure out what I did wrong so I can put the blog on the production server.
If you didn't hand-change the wpurl in the dev database, what probably happened is that you entered your url, and WP made a 301 redirect to the live site. Then, without realizing it, you changed the url config in your live site. To make it work: Put this in your wp-config.php <code> define('WP_SITEURL', 'http://your-wp-url.com'); define('WP_HOME', 'http://your-wp-url.com'); </code> That should do it.
Copying wordpress to another server breaks it on original server
wordpress
I have the following code generated by wordpress for my nav1: <code> &lt;div id="nav1"&gt; &lt;ul class="menusm"&gt; &lt;li class="page_item page-item-6"&gt;&lt;a title="Inicio" href="http://localhost/road/" class="top_level"&gt;Inicio&lt;/a&gt;&lt;/li&gt; &lt;li class="page_item page-item-11"&gt;&lt;a title="Quienes Somos" href="http://localhost/road/quienes-somos" class="top_level"&gt;Quienes Somos&lt;/a&gt;&lt;/li&gt; &lt;li class="page_item page-item-13"&gt;&lt;a title="Servicios" href="http://localhost/road/servicios" class="top_level"&gt;Servicios&lt;/a&gt; &lt;ul class="children" style="display: none;"&gt; &lt;li class="page_item page-item-25"&gt;&lt;a title="Inteligencia" href="http://localhost/road/servicios/inteligencia" class=""&gt;Inteligencia&lt;/a&gt;&lt;/li&gt; &lt;li class="page_item page-item-27"&gt;&lt;a title="Personal, Equipos, Armamentos" href="http://localhost/road/servicios/personal-equipos-armamentos" class=""&gt;Personal, Equipos, Armamentos&lt;/a&gt;&lt;/li&gt; &lt;li class="page_item page-item-22"&gt;&lt;a title="Seguridad Operativa" href="http://localhost/road/servicios/seguridad-operativa" class=""&gt;Seguridad Operativa&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;li class="page_item page-item-17"&gt;&lt;a title="Contacto" href="http://localhost/road/contacto" class="top_level"&gt;Contacto&lt;/a&gt;&lt;/li&gt; &lt;li class="page_item page-item-37 current_page_item"&gt;&lt;a title="Cotice su stand en ferias" href="http://localhost/road/pedir-cotizacion" class="top_level"&gt;Cotice su stand en ferias&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt;&lt;div class="clr"&gt;&lt;/div&gt; </code> And I would like the last <code> &lt;li&gt; </code> tag under the title of "Cotice su stand en ferias" to use a button instead of text as the rest of the <code> &lt;li&gt; </code> 's. Is there a way to accomplish this without having to completely remove that item and placing a button next to the <code> #nav1 </code> ? Thanks for the help in advance. Edit: got it. <code> #nav1 ul li:last-child {background: url(images/cotizacion-icono.jpg) no-repeat scroll;} </code>
jQuery Solution if you're using jQuery you can use: <code> var $li = jQuery('ul &gt; li:last-child','#nav1'); </code> to select your last menu child. Then after you select it you can chain it with another function: <code> $li.wrapInner('&lt;input type="button" value="My Button!"&gt;'); </code> Then all together: <code> jQuery(document).ready(function() { // Cache your selection var $li = jQuery('ul &gt; li:last-child','#nav1'); // Replace it with your button $li.wrapInner('&lt;input type="button" value="My Button!"&gt;'); }); </code> Pure CSS Solution Setup your dropdown navigation: PHP in the template: <code> &lt;?php $args = array( 'sort_column' =&gt; 'menu_order, post_title', 'menu_class' =&gt; 'menu', 'include' =&gt; '', 'exclude' =&gt; '', 'echo' =&gt; true, 'show_home' =&gt; false, 'link_before' =&gt; '&lt;span&gt;', // Wrap your span here 'link_after' =&gt; '&lt;/span&gt;' ); // close it with a span too ?&gt; </code>
Page menu with one image link instead of page title?
wordpress
If anyone can help me I would be gratefull! I got a gravity form with the post_type fields including the submit image when submited it displays the: title content image tags So my question is: When I go to single.php I posted a code: <code> get_related_author_posts(); </code> which calls the authors last two posts in function.php. Please take a look at the code, that contains/illustrates the problem: http://pastie.org/1926079 I need a little help from my friends the wordpress gurus :) Thank You all in advance. I'm still learning the more advanced functions but this is where I'm stuck:)
I would use <code> wp_get_attachment_image() </code> ( Codex ref ), which returns a fully-formed HTML IMG tag: <code> &lt;?php wp_get_attachment_image( $attachment_id, $size, $icon ); ?&gt; </code> I assume you already know how to get the attachment image ID? The default image size is <code> thumbnail </code> , but you can pass any standard image size (e.g. <code> full </code> , <code> large </code> , <code> medium </code> ), or any custom image size added via <code> add_image_size() </code> .
How to: Retrieve an attachment image from post and output it
wordpress
I want my to reach my website's main page when entering an url like: http://example.com/blog However, I can't seem to get it to work with a typical rewrite rule: <code> RewriteRule ^/blog$ / </code> I'm always taken to my site's 404 page. Works fine if I specify a specific file (e.g. "/foo.html") instead of "/", but "/index.php" doesnt't work. How can I make this work?
The redirect has to be a 301, not an internal request. Otherwise WordPress will search dor a page named blog . And you don’t need mod_rewrite. <code> # Apache 1.3 needs a complete URL RedirectMatch Permanent ^/blog$ http://example.com/ # Apache 2.x needs just the path RedirectMatch Permanent ^/blog$ / </code>
How to redirect a virtual page (e.g. /blog) to the home page?
wordpress
I don't think I ever had practical need to create folders/files in WP before, but for a plugin I need cache (for resized images) folder in <code> wp-content/uploads </code> . Which raises the question - do I really need to go through all the process with <code> Filesystem API </code> (including messily asking for FTP credentials when needed), or <code> wp_mkdir_p() </code> is good enough for this?
<code> wp-content/uploads/ </code> should be writable for the server (otherwise it would be impossible to upload a file, no?). If you are going to create something under this directory, it is safe to use <code> wp_mkdir_p() </code> . I would only use <code> WP_Filesystem </code> if there is a chance the server does not have permissions to write to the location, like in <code> wp-content/plugins/ </code> , which does not have to be writable for the server (at least I think it doesn't have to be?). Sidenote: The File Permissions page of the Codex also talks about a <code> wp-content/cache/ </code> directory. Would this be a "more standard" location for cache files?
Creating directory in uploads - wp_mkdir_p() or WP_Filesystem?
wordpress