question
stringlengths
0
34.8k
answer
stringlengths
0
28.3k
title
stringlengths
7
150
forum_tag
stringclasses
12 values
I have uploaded some files (images) which I'd like to link in my own site as well as other places, but usually I try to host a different resolution of the same image to show up on other sites. My problem with wordpress right now is that if I upload the file to Wordpress' upload directory through FTP, I don't see the file show up in my media (in WP-admin). I can get a link from my ftp client (cyberDuck) but it doesn't actually link me to a working link, also the link is something like this: <code> http://ftp.mydomain.com/really-link-file-name-with-20%-and-at-the-end-its.jpg </code> So I assume it works like that b/c it contains jpg at the end but it doesn't work and takes me to a 404 page. Any ideas of how I can go about uploading through an FTP client and get those files to show up on wordpress and also link correctly?
If I upload the file to Wordpress' upload directory through FTP, I don't see the file show up in my media (in WP-admin) Try to avoid directly uploading via FTP. WordPress doesn't scan your uploads folder for new images. Instead, use the built-in media uploader within WordPress to upload images. WordPress will automatically place them in the correct folder, create downsized versions you can use in a quick gallery or client sales page, and store the image's meta information in the WordPress database. The Media Gallery pulls its information from the WordPress database, so to see your uploaded images here, this is the only way to do it! I can get a link from my ftp client (cyberDuck) but it doesn't actually link me to a working link Your client is giving you an FTP link. If you use an FTP link in a web browser like Internet Explorer (i.e. ) your browser will act like an FTP client and try to download the image rather than displaying in in the browser. What you need is an actual HTTP link, which you can get from WordPress if you uploaded through the Media Gallery. If you uploaded directly via FTP, your link would still be something like http://www.mydomain.com/wp-content/uploads/2010/11/something-something.jpg if you uploaded to the <code> /wp-content/uploads/2010/11/ </code> directory. If you put it somewhere else, change the link accordingly. To Review The correct way to add images to WordPress and get the links is through the Media Gallery: Log in to WordPress Go to Media &raquo; Add New Select your image and upload it to WordPress Set meta data as appropriate (Title, Caption, Alt Text, Description) If necessary, you can Edit the image as well (rotate, crop, scale) Highlight the File URL and copy-paste it somewhere where you'll remember it. This is the URL to the full-size image that you can link to from other places.
How do I link directly to uploaded files?
wordpress
I have been having an issue with the non-flash version of the NextGen Slideshow on my website. The slideshow seems to initially load the first slide about 5px below the desired position. The slide then moves up about a second or 2 later into the correct position. I have tried putting the slideshow in other widget areas and all result in the same positioning error. The page in question in here: www.ukjiayuan.com So far have been unable to get any support, but would really appreciate it if anyone can reccomend a solution. Many Thanks
Someone has just answered the question for me on the wordpress forum. It turns out that there was 5px of padding in the gallerys css file (line 301) that I hadn't found: .ngg-widget, .ngg-widget-slideshow { margin:0; overflow:hidden; padding:5px 0 0 0; &lt;--- change this to 0 0 0 0 or just 0 text-align:left I didn't add this, so it seems like the css have been like this in the first place. So if anyone else has this problem in the future just change that 5 to a 0.
NextGen Gallery Slideshow Positioning Issue
wordpress
In the text editor, where you can set headings and other settings, is it possible to add your own styles for clients to use? and even remove the unnecessary ones?
The "classic" TinyMCE editor has two dropdowns: <code> formatselect </code> for paragraph styles and <code> styleselect </code> for character styles - which can also contain paragraph styles, to make it more confusing. The configuration in WordPress by default only shows the format dropdown. If you apply a custom stylesheet to the editor, TinyMCE can use it to pick up the classnames and add them to the style dropdown - but this did not work every time for me. Since 3.0 you can call <code> add_editor_style() </code> in your <code> functions.php </code> to add a stylesheet to the editor. By default it's <code> editor-style.css </code> in your theme directory. Before 3.0 you have to hook into the <code> mce_css </code> filter to add the URL to your editor stylesheet. This will end up in the <code> content_css </code> TinyMCE configuration value . To add the style dropdown, the <code> styleselect </code> option must appear in one of the button bar configuration arrays ( <code> theme_advanced_buttons[1-4] </code> in TinyMCE, filtered by <code> mce_buttons_[1-4] </code> in WordPress). The list of block formats is controlled by the <code> theme_advanced_blockformats </code> option of TinyMCE , which you can add to the control array in the <code> tiny_mce_before_init </code> filter. If you want to customize the names of the style dropdown (not just your CSS class names), look at the <code> theme_advanced_styles </code> option . You can also use the more advanced <code> style_formats </code> option which gives you more flexibility to define the styles. The relevant PHP code with all the hooks and default configuration is in <code> wp-admin/includes/post.php </code> , in function <code> wp_tiny_mce() </code> . All together, your setup could look like this: <code> add_action( 'after_setup_theme', 'wpse3882_after_setup_theme' ); function wpse3882_after_setup_theme() { add_editor_style(); } add_filter('mce_buttons_2', 'wpse3882_mce_buttons_2'); function wpse3882_mce_buttons_2($buttons) { array_unshift($buttons, 'styleselect'); return $buttons; } add_filter('tiny_mce_before_init', 'wpse3882_tiny_mce_before_init'); function wpse3882_tiny_mce_before_init($settings) { $settings['theme_advanced_blockformats'] = 'p,h1,h2,h3,h4'; // From http://tinymce.moxiecode.com/examples/example_24.php $style_formats = array( array('title' =&gt; 'Bold text', 'inline' =&gt; 'b'), array('title' =&gt; 'Red text', 'inline' =&gt; 'span', 'styles' =&gt; array('color' =&gt; '#ff0000')), array('title' =&gt; 'Red header', 'block' =&gt; 'h1', 'styles' =&gt; array('color' =&gt; '#ff0000')), array('title' =&gt; 'Example 1', 'inline' =&gt; 'span', 'classes' =&gt; 'example1'), array('title' =&gt; 'Example 2', 'inline' =&gt; 'span', 'classes' =&gt; 'example2'), array('title' =&gt; 'Table styles'), array('title' =&gt; 'Table row 1', 'selector' =&gt; 'tr', 'classes' =&gt; 'tablerow1'), ); // Before 3.1 you needed a special trick to send this array to the configuration. // See this post history for previous versions. $settings['style_formats'] = json_encode( $style_formats ); return $settings; } </code>
can I add a custom format to the format option in the text panel?
wordpress
just want to change a little bit author email notify message(wp_notify_postauthor - pluggable.php),and I'm applying filters on comment_notification_text <code> function myfunction(){ return "&lt;div class='left_side'&gt;"..$comment..$post.."&lt;/div&gt;" } add_filter('comment_notification_text', 'myfunction'); </code> How to access data $comment,$post,... in myfunction ?
$comment_id can be passed as second parameter to your function. Modify you add_filter: <code> add_filter('comment_notification_text', 'myfunction', 10, 2); </code> Then get $comment and $post from $comment_id: <code> function myfunction( $notify_message, $comment_id ) { $comment = get_comment( $comment_id ); $post = get_post($comment-&gt;comment_post_ID); </code>
Wordpress change author email notify message?
wordpress
In the code below (from my functions.php), I'm attempting to create an array of items from the wp_postmeta table where the meta_key is "_wp_attached_file". I'm getting an error: Fatal error: Call to a member function query() on a non-object What's wrong with the query? <code> $excludeImages = array(); $excludeImages = $wpdb-&gt;query("SELECT meta_value FROM $wpdb-&gt;postmeta WHERE meta_key = '_wp_attached_file'"); array_push($excludeImages); </code>
Hi @Scott B: Did you remember to include a <code> global $wpdb; </code> in your code, like so? <code> global $wpdb; $excludeImages = array(); $excludeImages = $wpdb-&gt;query("SELECT meta_value FROM $wpdb-&gt;postmeta WHERE meta_key = '_wp_attached_file'"); array_push($excludeImages); </code>
Fatal error: Call to a member function query() on a non-object
wordpress
When i try to access my domain mapping page it asks me to move the line define('sunrise', 'on') above the last require_once line in the wp-config file. It is already above this line. I tried moving it higher and even to the top of the file(below the opening I recognizes if i remove the line alltogether (asks me to uncomment the line or add it if it is missing) so I know It is not looking at some other file. What could cause this behavior? http://pastebin.com/wTWhxPjj
Apparantly this happens with the newer version of domain mapping because sunrise.php itself needs to be updated. To solve it I: Copy the new sunrise.php file from wp-content/plugins/wordpress-mu-domain-mapping/sunrise.php to wp-content/sunrise.php and you'll be fine. And it works now.
domain mapping confused about sunrise
wordpress
I see that if I turn off "An administrator must always approve the comment" and "Comment author must have a previously approved comment" I get no notifications of new comments on my site. Can I somehow make it send the notification even though approvals are unchecked in dashboard under "discussion settings"? And what would be a good way to send this notification to all users registered on this website, and not only to admin? I tried WP Comment Notifier For All (Wordpress Plugin) . but it didn't work... thank you
mmm, well Comments Notifier (Wordpress Plugin) did the trick
Send email on new comment when no admin approval needed?
wordpress
I've got code in my functions.php which parses the WP uploads folder and lists all images it finds there. Is it possible to place a filter here that would exclude any image that is already "attached" to a post? eg: "List all images in folder "uploads" where image is not found in (attached images)"
Under Media / Edit, there's a means to list them, so I suggest you reuse the existing API. Else, a general method, which works anywhere, is to run a db query with a left join: <code> select ID from foo left join bar on whatever where condition and bar.ID is null; </code>
How to list all images in uploads directory except those that are attached to any post
wordpress
Is there a good WordPress book intended for graphic designers? I've started working with a friend in an arrangement where he designs a site and I build it in WordPress. This works great since I have the design sense of a blind monkey. He would like to learn more about WordPress and how best to design for it. I'm familiar with several good WordPress books, but most of them are intended for designer/developers. I'm looking for something that will serve as a guideline, offering suggestions for design conventions that are well suited to WordPress. Are there any such books? If there's not a book specifically aimed at designers, which other book would you suggest?
Some said this rockable book is awesome, though I don't buy it myself. I'm backend wordpress developer not front end, so I guess this book is not for me.
WordPress book for graphic designers?
wordpress
In my functions.php, I have a need to list all images in the uploads folder which are not currently attached to a post in the WP database. It appears that every time an image is uploaded to the WP uploads folder (via FTP or via Media Manager), a records gets inserted in the WP database, right? How can I obtain a list of all images that are not currently attached to any post?
This should work: <code> $args = array( 'post_type' =&gt; 'attachment', 'numberposts' =&gt; -1, 'post_status' =&gt; null, 'post_parent' =&gt; 0 ); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $post) { setup_postdata($post); the_attachment_link($post-&gt;ID); } } </code>
Script to get a list of all images that are detached?
wordpress
I want to create a loop where 2 or 3 items from my blogroll are spliced in like this: <code> &lt;loop&gt; &lt;post1&gt; &lt;post2&gt; &lt;blogroll1&gt; &lt;post3&gt; &lt;blogroll3&gt; &lt;/loop&gt; </code> I'll be using images and excerpts for the loop, and the goal is to get the <code> wp_links </code> links to display EXACTLY like the <code> wp_posts </code> , so if I can actually splice in the links to the <code> $post </code> variable somehow and loop over them AS IF they were posts, that would be great. Getting the posts via <code> get_bookmarks </code> is easy, but how would I fake WP into thinking they're <code> $posts </code> and how would I splice them into the <code> $post </code> object?
Thanks to everyone. Here is the solution that I ultimately ended up with. Rather than messing around in the loop itself, I chose to hook into <code> the_post </code> with a function that recreates the markup of the loop using data from <code> $links </code> . <code> &lt;?php global $links; global $links_count; $links = get_bookmarks("limit=5"); function dg_archive_insert_links(){ global $post; if (!is_singular()){ add_action('the_post', 'dg_insert_links'); } } add_action('wp', 'dg_archive_insert_links'); function dg_insert_links(){ global $wp_query; global $links_count; global $links; if ( ($wp_query-&gt;current_post % 3) == 0 &amp;&amp; ($wp_query-&gt;current_post &gt; 0) &amp;&amp; $links[$links_count]-&gt;link_url): ?&gt; &lt;div class="post type-post hentry"&gt; &lt;h2&gt;&lt;a href="&lt;?php echo $links[$links_count]-&gt;link_url; ?&gt;" rel="bookmark" title='Click to read: "&lt;?php echo $links[$links_count]-&gt;link_name; ?&gt;"'&gt;&lt;?php echo $links[$links_count]-&gt;link_name; ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;?php if ($links[$links_count]-&gt;link_description): ?&gt;&lt;div class="entry-summary"&gt;&lt;?php echo $links[$links_count]-&gt;link_description; ?&gt;&lt;/div&gt;&lt;?php endif; ?&gt; &lt;?php if ($links[$links_count]-&gt;link_image &amp;&amp; $links[$links_count]-&gt;link_description): ?&gt; &lt;a href="&lt;?php echo $links[$links_count]-&gt;link_url; ?&gt;" rel="bookmark" title="&lt;?php echo $links[$links_count]-&gt;link_description; ?&gt;" class="post_thumbnail" &gt;&lt;img src="&lt;?php echo $links[$links_count]-&gt;link_image; ?&gt;" width="150px" alt="&lt;?php echo $links[$links_count]-&gt;link_description; ?&gt;" /&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;?php $links_count++; endif; } </code> There's no need to create a new var to count, since it already exists at <code> $wp_query-&gt;current_post </code>
How to splice in wp_links links into the loop?
wordpress
I'm writing a plugin that creates and handles a simple form. This has been my approach sofar, but it's turned out to have some major flaws: 1) On plugin activation, create a blank page for the form at mysite.com/form, and another blank page to process the form at mysite.com/processform. (They need to be separate pages with distinct URLs so that submissions can be tracked via google analytics. Otherwise, I'd just do all this via AJAX. I know, I know... not my decision.) 2) On the "wp" action, check to see what page we're on. 2a) If it's my form page, add a "the_content" filter to render the form (it needs some dynamic hidden elements like a nonce, which is why I didn't just include the form markup when I created the form page originally). 2b) If it's my processform page, add a "the_content" filter to process the POST and render any feedback. The major problem is with my POST handling. I'm hooking it to the "the_content" filter (because I need it to supply feedback), but this filter is sometimes run multiple times during a page load, causing the POST to be handled multiple times. I've included what I have below, but I can't help thinking I'm completely on the wrong track with my approach. How would you create and handle a form with your plugin if you needed it to hit a success URL (ie. not via AJAX)? My code: <code> &lt;?php // On activation, create the blank pages function my_form_install() { // CREATE THE FORM PAGE $page_markup = ''; $arr_page_options = array( 'post_status' =&gt; 'publish', 'post_type' =&gt; 'page', 'post_author' =&gt; 1, 'post_title' =&gt; 'Form', 'post_content' =&gt; $page_markup, 'comment_status' =&gt; 'closed' ); // CREATE THE FORM PROCESSING/SUCCESS PAGE $success_page_markup = ''; $arr_success_page_options = array( 'post_status' =&gt; 'publish', 'post_type' =&gt; 'page', 'post_author' =&gt; 1, 'post_title' =&gt; 'Form Process', 'post_content' =&gt; $success_page_markup, 'comment_status' =&gt; 'closed' ); } register_activation_hook(__FILE__,'my_form_install'); // On the wp action, check to see if this is one of our pages. If so, add our filters. function check_current_page($obj_wp) { if(isset($obj_wp-&gt;query_vars["pagename"])) { $page_name = $obj_wp-&gt;query_vars["pagename"]; switch($page_name) { case "form": add_filter('the_content', 'my_render_form'); break; case "form-process": add_filter('the_content', 'my_process_form'); break; } } } add_action('wp', 'check_current_page'); // Function to render the form function my_render_form($page_markup) { $page_markup .= '&lt;form method="post" action="/form-process"&gt; &lt;input type="text" name="some_input_field" /&gt; &lt;input type="submit" value="submit" /&gt; &lt;/form&gt;'; return $page_markup; } // Function to process the form function my_process_form($page_markup) { if($_POST) { // Do the form processing. This would involve many possible returns, // but I've just included one to simplify thigns. $page_markup .= 'Your form has been processed.'; } return $page_markup; } ?&gt; </code>
That's just a quick feedback: Use a shortcode to insert your form into content. Those are quite flexible. And for the processed form's need to have another URL you can add a rewrite endpoint like /form/processed/ you can check after submission then. That's probably more modular. In the end that prevents you to deal with the <code> the_content </code> filter as you can deal with anything within the shortcode callback. It's a rough suggestion only, but probably does the job for you.
Best Practices for Creating and Handling Forms with Plugins?
wordpress
I asked this before over at the WordPress forums some time ago, before WP3 with MU was released and I think it's relevant that I ask it again, here instead, cause of WP3. Basically I want to have my personal website and blog both powered by WordPress, the website should be at www.domain.com (or domain.com) and the blog at blog.domain.com. My first idea is to use 2 WP installations with the same exact theme sharing the same database. This would easily allow me to share content between the two. Like displaying the latest blog posts in the front page of the website, for instance. It would also allow me to easily maintain different content for each site with appropriate links for each page. What I meant is, a blog post should be accessed like <code> blog.domain.com/article/blog-post-title </code> and not <code> www.domain.com/article/blog-post-title </code> ; the same way, a main site page should be accessed like <code> www.domain.com/about-me </code> and not <code> blog.domain.com/about-me </code> . But two installations come with a few problems too... Double the work for maintaining WP updated to the latest version along with plugins. In case I need user registration for comments, two would be needed and I don't think the users will like that. I'm sure there are more problems, but this is what I can think of right now. So, does WP3 come with any feature, like MU, that could help me achieve what I want or my best and easiest bet is to go the double installation route?
You would just need to use the multisite functionality now in WordPress, see http://codex.wordpress.org/Create_A_Network . Setup the site to use the subdomain install. You would then setup the main blog to be your site, ignoring the posts section for that site. Then setup a new site within the Super Admin menu and set the subdomain for the new site to be blog.yoursite.com. You can then write blog posts from this new site while keeping the site navigation in the root install.
One WordPress install for main site at domain.com and blog at blog.domain.com?
wordpress
I have seen many professional wordpress themes for sale that have shortcodes built in with which you could easily make posts like this: <code> [alert_box]This is an alert box which based on this short-code automatically switches the CSS so it is easier than messing with classes every time[/alert_box] </code> How can I do this? I know that it requires you to add something to the functions.php, though I haven't been able to figure out how. Thank you, any help is appreciated.
See the Shortcode API article on the Codex for a tutorial and my Shortcode Plugin for some examples. A very basic example for the <code> functions.php </code> : <code> /** * Shortcode for bloginfo() * * Usage: [bloginfo key="template_url"] * * @see http://codex.wordpress.org/Template_Tags/get_bloginfo * @source http://blue-anvil.com/archives/8-fun-useful-shortcode-functions-for-wordpress * @param array $atts * @return string */ function bloginfo_shortcode($atts) { extract( shortcode_atts( array( 'key' =&gt; 'name' ), $atts ) ); return get_bloginfo( $key ); } add_shortcode( 'bloginfo', 'bloginfo_shortcode' ); </code>
How do I create shortcodes for my wordpress themes?
wordpress
I'd like to add custom fields in my custom post type to the RSS feed for that post type located at http://example.com/feed/?post_type=my_custom_post_type I've seen info on doing this for the regular feed but nothing for how to rewrite the custom post type feed. I'll need to add 10 - 15 items to the feed (1st act, 2nd act, 3rd act, price, purchase link...)
<code> function add_custom_fields_to_rss() { if(get_post_type() == 'my_custom_post_type' &amp;&amp; $my_meta_value = get_post_meta(get_the_ID(), 'my_meta_key', true)) { ?&gt; &lt;my_meta_value&gt;&lt;?php echo $my_meta_value ?&gt;&lt;/my_meta_value&gt; &lt;?php } } add_action('rss2_item', 'add_custom_fields_to_rss'); </code> You should be able to substitute and any other meta values you need to add to the feed.
Add Custom Fields to Custom Post Type RSS
wordpress
trying to call <code> unregister_setting('general','users_can_register'); </code> so as to removed the option for allowing or dissallowing user registration (it is required in the theme, so it is set programatically) but it is returning <code> Call to undefined function unregister_setting()... </code>
That function is only available from the wp-admin section of the site. The file that contains it is only loaded as part of the wp-admin. You need to wrap it in a hook function: <code> function unregister_users_can_register_setting() { unregister_setting('general', 'users_can_register'); } add_action('init', 'unregister_users_can_register_setting'); </code>
why is unregister_setting() undefined?
wordpress
I was wondering this, too. I tried and spent quite a few hours trying, but I was finally able to proceed. I discovered a few things that won't be obvious to most people along the way, so I'm posting some steps here. You should be able to have this set up on a test server for a test yourself in no time. If anyone has found an alternate way to do it, please let me know. First, I had wanted all of my bookmarks to be organized somewhat, and though there are some tagging extensions for firefox, a lot of them seemed too bulky. In retrospect, I could have tried some of them first. I chose to use <code> delicious.com </code> (formerly <code> del.icio.us </code> ) to tag my bookmarks for me. It seemed the simplest way to go about it, and most of the 1,500 bookmarks I had were known to that site, so tags were available. You will be able to use the firefox delicious extension, or import directly to their website. They have an API, and hidden inside it is this URL <code> http:// username:password@api.del.icio.us/v1/posts/all </code> which should get you to having your bookmarks, now with tags, as an xml file. Next, you'll use the script from here http://memografia.com/wordpress/delicious-to-wordpress-importer/ to import it as a blog. But you can't put this script in your plugins directory and make it work! WordPress 3.0 changed the way they do the importers, BUT they left in some legacy support (though this isn't really documented anywhere.) Simply make folder named 'input' in the wp-admin folder and drop the delicious.php file in there. (This works with any importer script that uses the register_importer() function.) Now when you go to your dashboard and look under Tools> Import you'll see that Delicious is an option. You can import the bookmark tags as categories or tags and it'll make a post for each bookmark. If anyone tries this out I'd love advice on what to do next. I reseached how to do this so I could get a handle on my bookmarks and comment on the ones that were most useful. I can do that, but if anyone knows of any plugins that would grab excerpts to flesh things out, please let me know. It is rather neat to have an archive of your bookmarks that can easily be sorted by time.
To be ON TOPIC on the QUESTION (firefox) i dont think the approach to use delicious as intermediate step is preferred because: you lose the hierarhical taxonomy applied in firefox (they way you structured things) you lose the favicons as gathered in firefox you lose the information added by dividers between links you lose information on the order of directories and urls applied in firefox it is not compatible with other sources of bookmarks e.g. other browsers and e.g. a directory of urls Therefore my approach is to a) export firefox to a "BOOKMARK" directory structure with each bookmark saved as URL. b) this bookmark directory is the actual heart and can be filled from other browsers, holds the hierarchical information and inside the .url files additonal meta information can be placed. (At this stage I dropped the divider export in my current code) From WordPress you can traverse through the directory structure an place it in WP. What you will notice is that the links as currently in WordPress also lose the applied directory taxonomy (e.g. no hierarchical categories) and have no good meta table therefore I have chosen to make a side table for my link storage to retain this information (see other answer for steps after that). The following might be the thing needed if you want to focus on exporting firefox first. once again: traversing through a physical directory and then reading this in e.g. a database table (wplinks) is out-of-the-box: <code> require_once("class-EdlSqliteDb.php"); require_once("class-EdlUtil.php"); class EdlFirefox { const BOOKMARKTYPE_URL = 1; const BOOKMARKTYPE_DIRECTORY = 2; const BOOKMARKTYPE_DIVIDER = 3; const FMODE = 0777; const DIVIDER = '--------------'; var $use_cache = true; var $dbh; public function __construct($DbLocation, $ffRoot, $exportLocationBookmarks) { $this-&gt;mDbLocation = $DbLocation; $this-&gt;mRootTitle = $ffRoot; $this-&gt;mExportLocation = $exportLocationBookmarks; // database settings $this-&gt;dbh = new EdlSqliteDb($DbLocation); $this-&gt;dbh-&gt;addQ(1,"SELECT id FROM moz_bookmarks WHERE title=?"); $this-&gt;dbh-&gt;addQ(2,"SELECT id, title, type, fk FROM moz_bookmarks WHERE parent=? ORDER BY position"); $this-&gt;dbh-&gt;addQ(3,"SELECT content FROM moz_items_annos WHERE item_id=?"); $this-&gt;dbh-&gt;addQ(4,"SELECT url,favicon_id FROM moz_places WHERE id=?"); $this-&gt;dbh-&gt;addQ(5,"SELECT data, mime_type FROM moz_favicons WHERE id=?"); // parse the content $this-&gt;ParseTree(); } /* * check the ff database for the the root folder folders * */ function ParseTree() { $row = $this-&gt;dbh-&gt;DbExecutePrepared(1, Array($this-&gt;mRootTitle), 'row'); if (USE_FIREFOX_FOLDER) { $this-&gt;ParsePagesPerTree($row[0], $this-&gt;mExportLocation . '/'. FIREFOX_FOLDER . '/'); } else { $this-&gt;ParsePagesPerTree($row[0], $this-&gt;mExportLocation . '/'); } return; } /* * if a bookmark is a url then write it as a file * */ function processFFUrl($moz_bookmarks_id, $moz_bookmarks_fk, $moz_bookmarks_title, $strRootFolder) { // (1.1) Get from the annotations the description of the url $moz_items_annos_row = $this-&gt;dbh-&gt;DbExecutePrepared(3, Array($moz_bookmarks_id), 'row'); $moz_items_annos_description = $moz_items_annos_row[0]; // (1.2) get the url and favicon_id from moz_places if ($moz_places_recordset = $this-&gt;dbh-&gt;DbExecutePrepared(4, Array($moz_bookmarks_fk), 'recordset')) { foreach ($moz_places_recordset as $moz_places_row) { $moz_places_url = $moz_places_row[0]; $moz_places_favicon_id = $moz_places_row[1]; } } $this-&gt;getFaviconIcon($moz_places_favicon_id, $moz_places_url); // (1.3) create the file $link_url_string = "[InternetShortcut]\n"; $link_url_string .= 'URL=' . $moz_places_url . "\n"; $link_url_string .= 'description=' . $moz_items_annos_description . "\n"; if (!is_file($strRootFolder . '/'. $moz_bookmarks_title . '.url')) { $filename = $strRootFolder . '/'. $moz_bookmarks_title . '.url'; $fp = fopen($filename, 'w'); fwrite($fp, $link_url_string); fclose($fp); } } /* * for each logical folder create a physical folder * */ function parsePagesPerTree($intRootId, $strRootFolder) { if ($moz_bookmarks_recordset = $this-&gt;dbh-&gt;DbExecutePrepared(2, Array($intRootId), 'recordset')) { foreach ($moz_bookmarks_recordset as $moz_bookmarks_row) { $moz_bookmarks_id = $moz_bookmarks_row[0]; $moz_bookmarks_title = EdlUtil::filename_safe($moz_bookmarks_row[1]); $moz_bookmarks_type = $moz_bookmarks_row[2]; $moz_bookmarks_fk = $moz_bookmarks_row[3]; $moz_bookmarks_url = ''; $moz_bookmarks_favicon_id = ''; // A bookmark can be one of three things: process (1) urls, (2) directories and (3) dividers if ($moz_bookmarks_type==self::BOOKMARKTYPE_URL) { $this-&gt;processFFUrl($moz_bookmarks_id, $moz_bookmarks_fk, $moz_bookmarks_title, $strRootFolder); } elseif ($moz_bookmarks_type==self::BOOKMARKTYPE_DIRECTORY) { $dir = $strRootFolder . '/'. $moz_bookmarks_title . '/'; if (!file_exists($dir)) { if (!mkdir($dir, 0777, true)) { die('Failed to create folders...'); } } $this-&gt;parsePagesPerTree($moz_bookmarks_id, $strRootFolder . '/'. $moz_bookmarks_title); } elseif ($moz_bookmarks_type==self::BOOKMARKTYPE_DIVIDER) { // todo } } } return; } // function getFaviconIcon($moz_bookmarks_favicon_id, $moz_bookmarks_url) { $icon_data = ''; $moz_bookmarks_favicon = ''; if ($moz_bookmarks_favicon_id) { if ($moz_favicons_recordset = $this-&gt;dbh-&gt;DbExecutePrepared(5, Array($moz_bookmarks_favicon_id), 'recordset')) { foreach ($moz_favicons_recordset as $moz_favicons_row) { $icon_data = $moz_favicons_row[0]; $icon_mime_type = $moz_favicons_row[1]; // the following array is also defined in the google icon checker! $icon_type = array( 'image/png' =&gt; 'a.png', 'image/gif' =&gt; 'a.gif', 'image/x-icon' =&gt; 'a.ico', 'image/jpeg' =&gt; 'a.jpg', 'image/bmp' =&gt; 'a.bmp'); $moz_bookmarks_favicon = $icon_type[$icon_mime_type]; // TODO reimplement echo 'warning: you should add:' . $icon_mime_type; //if ('http://apps.facebook.com/frontierville/' == $moz_bookmarks_url) //{ // echo $moz_bookmarks_favicon_id . " - " . $icon_mime_type . " - " . // $moz_bookmarks_favicon; //} } } } // if $moz_bookmarks_favicon = empty then provide weird name if ($moz_bookmarks_favicon) { $populair_cache = new EdlCache($moz_bookmarks_url, $moz_bookmarks_favicon); $obj = $populair_cache-&gt;CheckCacheData($icon_data, FILECACHE_FIREFOX, false); } // we dont want to return the data it only needs to be update return; } } </code> I hope I can give you clues to take this a step further. 1) What I wanted is an easier way to manage my bookmarks and enrich it with information that is already out there. 2) the different systems out there like Alexa, Delcious, StumbleUpon etc... not all give the information on a url level e.g. Alexa gives information on a higher level in the domain structure e.g. abc.def.com : you need def.com for the ranking or abc.def.com/whatever/rtc.php : for this you e.g. need def.com/user (like youtube). So you need both the domain structure and the relative url structure and have each single node of every possible url (both domain and relative) as an entry in the database to be able later to represent this and enrich this and you need the relations between each part in the url to be able to represent it. I have written a class that loads in the official TLD structure and used this as root items in my database. So .uk gets the id 1 and .co.uk get a parent id 1. I used both the Mozilla list and other: source is the Mozilla Public Suffix List: http://publicsuffix.org/ but that is a bit outdated so you need to add to it Now that I have the official TLD's in there I have class that loads in the Alexa top 1.000.000 sites. This will link in the same way. Many of these are a sort of unofficial top level TLD's. Since e.g. "google.com" is not as official as the TLD of some country but it seems more important. By doing that you will discover some patterns but also some exceptions e.g. you will find IP addresses that are populair. Each of these entries fills the field "Alexa Ranking". (for performance I first load the .csv in a help table) Alexa will force you to review the patterns so that is good (a good test set) I have written a class that traverses my Firefox Databases (sql lite) and exports all urls in there as .URL in a hierarchical directory structure. It also exports the favicons whether they be .ico, .png, .gif etc... (see below). This is also read in the database. Since I update this a lot it sycns with the database described in 1 and 2. (in the beginning I also exported the dividers but I stopped doing that). I have begun to just drag and drop bookmarks in this directory structure from other browsers e.g. from chrome I just drag a bookmark from the browser to the directory which also delivers that .url file. The directory structure of URL's I have given extra properties e.g. (h) at the beginning of the name will lead to a "heart" e.g. one URL I particuarly like and #01# will place it at the top (or at least thats the way code further on handles it). I have placed this directory structure in a dropbox. I still have to write the code on the server to be in constant sync so the dropbox server part. (My WORDPRESS on the server counterpart constantly reads the URL directory structure for syncing and updating bookmarks as above but i now use ftp sync) I have written classes for delicious (you need a MD5) and StumbleUpon to get not only the ranking (delicious=amount of bookmarks) (SU= amount of reviews and amount of pageviews) but also the TAGS and the description people use (why should I invent my own tags if people have already given them). Since you have a limit amount of calls you can do to these systems you need to spread it over time to enrich your database. (if you now go to delicious and look up a link see the right side and get an idea about the taxonomy of tags given to links) I use the Google favicons provider (const GOOGLE_ICON_URL = 'http://www.google.com/s2/favicons?domain=';) to show the favicons BUT since Google does not have all the icons (e.g. not for facebook applications) I enrich the cache with the icons I exported from Firefox. For that you need a priority system build in which chooses the correct favicon over the other. To cache this I have a caching structure that looks like the domain reversed for the . parts e.g. .com.facebook.apps.geochallenge and on a deeper level the relative path structure. In eeach directory in that cache structure I store the cache favicons. In a previous release I also store there the results of the calls to delicious and stumblupon. It seems that this is WordPress out-of-scope but in fact (grin) it is very in-scope. The build-in link functionality has no good meta options / no meta table and it has some more restrictions like no hierarchical categories etc... Also you need to type in information in it itself while there are a lot of services which already categorize urls (e.g. dmoz) and give it tags etc... which have become sort of default. So this lies "under" my WordPress site for handling my links. I am making this setup with all the information of at least the top 1.000.000 plus sites to make the amount of calls less and to later on share this as a plugin. I have a stumbleupon plugin in the wp plugin db and that led to this. It can give you information on the external links you have in your weblog. There are a lot of plugins that give you information on SEO general but none which show you reports and comparions of e.g. ´what percentage of your outgoing links is in which category or popular or not etc..´. It also gives rankings to your incoming links and outgoing links etc. etc.
Wondering how to turn your firefox bookmarks into a WordPress blog?
wordpress
Anyone know of a way to deregister custom post types ? Is there an equivalent to register_post_type() ?
Currently there is not a function for unregistering a post type, the process however is quite simple. Andrew Nacin provided some code over on trac, found here and posted below. <code> if ( ! function_exists( 'unregister_post_type' ) ) : function unregister_post_type( $post_type ) { global $wp_post_types; if ( isset( $wp_post_types[ $post_type ] ) ) { unset( $wp_post_types[ $post_type ] ); return true; } return false; } endif; </code> Unregistering a built-in post type will have unknown effects on WordPress, so please do so at your own risk. Unregistering a custom post type should be perfectly safe, but would naturally do no cleanup on your installation(ie. unregistering a post type does not equate to data removal from the database). I can imagine a few scenarios where this could be required, but the more sensible approach(where possible), would be to simply not register the post type in the first place if it's not wanted.
Deregister custom post types
wordpress
What is the variable that holds the wp.me url? / What is the webservice / call that provides me the wp.me url? / What is the workaround to read that rel tag from the dynamic generator header (on a self hosted domain). ... to show it beneath each post.
WP 3.0 includes: <code> wp_get_shortlink() </code> which returns the ?p=1 style url for any post within your domain. This can be filtered, however for other shortening services, which is what the Wordpress.com Stats plugin does for self-hosted blogs. With that plugin installed and activated, wp.me shortlinks will be output instead of the default mydomain.com/?p=1, and can be retrieved with the function which can be used within the loop as: <code> echo wp_get_shortlink() </code> or to retrieve any post outside the loop: <code> $link = wp_get_shortlink($post-&gt;ID); </code>
How to show wp.me shortlink underneath each post?
wordpress
I need to allow registration as part of a build for a client, and I am aware this can be turned on in the admin panel, but can I turn it on in the function?
Yes sure you can, just update the appropriate option inside your given function.. <code> update_option( 'users_can_register', 1 ); </code> It's a checkbox option, so the value is 1 = on, 0 = off.. Hope that helps..
can registration be enabled programatically?
wordpress
Does anyone have a suggested plugin that does the following: when a user hits publish on a post for the first time, it should have a popup, notice, or alert that asks the following: Do you have a title? Is the article complete? Spell checked? Did you pick tags? Have you selected a category? Choose a featured image? Any type of that functionality to catch uncompleted fields or merely serve as a warning would be quite awesome.
Create new plugin and add this as your the content: <code> &lt;?php /* Plugin Name: [CR]TestDropIn Plugin URI: http://bayu.freelancer.web.id/ Description: A barebone plugin to test whatever wordpress API you want to test Author: Arief Bayu Purwanto Version: 0.0.1 Author URI: http://bayu.freelancer.web.id */ add_action('admin_head', 'xxx_admin_hook'); function xxx_admin_hook(){ ?&gt; &lt;script language="javascript" type="text/javascript"&gt; jQuery(document).ready(function() { jQuery('#post').submit(function() { //alert('Handler for .submit() called.'); //return false; var cfm = confirm("Do you have a title?\n" + "Is the article complete?\n" + "Spell checked?\n" + "Did you pick tags?\n" + "Have you selected a category?\n" + "Choose a featured image?", "Check your content"); if(cfm) { return true; } jQuery('#ajax-loading').hide(); jQuery('#publish').removeClass('button-primary-disabled'); return false; }); }); &lt;/script&gt; &lt;?php } </code> Note: It has bug as it doesn't cancel the loading icon. Nothing big if you don't really care that, as it doesn't interfere the process nor does it break the wordpress. It just doesn't that good to see. bug fixed! Plugin published here (while waiting approval for plugin repository).
WordPress prompt checklist before publish?
wordpress
With WordPress 3.0 its easy to for users to submit custom content from the front end. They don't even need to be logged in anymore. Is there a functions code (not a plugin) to notify a predefined email, such as the site admin, of new posts in just a certain post type? For example the site admin get notified whenever a new "usernews" post type is posted? Thanks!
I don't know the name of a function that would do just that - but i can give you what i think is a good algorithm to do so However, I suggest you do the following trick : Once the user publishes new content - let it have a category called "user submission" for example or any other stuff Once an admin views the post, he can remove that category and label the content accordingly. So all you have to do is use feedburner or any email notification system to let the people you want know about the "new posts" or RSS subscription by category to do by programming : 1 - you have to fetch the user details for which users are admins from the tables users/usermeta 2 - in some separate table, you must have lastPostId, AdminId 3 - write a script get the posts that have an ID > lastPostId and send the email 4 - this script can be run using a cron job
Notify admin on new submit
wordpress
Looking for advice for the best method to accomplish the following. I have a custom page template with several custom fields/taxonomy. The data needed for these custom fields actually resides in .txt files that are updated once a week. They are easily converted into .csv files. What would be the best and most secure method in getting this data into a custom page template, I figure I have 3 options. Read the raw .txt or .csv files using custom php? Import the .csv into a separate database and grab the data from it? Import the data into the WordPress database? Option 3 seems to be the best one, but I am completely unfamiliar with the wordpress database structure and the best way to go about this.
Unlikely that you will need intermediary database, from your description this is likely to be easy enough with bit of PHP and WP APIs. Create WP-Cron task (if you need automated recurrent import). Read data from flat files, for example with <code> fgetcsv() </code> . Use <code> wp_insert_post() </code> for creating posts and custom field functions to add your data. This was recently covered in detail in stackexchange-url ("WP insert post PHP function and Custom Fields") question.
Advice needed for importing custom field data and database structure
wordpress
( Moderator's note: The original title was "Custom User Role Restrictions") A project I am working on requires me to create two new user roles - one for the owner of the website and the other for agents of the company. With the website owner user role I was just looking for a way to restrict users in this group from modifying core site settings while having access to modify all other settings. The code below seems to work perfectly for everything other than the user management area. I did want users of this group to be able to add/modify website users BUT where I am running into a problem is that users of this group currently have the ability to create users in the "Administrator" category and they are also able to deleting existing "Administrators" . What I am looking for is a way to modify the code below so that such users can NOT delete or modify a user account which is set as "Administrator" and restrict the user from being able to create a new Administrator account. Does anyone know how this can be done? <code> // CREATE CUSTOM - SITE OWNER - USER ROLE WITH CUSTOM CAPABILITIES if (!get_role('website_owner')) { //let's use the editor as the base capabilities $caps = get_role('editor')-&gt;capabilities; $caps = array_merge( $caps, array( 'install_plugins' =&gt; false, 'activate_plugins' =&gt; false, 'update_plugins' =&gt; false, 'delete_plugins' =&gt; false, 'list_users' =&gt; true, 'add_users' =&gt; true, 'create_users' =&gt; true, 'edit_users' =&gt; true, 'delete_users' =&gt; true, 'remove_users' =&gt; true, 'unfiltered_upload' =&gt; true, 'install_themes' =&gt; false, 'update_themes' =&gt; false, 'delete_themes' =&gt; false, 'switch_themes' =&gt; false, 'edit_theme_options' =&gt; true, 'manage_options' =&gt; false, 'import' =&gt; false, 'update_core' =&gt; false, 'edit_dashboard' =&gt; false, 'gravityforms_view_entries' =&gt; true, 'gravityforms_edit_entries' =&gt; true, 'gravityforms_delete_entries' =&gt; true, 'gravityforms_export_entries' =&gt; true, 'gravityforms_view_entry_notes' =&gt; true, 'gravityforms_edit_entry_notes' =&gt; true, 'gravityforms_feed' =&gt; true, )); //adding new capabilities. // Ref: http://codex.wordpress.org/Roles_and_Capabilities#Capability_vs._Role_Table add_role( 'website_owner', 'Website Owner', $caps ); } </code>
Hi @NetConstructor: I think this is what you need. Note that I didn't include the full setup of your <code> 'website_owner' </code> role, just the addition of a new capability called <code> 'manage_administrators' </code> . Also, I only attempted to remove the "Delete" link from any users that don't have the <code> 'manage_administrators' </code> capability (which you'll need to add to the administrator role, of course) and I also simply removed the Administrator as a role option on the "Add New User" page. I didn't attempt to ensure they can't delete or add administrators via some nefarious method, and I didn't disable any other feature that might allow them to add or delete administrators. That said, maybe this is sufficient? <code> add_action('user_row_actions','yoursite_user_row_actions',10,2); function yoursite_user_row_actions($actions, $user_object) { // remove the ability to delete an administrator global $pagenow; if ($pagenow=='users.php' &amp;&amp; isset($user_object-&gt;caps['administrator']) &amp;&amp; !current_user_can('manage_administrators')) unset($actions['edit']); unset($actions['delete']); return $actions; } add_action('editable_roles','yoursite_editable_roles'); function yoursite_editable_roles($all_roles) { // remove the ability to add an administrator global $pagenow; if (in_array($pagenow,array('user-edit.php','user-new.php')) &amp;&amp; !current_user_can('manage_administrators')) unset($all_roles['administrator']); return $all_roles; } add_action('admin_init','yoursite_admin_init'); function yoursite_admin_init() { $wp_roles = new WP_Roles(); $wp_roles-&gt;use_db = true; $administrator = $wp_roles-&gt;get_role('administrator'); if (!$administrator-&gt;has_cap('manage_administrators')) $wp_roles-&gt;add_cap('administrator','manage_administrators'); $website_owner = $wp_roles-&gt;get_role('website_owner'); if (!$website_owner) { //let's use the editor as the base capabilities $caps = get_role('editor')-&gt;capabilities; $caps = array_merge( $caps, array( 'install_plugins' =&gt; false, 'activate_plugins' =&gt; false, 'update_plugins' =&gt; false, 'delete_plugins' =&gt; false, 'list_users' =&gt; true, 'add_users' =&gt; true, 'create_users' =&gt; true, 'edit_users' =&gt; true, 'delete_users' =&gt; true, 'remove_users' =&gt; true, 'unfiltered_upload' =&gt; true, 'install_themes' =&gt; false, 'update_themes' =&gt; false, 'delete_themes' =&gt; false, 'switch_themes' =&gt; false, 'edit_theme_options' =&gt; true, 'manage_options' =&gt; false, 'import' =&gt; false, 'update_core' =&gt; false, 'edit_dashboard' =&gt; false, 'gravityforms_view_entries' =&gt; true, 'gravityforms_edit_entries' =&gt; true, 'gravityforms_delete_entries' =&gt; true, 'gravityforms_export_entries' =&gt; true, 'gravityforms_view_entry_notes' =&gt; true, 'gravityforms_edit_entry_notes' =&gt; true, 'gravityforms_feed' =&gt; true, 'manage_administrators' =&gt; false, )); $wp_roles-&gt;add_role('website_owner','Website Owner',$caps); } } </code>
Disallowing Users of a Custom Role from Deleting or Adding Administrators?
wordpress
I have a plugin that restricts the categories users can view/edit in the admin. All works fine in WordPress 3.0.1, but as I started testing 3.1 I noticed that the category filter, which is AJAX, allows you to bypass the restrictions. I'm able to filter this out in 3.0.1 because it's submitted via URL parameters. My trouble is being able to $_GET the 'cat' parameter from the new AJAX request. I have tried testing for $_SERVER['HTTP_X_REQUESTED_WITH'], but it doesn't register. I've asked this question on the wp-hackers mailing list, but no one can give me actual code that helps with my predicament.
For excluding terms of a taxonomy the better way to do that would be to use the hook that was created for doing term exclusions.. <code> list_terms_exclusions </code> Get the available categories using <code> get_terms </code> (get_categories calls get_terms anyway IIRC), and do your exclusions using a hook on <code> list_terms_exclusions </code> and your code should work as expected.. You can see the hook i'm referring to on line 1040. http://core.trac.wordpress.org/browser/trunk/wp-includes/taxonomy.php NOTE: Your plugin does not have a sanitization callback function when it calls register_setting , your options won't get sanitized properly without one, i'd strongly advise you declare a callback function and sanitize the data as appropriate (especially if you're passing that saved data into queries).
Get cat parameter from admin-ajax
wordpress
I'm developing a custom wp theme which needs a gallery function. I looked over a few popular gallery plugins, but all of them seem "bloated" with a lot of unnecessary stuff. Do you have any recommendations of a light gallery plugin that allows the admin to upload photos and group them into galleries?
What's wrong with the built-in gallery functionality? Seems to match your description pretty well. ;-)
Basic gallery plugin suggestion
wordpress
I'm working on a custom plugin that needs to display specifically the commenter's nice name. The codex shows how to do this for the logged in user but not someone else. Can this easily be done?
<code> wp_get_current_commenter() </code> returns an array, the entry <code> 'comment_author' </code> stores the name: <code> Array ( ['comment_author'] =&gt; 'Harriet Smith, ['comment_author_email'] =&gt; 'hsmith@,example.com', ['comment_author_url'] =&gt; 'http://example.com/' ) </code> More information is available in the codex . Update To find the nice name, ask the DB: <code> /** * Searches the user table by display name. * @param string $display_name * @return object */ function get_user_by_display_name( $display_name ) { global $wpdb; $user = $wpdb-&gt;get_row( $wpdb-&gt;prepare("SELECT * FROM $wpdb-&gt;users WHERE display_name = %s", $display_name) ); if ( ! $user ) { return FALSE; } _fill_user($user); return $user; } // Usage: if ( $userdata = get_user_by_display_name( 'Thomas Scholz' ) ) { print $userdata-&gt;user_nicename; } </code> Caveat: Not tested. :)
Display WordPress commenter nice name
wordpress
My plugin needs to know if the currently active theme places the post title in H1 heading tags? I'm looking for suggestions on approaches to create script that could discern this. UPDATE: The plugin evaluates the SEO profile of the post content to help the user make improvements for search rankings. Second only to the post title, the h1 tag is one of the most important tags for SEO. However, I don't want to ask the user to include their primary keyword in an h1 heading tag in the post content if the theme already does that (as many do).
Send an HTTP request to the page and search the response body for <code> &lt;/h1&gt; </code> . See this Gist for an example. Store the result in an option and delete this option when the user switches the theme (hook into the action <code> switch_theme </code> ).
How to determine, from plugin script, if active theme has The Post Title
wordpress
If you find a WordPress bug, how do you verify that it has been reported and/ or is being worked on for the next release?
The process of evaluating and reporting bugs is documented in Codex under Reporting Bugs .
WordPress bug reporting?
wordpress
How should I use posts_where to change meta_value from a string to integer?
Try this: <code> add_filter('posts_where', 'unquote_numeric_meta_value', 10, 2); function unquote_numeric_meta_value($where, $args) { $value = isset($args-&gt;query_vars['meta_value']) ? $args-&gt;query_vars['meta_value'] : false; if(is_numeric($value)) $where = str_replace("'{$value}'", $value, $where); return $where; } </code>
How should I use posts_where to change meta_value from a string to integer?
wordpress
I created a separate template, attachment.php, for displaying image attachments. It's relatively simple; basically a stripped down version of single.php. Everything is working great except that when I have the All in One SEO plugin enabled (and set to rewrite titles), the titles on those attachment pages are being doubled. For example, this attachment 's title should be "11 hours of MacBook Air battery life", but the title tag is being rendered as "11 hours of MacBook Air battery life 11 hours of MacBook Air battery life" This only happens on the attachment.php pages, not on the rest of the site's normal posts and pages. Any idea what could cause that?
The problem is the way that All in One SEO is set up. It assumes that you always attach your media files to a post or page. Simple way is to attach them to a post or page and it will make your attachment title be "PostName AttachmentName - Blogname". The other way is also easy, but you have to make a change to the plugin. You open up the aioseop.class.php file, and find this chunk of code: <code> else if (is_attachment()) { $title = get_the_title($post-> post_parent).' '.$post-> post_title.' – '.get_option('blogname'); $header = $this-> replace_title($header,$title); } </code> The problem with this setup is that it grabs the parent whether or not it is a child. If it has no parent, its parent title is its own title, hence the double title. To remedy this, we can add an if statement to check whether or not it has a parent to avoid the double title. So the code would look like this: <code> else if (is_attachment()) { if(get_the_title($post-> post_parent) != $post-> post_title) { $title = get_the_title($post-> post_parent).' '.$post-> post_title.' – '.get_option('blogname'); } else { $title = $post-> post_title.' – '.get_option('blogname'); } $header = $this-> replace_title($header,$title); } </code> Then you just upload this to the All in One SEO plugin folder and your problem should be fixed. Hope that helps. {R:S}
Doubled titles when using All in One SEO with custom template
wordpress
Trying to use meta_compare as suggested in the codex : <code> query_posts('meta_key=miles&amp;meta_compare=&lt;=&amp;meta_value=22'); </code> Here is my code: <code> global $wp_query; query_posts( array_merge( array( 'category__and' =&gt; $mycatsarray, 'meta_key' =&gt; 'price', 'meta_compare' =&gt; '&gt;=', 'meta_value' =&gt; 8500000, 'orderby' =&gt; meta_value_num, 'order'=&gt;DESC ), $wp_query-&gt;query ) </code> ); I'm using array_merge to persist the original query. So I couldn't quite figure out how to use the suggested syntax ('&amp;name=value') for meta_compare and meta_value. Anyways, in my code the meta_value seems to be treated like a string and not an integer as expected. Here is an example of some typical price custom fields from my custom posts: 8500000 600 15000 900 750 9000000 If it's not a string issue, it could be that WordPress is ordering (DESC) these custom fields as follows: 9000000 900 8500000 750 600 15000 I would like them to be ordered (DESC) as follows: 9000000 8500000 15000 900 750 600 Am I doing something wrong here?
See this question and my answer there stackexchange-url ("query_posts -> using meta_compare / where meta value is smaller or greater or equals…") Basically for the purpose of meta comparison value is always treated as string, because it is passed as such to <code> $wpdb-&gt;prepare() </code> method.
meta_compare seems to be treating values as strings instead of integers as expected
wordpress
WordPress may have a text editor that appears to be WYSIWYG, but upon using it I discovered that it is actually WYSIWYMG- What You See Is What You Might Get (once it's done screwing with the HTML). Isn't there a way to tell it to do nothing with the text you put into it? Just leave it as it is. No optimizations, no trying to guess what I meant, no correcting my HTML, no converting whitespace into nbsp's that for some reason cause line breaks, no changing the formatting or the spacing between embedded objects after you edit it to fix one typo... I did try searching the settings area but found only one HTML related option (regarding matching closing tags).
After you post your content, WordPress will pass the_content() function through a number of filtering function's. There are four of them, wptexturize(), convert_smilies(), convert_chars(), and wpautop(). All of these are defined in wp-includes/formatting.php and are referenced in wp-includes/default-filters.php. To remove these filtering functions you can disable them by putting this in your functions.php theme file: <code> remove_filter('the_content', 'wpautop'); remove_filter('the_content', 'wptexturize'); remove_filter('the_content', 'convert_smilies'); remove_filter('the_content', 'convert_chars'); </code> That should remove all formatting between what you save in TinyMCE (the WYSIWYG editor) and the front end view of your website. For more reference on what each of these does refer to the codex. I hope this helps, best of luck!
Why is WordPress WYSIWYMG and how do I make it WYSIWYG?
wordpress
I'm using add_filter('manage_posts_columns') in my plugin.php to add a column to the Edit Posts listing which is driven by edit.php. How can I attach a css style to the edit.php? I want to be able to color the background of my column td.
Creating Admin Themes article in Codex shows you how to add css styles to admin pages
How can I add a css rule to edit.php?
wordpress
I used to have a self hosted wordpress blog but I switch to a wordpress.com one. I can't seem to find the plugins area. Any help?
You can't upload plugins on WordPress.com . For security and performance reasons, you can only run what wordpress.com staff has approved.
How can I install a plugin on a Wordpress.com hosted blog?
wordpress
Is it now possible to query multiple categories from the URL? http://www.mywpsite.com/?cat=1+7 ? I think this has worked for tags for some time . If not, is there another way to achieve this?
If you have a feature request for WordPress, the best way to get it addressed is to add a ticket on Trac. Then developers can adopt the task, patch WordPress, and submit the improvements to the next version. If a Trac ticket has already been created for a particular feature, you can comment on it to weigh in and follow the subsequent discussion. The last time I checked, there was a ticket for querying multiple terms in a taxonomy (tags, categories, or custom) at the same time: Ticket #12891 . According to the ticket, the project is scheduled to be included in WP 3.1. But we won't know for sure until the first release candidate comes out. According to the last scope update before the feature freeze , this is going to be included in 3.1 ... but it won't be "fixed" until 3.1 is actually released. If you want to use the feature now, you have a couple of options: You can download the actual patches from Trac and patch your WordPress installation to add the new functionality. I wouldn't recommend this because they may or may not depend on other 3.1 improvements that aren't included explicitly in these patches (i.e. improvements added by other tickets). Install the WordPress Beta Tester plug-in and upgrade to version 3.1-alpha. This would be the safest way to use the new feature, but still might cause problems! WordPress 3.1 isn't considered "stable" yet and some of the features/code might (will definitely) change before the final release date. There's no guarantee that the latest nightly build will be bug-free.
Have multiple category queries from the URL been fixed yet?
wordpress
Is there an easy way to query for any posts that is tagged with any term from a particular taxonomy? I know this technique: <code> $custom_taxonomy_query = new WP_Query( array( 'taxonomy_name' =&gt; 'term_slug', ) ); </code> But I would like to either pass a wildcard in place of term_slug, or perhaps just an empty string. Then that would give me all posts that are tagged by any term in that taxonomy, not just one specific term. Thanks for your help, Dave
In retrospect, I've did a mashup of MikeSchinkel and t31os suggestion. It's possible to inject that to existing queries on the fly, but it needs WordPress 3.1: stackexchange-url ("Plugin to get an RSS Feed for posts containing any term from a taxonomy.")
Custom Taxonomy WP_Query for All Terms in a Taxonomy?
wordpress
I have a client who wants to use Joomla, because they were told it was good. I'm trying to convince them that WordPress is a much more user-friendly option. I've played with Joomla (and Drupal) once before, and I found the learning curve incredibly steep (probably due to their obscure terminology). I consider myself quite technically savvy, and if I found it hard, I'm sure my less technically competent clients will find it even more obscure and difficult to learn. So far, I have yet to come across anything a client would need that couldn't be done in WordPress, but before I tell them that, I wanted to check that this is, indeed, the case. Is there anything that Joomla or Drupal can do that WordPress can't (especially now with custom post types in WP 3+)?
If memory serves, Drupal's lead dev summed things up like so last summer: Drupal is, on the UI front, where WP was 3 years ago; and WP is, on the feature front, where Drupal was 3 years ago. My own experience with WP and Drupal are basically so: WP has a prettier/easier UI. Drupal is more robust: core and add-on devs are rarely writing code to learn PHP. WP is still stuck in old PHP4 paradigms. Drupal isn't. WP development is still not unit-test driven. Code quality is, at best, inconsistent. Drupal is mostly EAV-driven. This makes things much more flexible... and slow for anything requiring complex queries. (Drupal compensates this by having built-in caching.) WP is heading in the same direction. I can't really say for Joomla. I dismissed it years ago because I hated the UI. But everyone here probably has a trustworthy friend who is very happy with it. As to what I tend to use: For a blog or a simple brochure-like site, definitely WP. For a slightly more complex site, also WP -- but an inner voice always tells me I should be using Drupal instead. For anything really complex and mission critical, a unit-test driven PHP framework (Symfony, Solar, Yii...). UI will end up so so, but I like to sleep at night.
Is there anything that Joomla or Drupal can do that can't be done in WordPress?
wordpress
I am using a plugin the updates the option table using update_option command. When I update content with hebrew characters it turns into gibrish. My database does support hebrew (or any other utf8 chars). Is there any workaround? Thank you!
Chances is are that the content-type/charset header is not being sent, and that you end up reading the utf8 chars as if they were latin-1. Also, note that serialize()/unserialize() are not multibyte character-safe. For a subset of characters, the string's length as returned by serialize() will occasionally differ from the expected length as it would be returned by mb_strlen(). This leads to all sorts of hard to debug unserialize problems which, since around WP 2.8, WP tries to discard in order to avoid crashing sites.
update_option method with support of utf8
wordpress
I have my blog hosted at www.alphaot.com and I guess it's good enough. But problems arise when the lines of code get longer than 30 characters. The lines just wrap and get icky or something they even don't wrap! In your experience what's a great WordPress theme for a developers blog to post code to? Also, I'm using Windows Live Writer, any extensions for code publishing you would recommend? Edit: More than plugins, I'm interested on a clean, free wordpress theme that is WIDE so the code doesn't have to be wrapped.
In the end I used the theme called Elegant Grunge from Michael Tyson. I'm using Windows Live Writer 2011 with the Insert Code plugins for it, and it works very well. Check out my blog Alphaot.com to see how it ended up.
What theme is good for posting code?
wordpress
I have been using w3 Total Cache with the setting to enable Expires Headers and eTags but they are not being set. I'm serving images and other media from a sub-domain such as static.example.org served by nginx but it didn't work even when I was serving these files with Apache from the main domain. I've tried disabling and re-enabling the browser caching settings in the admin without success. What do you suggest?
do you have mod_expires installed and enabled in your apache module?
w3 Total Cache expire headers not set
wordpress
What is the most flexible photo gallery plugin available on WordPress? By flexible, I mean a plugin that can: create galleries per folder / event display / generate thumbnails per size I want (it would be good to have an API/function for this) display the most recent gallery from either certain event or all photos uploaded. Is there any? Or something close to this?
The most full featured one I've found is NextGEN gallery. It even has add-ons for specific functionality beyond what's built in.
Most Flexible Photo Gallery Plugin?
wordpress
another question about image. Can I add/attach images to post without adding it to post? The reason behind this is so that I can manipulate it whatever I want using API.
There is a Plugin called Attachments http://wordpress.org/extend/plugins/attachments/ Maybe this is something you looking for.
Can I attach image to post without adding it to post?
wordpress
I am trying to build a class to make the job off adding new settings easier. The trouble I am having is that, although I have traced the variable through all of it's stages, the string 'manage_options' doesn't seem to grant admin the right to amend and option. I keep getting "You do not have sufficient permissions to access this page." when I try access the new settings page. Here is a heavily simplified version of the class, the creation function and its action hook. <code> class optionObject{ var $user_level = 'manage_options'; function add_page() { add_options_page(menu_page_title, page_title, $this-&gt;user_level, menu_slug, array(&amp;$this, 'do_page')); } function do_page(){ //do stuff to display page } } function test_options(){ $options = new optionObject(); add_action('admin_menu', $options-&gt;add_page()); } add_action('admin_init', 'test_options' ); </code> Unedited Version here
<code> admin_init </code> is called after <code> wp-admin/menu.php </code> is included , so the access check has already been executed and the <code> admin_menu </code> action has fired by the time you execute <code> test_options() </code> . Remove the <code> admin_init </code> hook and call <code> test_options() </code> directly, or find another way of structuring your code so that the <code> admin_menu </code> hook is set up correctly. You might think it could work because you see the menu option when you are on other pages. This is because the menu is drawn after the page access is checked : The menu is drawn in: <code> wp-admin/menu-header.php </code> on line 169 included in <code> wp-admin/admin-header.php </code> on line 143 included from various places, but always after <code> wp-admin/admin.php </code> line 132 which is after <code> admin_init </code> fires in <code> wp-admin/admin.php </code> on line 98 The access check however is done in: <code> wp-admin/menu.php </code> on line 441 which is after <code> admin_menu </code> fires in <code> wp-admin/menu.php </code> on line 328 which is included in <code> wp-admin/admin.php </code> on line 93 You see that adding menu items in <code> admin_init </code> is OK to be included in the drawn menu, but too late for the access check. That's your current situation, and you need to change that by adding the page in the <code> admin_menu </code> hook or earlier.
add_option_page capability behaving strange
wordpress
In the function below, the save_content function runs, but the doReplace does not (echo "This is the doReplace" never shows. Any ideas why? <code> add_action('content_save_pre', 'save_content'); function save_content($content){ global $post; $mykeyword = rseo_getKeyword($post); $mykeyword = preg_quote($mykeyword, '/'); $content = preg_replace_callback("/\b($mykeyword)\b/i","doReplace", $content); return $content; } function doReplace($matches) { echo "This is the doReplace"; die; } </code>
Your function needs to return the data, not echo it.. <code> function doReplace($matches) { return "This is the doReplace"; } </code> Hope that helps..
Why does preg_replace_callback never fire in this function?
wordpress
I have a function inside my plugin that attaches to save_post, and inside that function, I'm seeking to filter the post_content prior to it being saved. However, the content never actually gets changed once its saved. See below where I'm setting $post-> post_content = "test"; <code> add_action('save_post', 'save_post_filter',10,2); function save_post_filter($postID, $post){ if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return $postID; } else { if($parent_id = wp_is_post_revision($postID)) { $postID = $parent_id; $post = get_post($postID); } $post-&gt;post_content = "test"; } } </code>
The <code> content_save_pre </code> filter is applied to the content before it gets saved in the database. Some default filters hook into it too, for example <code> balanceTags() </code> and <code> wp_filter_post_kses() </code> .
How to filter $post-> post_content prior to save
wordpress
I'm sure this question is asked alot, but I cannot figure it out, since all the different ways to query posts are confusing me.. Here is my current code. How can I tell the code to only get posts from category ID #22? <code> &lt;?php $querystr = " SELECT post_id, AVG(meta_value) AS total, COUNT(post_id) as num_karakter FROM sk_postmeta WHERE meta_key = 'krit_karakter' GROUP BY post_id ORDER BY total DESC LIMIT 5 "; $pageposts = $wpdb-&gt;get_results($querystr, OBJECT); if ($pageposts) { ?&gt; &lt;ul class="smartbar-items"&gt; &lt;?php foreach ($pageposts as $post): setup_postdata($post); ?&gt; &lt;li&gt;&lt;a href="&lt;?php echo get_permalink($post-&gt;post_id);?&gt;"&gt;&lt;img src="&lt;?php bloginfo('url');?&gt;/wp-content/files_mf/&lt;?php echo get_post_meta($post-&gt;post_id, 'game_poster', true); ?&gt;" width="80" height="110" alt="&lt;?php echo get_the_title($post-&gt;post_id);?&gt;" /&gt; &lt;br /&gt;&lt;?php echo get_the_title($post-&gt;post_id);?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; </code> Thanks for all help!
I would do this in two pieces. Add this into your functions.php file to grab custom fields globally: <code> function get_custom_field($key, $echo = FALSE) { global $post; $custom_field = get_post_meta($post-&gt;ID, $key, true); if ($echo == FALSE) return $custom_field; echo $custom_field; </code> } Build your query as follows: I can't seem to get markdown to play nice, so here's the code in Pastie http://pastie.org/1294594
Select category in custom query
wordpress
After reading stackexchange-url ("Adding a Taxonomy Filter to Admin List for a Custom Post Type?") I tried it but I wasn't able to get it to filter two (2) different taxonomies at same time. The system is only filtering latest taxonomy and ignoring other one. Does anyone know how to filter two taxonomies at same time?
Hi @Ünsal Korkmaz: I don't have the time to actually write up a fully working example for you right now, but since you requested help in email I figured I would point you in the right direction. As you may or may not know, this isn't really an issue for the admin post listing; most all of that code should work fine. The issue is that currently WordPress does not have the ability to use <code> query_posts() </code> / <code> get_posts() </code> / <code> WP_Query </code> to filter on more than one taxonomy term without using hooks. (There is a very good chance that will change in v3.1; we can only hope!) The solution is to use a <code> 'posts_where' </code> hook as illustrated here with the <code> tax_terms_where() </code> function written for that answer: <a href="stackexchange-url Getting the Intersection of Two Custom Taxonomy Terms for a Custom Post Type? You'll also need to modify the <code> 'parse_query' </code> hook to capture your filter values, something like this (I have not tested this, so there may be small syntax errors): <code> &lt;?php add_filter('parse_query','yoursite_parse_query'); function yoursite_parse_query($query) { global $pagenow; $qv = &amp;$query-&gt;query_vars; if ($pagenow=='edit.php') { $tax_terms = array(); if (!empty($qv['marka'])) $tax_terms[] = "marka:{$qv['marka']}"; if (!empty($qv['konu'])) $tax_terms[] = "konu:{$qv['konu']}"; if (count($tax_terms)) $qv['tax_terms'] = implode(',',$tax_terms); } } </code> The above assumes you have dropdowns with names of <code> 'marka' </code> and <code> 'konu' </code> . You'll probably also need to tell WordPress to recognize them as query vars using an <code> 'admin_init' </code> hook. Again, I haven't tested this so I'm hoping it works as written: <code> add_action('init','yoursite_init'); function yoursite_init() { global $wp; $wp-&gt;add_query_var('marka'); $wp-&gt;add_query_var('konu'); } </code> That's about it. Combine the knowledge of the three posts; this one, the one on stackexchange-url ("admin lists"), and the one on stackexchange-url ("multiple taxonomy queries") and I think you'll get it done. You might even want to post your solution for others to learn from. Let me know if you get stuck.
Filtering Posts by Multiple Taxonomy Terms such as in an Admin Post Listing?
wordpress
I've got a small .js file on my wp site where I have been adding in all of my small js scripts. It works perfectly, but I am stuck trying to figure out how to add in another script. So far jslint does not complain about my current file and says it is ok. my script: <code> jQuery(function ($) { function mycarousel_initCallback(carousel) { jQuery('.jcarousel-control a').bind('click', function() { carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text())); return false; }); jQuery('.jcarousel-scroll select').bind('change', function() { carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value); return false; }); // Next Button $('#mycarousel-next').bind('click', function() { carousel.next(); return false; }); // Prev Button $('#mycarousel-prev').bind('click', function() { carousel.prev(); return false; }); }; } </code> The script I want to add in starts like this: <code> jQuery(document).ready(function($) { var gallery = $('#thumbs').galleriffic({ delay: 3000, // in milliseconds }); }); </code> Where I keep getting stuck, is that I am finding a lot of scripts that start with the jQuery(document) part. When I try to add scripts that begin like that then everything breaks. I'm guessing this is a really stupid question, but what do I need to change in the new addon script so that it will play nice with my current file? thank you for your help and time on this one. Trying hard to learn js though it's a slow process here.
The <code> jQuery(document).ready </code> event is called when the document DOM is ready to be manipulated. In earlier days we attached all our handlers to <code> document.load </code> , but this waits until all images are loaded too, and most of the time one doesn't need that. There are three equivalent ways of hooking into this event, and a fourth almost-equivalent: <code> // Long form jQuery(document).ready(function() { // Your handler }); // Short form jQuery(function() { // Your handler }); // Intermediate form (not recommended) jQuery().ready(function() { // Your handler }); // Classic event binding - will not be executed again if you hook it too late jQuery(document).bind("ready", function() { // Your handler }); </code> You sometimes see <code> $ </code> used instead of <code> jQuery </code> . This is easy because it is shorted, but some other JS libraries use it also. To prevent overwriting others, jQuery can be executed in <code> noConflict </code> mode . This means that <code> $ </code> is not used, only <code> jQuery </code> is. But, the first argument to your <code> ready </code> handler will be the jQuery object itself. This means that you can write your handler like <code> function($) {} </code> , and you can use <code> $ </code> inside of your function. So your code would become something like this: <code> jQuery(function ($) { function mycarousel_initCallback(carousel) { jQuery('.jcarousel-control a').bind('click', function() { carousel.scroll(jQuery.jcarousel.intval(jQuery(this).text())); return false; }); jQuery('.jcarousel-scroll select').bind('change', function() { carousel.options.scroll = jQuery.jcarousel.intval(this.options[this.selectedIndex].value); return false; }); // Next Button $('#mycarousel-next').bind('click', function() { carousel.next(); return false; }); // Prev Button $('#mycarousel-prev').bind('click', function() { carousel.prev(); return false; }); }; // We are already in the 'ready' event handler, no need to hook into it again // Just add our code here! var gallery = $('#thumbs').galleriffic({ delay: 3000, // in milliseconds }); } </code> If you have more pure JavaScript questions, you might want to ask them on our "parent" site, stackexchange-url ("Stack Overflow"). They have stackexchange-url ("lots of jQuery expertise") there.
combining js scripts from a js newb
wordpress
I'm working on building a recipe/meal planning site in WordPress. I need to have recipes indexable and sortable by the ingredients required, and I'm trying to figure out the best way of doing that. Ideally, I would like to have ingredients in one taxonomy, and utensils/appliances required in another taxonomy. I'm coming up against a stumbling block, though, because I can't think of any simple way to associate measurements with the ingredients. Where I'm at now is using custom fields for the ingredients and values for the measurements and units, like this: Meta Key: eggs Meta Value: 3|eggs Meta Key: flour Meta Value: 2.75|cups and so on. My question is, is there a better way of structuring this information? Related, there apparently is a microformat specification for recipes , which is essentially the format I plan on using for display. There is a WordPress plugin ( hRecipe ) to generate this output format, but its not semantic enough for my liking. If/when I figure out a better way of storing this kind of data, I'll probably release it as plugin...
It's a good idea to use a custom taxonomy to link your ingredients, as this will allow you to get recipes by ingredient. This also means you don't have to store each individual ingredient as a separate meta key-value pair, as you won't do any lookups there. Just store one big object, <code> ingredients </code> , as an ordered list of ingredients and their quantities and units. Read it out when you display the page. So something like this: <code> $ingredients = array( 'eggs' =&gt; array(4), 'whole wheat flour' =&gt; array(1, 'cup'), 'baking powder' =&gt; array(1.5, 'teaspoon'), ); </code> You could also use the ingredient slug or id as the index of the array, then you can cross link from the ingredient list. By separating the number and the units, you can adjust the numbers for number of guests. Say your default is 4 and I have 6 guests, you just multiply everything by 1.5. You can even include a US to metric conversion! But I'll stop before this becomes a stackexchange-url ("Seasoned Advice") question!
Best structure for entering recipes in a WordPress theme?
wordpress
I have a custom post type that i want to access through jQuery - preferably using JSON. So first things first. creating a function that returns/echos json is easy enough, but how would I access it through jquery. as Mike writes in stackexchange-url ("this question"), he - as far as I understand - places it in the wordpress root. which would make it accessable using the php file name - but Is this recommendable? I would rather put it inside a plugin folder. I have tried reading the wordpress codex, but the way ajax calls are handled just confuses me, as you are posting every ajax call to admin-ajax.php, even though it is not an admin page? Can someone please straighten out the problems I'm having? /Storm edit The problem I had was understanding how ajax calls were to be made in wordpress, as well as where to place your php and js code to do/handle the calls. In the other question I linked to, you created a function placing the file in the wp root - I dont want to do that. But I have now learned how to use the wp_ajax_(nopriv_)[action] and can effectivly access the json i create. The problem remaining is Where i should place the JS to make the call. I want to place it in the plugins js file, but as this is to be presented in a page, not on the admin site, ajaxurl isn't defined, so i have to echo using php. <code> echo admin_url('admin-ajax.php'); </code> So the question becomes how should I combine this php with the javascript, and how should i then enqueue it, seeing as it's not a file or a script.
Ajax Handler It is indeed a bit confusing that the Ajax handler is in the <code> wp-admin/ </code> directory, but yes, you can and should use it for non-admin requests too. You then register a handler for the <code> wp_ajax_nopriv_[action] </code> hook, instead of the normal <code> wp_ajax_[action] </code> . In this case you only have to follow the first lines of <code> admin-ajax.php </code> , since a request done by a user that is not logged in will already leave the page around line 50. So register a function for the hook <code> wp_ajax_nopriv_get_custom_post_data </code> , and it will get called if you ask for <code> admin-ajax.php </code> with the <code> action </code> parameter set to <code> get_custom_post_data </code> . Be sure to call <code> die() </code> at the end of your handler yourself, otherwise the default <code> die(-1) </code> will be returned. And also register the logged-in version, <code> wp_ajax_get_custom_post_data </code> (to the same handler function, no problem), since if you are logged in to your site, you will not hit the <code> nopriv </code> hook. Server-side config to Javascript The trick to send server-side configuration data (like the <code> admin-ajax.php </code> url), is <code> wp_localize_script() </code> . You pass it an array of keys and values which will be included in the top of the page. This was probably originally created only for localizable strings, but you can use it to pass configuration data too. <code> wp_localize_script('storm_json_config', 'storm_config', array( 'ajaxurl' =&gt; admin_url('admin-ajax.php'), )); </code> <code> storm_json_config </code> is the handle name (if you want to dequeue it later), <code> storm_config </code> is the name of the Javascript object that will contain your data. So your static Javascript file can contain a line like <code> jQuery.post(storm_config.ajaxurl, ...) </code> . See also stackexchange-url ("bueltge's answer to a similar question"). Static Javascript from the plugin dir To load a static Javascript file from your own plugin dir, you use <code> wp_enqueue_script() </code> . That would look something like this: <code> wp_enqueue_script('storm_json', plugin_dir_url(__FILE__) . 'js/json.js', array('jquery'), '20101105'); </code> Where <code> storm_json </code> is again a handle name, then you give the link to the file, then the dependencies (can be <code> null </code> ), and then a version number that will be added after the request to beat browser caches on updates.
How to manage ajax calls and JSON in wordpress
wordpress
Is there a function to add array of post id's to a category,something like this array(2,3,5,6) to put in some category,not looking for update post. Tnx in advance.
Not exactly add array , but you can loop through that array and run <code> wp_set_object_terms() </code> on each post id. Just study function's arguments carefully, because it defaults to overwriting terms, rather that adding.
Add array of post id's to a category?
wordpress
I would like to "highlight" a featured post above all other posts with a special indicator. Is there a feature in WordPress that will do this or do I need to install a third party plug-in? I am using a custom WordPress install (not WP hosted).
Use the "sticky" feature. In the "Page Attributes" metabox (labelled as Publish ), if you click the "edit" link next to the Visibility option, there is a checkbox which allows you to "Stick this post to the front page" . Unless a theme overrides the default query, that post will show up above all the others. In addition, it adds the class name "sticky" to the attributes returned by <code> post_class() </code> , so you can style it however you want. To add some text to your featured posts and highlight them, add a function like this inside the loop in your index.php (or loop.php, etc., depending on your theme): <code> if (is_sticky($post-&gt;ID)) echo '&lt;span class="featured"&gt;Featured!&lt;/span&gt;'; </code> You can do the same thing with the css :before property, like this: <code> div.sticky h2:before { content: "Featured! "; } </code> (assuming you're using h2's to display the titles of your posts, and you want to add the text before the title)
Highlight a Featured Post?
wordpress
I have the following temporary filter to fix a content error. We have data in our posts that have 4 digit zip codes, because the leading zero was cut when the original file was created. (For instance, a Massachusetts zip code is 0XXXX, but now in our content it is XXXX) <code> function fix_zip_code($content){ if (preg_match('/&lt;span class="postal-code"&gt;(\d{4})&lt;\/span&gt;/i',$content, $match)){ $content = str_replace($match[0],'0'.$match[0],$content); } return $content; } add_filter('the_content', 'fix_zip_code'); </code> How can I apply that filter to all the content at once and re-save the posts so I can remove the regex filter completely?
<code> //run once $allposts = get_posts('post_status=publish&amp;numberposts=-1'); foreach ($allposts as $thispost) { wp_update_post( array( 'ID' =&gt; $thispost-&gt;ID, 'post_content' =&gt; fix_zip_code($thispost-&gt;post_content) ) ); } </code> But as Rarst mentioned, backup your database before doing anything...
How to apply content filter permanently?
wordpress
I would like to use jQuery in my Wordpress plugin. I'm trying to load the jquery library using the enqueue script but its throwing an error. Error: $ is not a function Here's the code snippet that's inside my main plugin.php file... <code> function ($post) { wp_enqueue_script('jquery'); ?&gt; &lt;script type="text/javascript"&gt; function doTestParse(searchString){ var rx = new RegExp('(?![^&lt;]+&gt;)'+searchString, "gi"); $(this).html($(this).html().replace(rx, '&lt;b&gt;$&amp;&lt;/b&gt;')); } &lt;/script&gt; &lt;?php ?&gt; </code>
jQuery is included in <code> noConflict </code> mode in WordPress, so you can't use the shorthand <code> $ </code> , but must write <code> jQuery(this).html(jQuery(this).html().replace(rx, '&lt;b&gt;$&amp;&lt;/b&gt;')); </code>
How to wp_enqueue_script jQuery inside a Plugin
wordpress
I've got to update a bit of sloppy code that shows the 5 most recent comments across the entire blog. The code is using WordPress' <code> get_comments() </code> method, which doesn't appear to return comment id's, or comment links (direct links to comments within posts via the hash-tag). How can I collect more information about the particular comments, and make them links to the actual comments within their parent pages? <code> &lt;h3&gt;Recent Comments&lt;/h3&gt; &lt;ul&gt; &lt;?php $comments = get_comments(array('status'=&gt;'approve','number'=&gt;'5')); ?&gt; &lt;?php foreach ($comments as $comment): ?&gt; &lt;?php $post = get_post($comment-&gt;comment_post_ID, 'OBJECT'); ?&gt; &lt;li&gt;&lt;?php print $comment-&gt;comment_author; ?&gt; on &lt;a href="&lt;?php print get_permalink($post-&gt;post_ID); ?&gt;"&gt; &lt;?php print $post-&gt;post_title; ?&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ul&gt; </code> This is located on the front page of the site, outside of the loop.
You're really close! Add #comment- <code> &lt;?php comment_id(); ?&gt; </code> to the href to append the anchor link <code> &lt;a href="&lt;?php echo get_permalink($comment-&gt;comment_post_ID);?&gt;#comment-&lt;?php comment_ID() ?&gt;"&gt; &lt;?php echo $post-&gt;post_title; ?&gt; &lt;/a&gt; </code>
Comment Link from get_comments()?
wordpress
Is there a good tool to analyze my rewrite rules? I always get confused with the regexes and the parameter replacements. I have created something myself and will post it here so others can use it, but please feel free to add other tools!
Well what a coincidence that you ask this, Jan! Just today I had time on a long train journey and decided to write a Rewrite Analyzer plugin, one that parses your rewrite rules and highlights the query variables. You can test URLs right there and see what query variables will be set. You can find it in the plugin repository, or just as Monkeyman Rewrite Analyzer when search for new plugins in your administration screen.
A tool to analyze rewrite rules?
wordpress
I have a blog with some posts, and each post has a embedded Facebook like button . Pressing the button opens a dialog so my visitors can share the post on Facebook with a comment. When sharing, however, the image selected by Facebook is a generic mail icon and not the post thumbnail. How can I control the image that is used when sharing?
The image that is used for sharing is taken from a chunk of code in the header of your site that will look something like this: <code> &lt;link rel="image_src" href="path/to/theme/screenshot.png" /&gt; </code> Typically it links to the screenshot of your site in the theme. If you removed the code from the header of the file and on single.php put it inside the loop and called your post thumbnail image into the href element I believe it would work. So it would look something like: <code> &lt;link rel="image_src" href="&lt;?php the_post_thumbnail(); ?&gt;" /&gt; </code> This would mean that if you have like buttons on pages that list multiple posts you probably won't have an image. If you included some conditional code that removed it only on single.php then you would have the normal image on any page with multiple posts and an like button and the post thumbnail when the single.php template is being used. So the header code would be: <code> &lt;?php if ( is_single() ) { /* do nothing on single pages */ } else { ?&gt; &lt;link rel="image_src" href="path/to/theme/screenshot.png" /&gt; &lt;?php } ?&gt; </code> Then you'd still use the code to include the post thumbnail in single.php.
How can I control the Facebook like image?
wordpress
I am using wordpress Version 2.9.2 and XML Sitemap Generator 3.2.3 I have registered with Google Webmaster Tools. But I get an error while notifying to Google and I really don't know what it means. Heres a screenshot : And when I click on view result it show me the following message: Ping Test Trying to ping: http://www.google.com/webmasters/sitemaps/ping?sitemap=http%3A%2F%2Fsearock.bplaced.net%2Fsitemap.xml.gz. The sections below should give you an idea whats going on. Errors, Warnings, Notices: WP_DEBUG was set to false somewhere before. You might not see all debug information until you remove this declaration! Result (text only): Result (HTML): If I want to debug the error where can I find WP_DEBUG ? Can someone tell me what's wrong here. Note : I have completed Google Webmaster verification process. Thanks.
<code> WP_DEBUG </code> is a constant which you can define in <code> wp-config.php </code> to disable hiding of PHP errors and notices. Add <code> define('WP_DEBUG', true); </code> to your config file to enable it. Just remember to never leave it on for long on a live blog. Since all pings fail this is likely not an issue with specific sitemap service, but with ping process itself. I think it might be HTTP requests failing for some reason, but there is no way to tell definitively from information you provided so far.
XML Sitemap Generator can't notify google and bing
wordpress
is there a way to allow admin users to add classes to individual menu items in the back end? we have done some individual javascripting and CSS using the title tag, but that is not flexible as it is visible to the end user, so the method is not suited effects needed to be applied to multiple items.
This is natively supported by WordPress. In the menus page, click "Screen Options" (in the upper right corner): Then check "CSS Classes": You will now have a "CSS Classes" Option for each menu item:
How to specify or extend the CSS-class of a menu item?
wordpress
Is there a way to change the text of the publish button on a custom post type to say some different? For example, Save instead of Publish. And also remove the draft button?
If you look into <code> /wp-admin/edit-form-advanced.php </code> , you will find the meta box: <code> add_meta_box('submitdiv', __('Publish'), 'post_submit_meta_box', $post_type, 'side', 'core'); </code> Note the <code> __('Publish') </code> – the function <code> __() </code> leads to <code> translate() </code> where you get the filter <code> 'gettext' </code> . There are two ways to handle your problem: 1. Address the string in a single specialized function (be sure to match the correct textdomain!) or 2. use a more generic approach. @Rarst has just now posted version 1, so I'll add version 2. :) <code> &lt;?php /* Plugin Name: Retranslate Description: Adds translations. Version: 0.1 Author: Thomas Scholz Author URI: http://toscho.de License: GPL v2 */ class Toscho_Retrans { // store the options protected $params; /** * Set up basic information * * @param array $options * @return void */ public function __construct( array $options ) { $defaults = array ( 'domain' =&gt; 'default' , 'context' =&gt; 'backend' , 'replacements' =&gt; array () , 'post_type' =&gt; array ( 'post' ) ); $this-&gt;params = array_merge( $defaults, $options ); // When to add the filter $hook = 'backend' == $this-&gt;params['context'] ? 'admin_head' : 'template_redirect'; add_action( $hook, array ( $this, 'register_filter' ) ); } /** * Conatiner for add_filter() * @return void */ public function register_filter() { add_filter( 'gettext', array ( $this, 'translate' ), 10, 3 ); } /** * The real working code. * * @param string $translated * @param string $original * @param string $domain * @return string */ public function translate( $translated, $original, $domain ) { // exit early if ( 'backend' == $this-&gt;params['context'] ) { global $post_type; if ( ! empty ( $post_type ) &amp;&amp; ! in_array( $post_type, $this-&gt;params['post_type'] ) ) { return $translated; } } if ( $this-&gt;params['domain'] !== $domain ) { return $translated; } // Finally replace return strtr( $original, $this-&gt;params['replacements'] ); } } // Sample code // Replace 'Publish' with 'Save' and 'Preview' with 'Lurk' on pages and posts $Toscho_Retrans = new Toscho_Retrans( array ( 'replacements' =&gt; array ( 'Publish' =&gt; 'Save' , 'Preview' =&gt; 'Lurk' ) , 'post_type' =&gt; array ( 'page', 'post' ) ) ); </code> You don't need to use the code as a plugin. Including it in your theme's functions.php will be enough. Update To remove the original Save button (not sure what the 'draft' button is), add the following code to your functions.php/a plugin: <code> add_action( 'admin_print_footer_scripts', 'remove_save_button' ); function remove_save_button() { ?&gt; &lt;script&gt; jQuery(document).ready(function($){$('#save-post').remove();}); &lt;/script&gt;&lt;?php } </code> Yes, it's ugly.
Change the text on the Publish button
wordpress
I'd like to implement a similar functionality as WP Categories screen in the Admin area. Where you can add category and it will appear in the list of all categories straight away. I have a CD custom post type and I would like to add tracks to a CD in the same way as WP Categories are added. So that after general CD info there will be an empty "New track info" form where a track's info is inserted and after hitting "Add track" - a track will appear under the general CD info, and again displaying an empty "New track info" form to add another track to a CD. (Hope that makes sense). Also, it will be grate if I could reorder track records by dragging and dropping. That's a lot of "wishing" that I don't know how to go on about. I'm a novice and unfortunately can't figure it out myself. I would really appreciate if people could point me on the right direction with this ... I would really appreciate any help! Many thanks, Dasha
first your form that calls the ajax must have the an action filed with the value of the ajax hook for example your ajax call is: <code> add_action('wp_ajax_show_all_tracks', 'show_all_tracks'); </code> the your form action field must be: <code> &lt;input type="hidden" name="action" value="show_all_tracks" /&gt; </code> thats for start' so as for adding tracks you need to add a function to add javascript to the track edit form or add it to your code by changing <code> function add_post_enctype() { echo ' &lt;script type="text/javascript"&gt; jQuery(document).ready(function(){ jQuery("#post").attr("enctype", "multipart/form-data"); jQuery("#post").attr("encoding", "multipart/form-data"); }); &lt;/script&gt;'; } </code> to <code> function add_post_enctype() { echo ' &lt;script type="text/javascript"&gt; jQuery(document).ready(function(){ jQuery("#post").attr("enctype", "multipart/form-data"); jQuery("#post").attr("encoding", "multipart/form-data"); jQuery("#Add Track").click(function() { jQuery.ajax({ type: "post",url: "&lt;?php echo admin_url('admin-ajax.php'); ?&gt;", data: { action: 'add_track', ad_type: jQuery( '#tr_name' ).val() , ad_type: jQuery( '#tr_time' ).val() , ad_type: jQuery( '#tr_lyrics' ).val() , _ajax_nonce: jQuery( '#nonce' ).val() , }, success: function(html){ //so, if data is retrieved, store it in html if (html.indexOf('ok') &gt; -1 || html.indexOf('true') &gt; -1) { alert('track added'); } } }); return false; }); }); &lt;/script&gt;';} </code> the create an ajax do action hook <code> add_action('wp_ajax_add_track', 'add_track'); </code> then the function itself to add the tracks: <code> function add_track(){ check_ajax_referer( "add_track" ); /* save to the custom field array that holds the track data. and return OK as string i know you can manage that*/ } </code> and last is change your form from: <code> &lt;form id="add-track-form" name="add-track-form" action="" method="post"&gt; &lt;input type="hidden" name="mytheme_meta_box_nonce" value="'&lt;?php wp_create_nonce(basename(__FILE__)) ?&gt;'" /&gt; &lt;?php foreach($this-&gt;_meta_box['form'] as $el){ $this-&gt;display_field($el); } ?&gt; &lt;input type="submit" id="add-track" name="add-track" value="Add Track" /&gt; </code> to <code> &lt;form id="add-track-form" name="add-track-form" action="" method="post"&gt; &lt;input type="hidden" name="nonce" id="nonce" value="&lt;?php echo wp_create_nonce( 'add_track' ); ?&gt;" /&gt; &lt;?php foreach($this-&gt;_meta_box['form'] as $el){ $this-&gt;display_field($el); } ?&gt; &lt;input type="submit" id="add-track" name="add-track" value="Add Track" /&gt; &lt;/form&gt; </code> hope this helps and its really more of a draft but it should get you in the right direction. ohad.
Ajax solution similar to WP Categories functioning in Admin area
wordpress
When displaying a category how can I tell what category it is? Say I'm on <code> http://www.example.com/category/quotes </code> , how can I get <code> quotes </code> aside from parsing the URL? I tried <code> get_the_category() </code> but it returns an array of all the categories of the first post shown in the page.
This should get you category object with ID, slug and rest of info: <code> $wp_query-&gt;get_queried_object(); </code>
How can I tell what category I'm in?
wordpress
I moved the blog I was working on from my development server (on DreamHost) to the client's server (some local host which they are unwilling to switch from). Everything seems to be working perfectly, except that users are not receiving their new user confirmation emails, or their lost password emails. I have Contact Form 7 installed, and that sends emails out perfectly, so I know the server is set up to send mail successfully. I have checked that I have the correct email address in General Settings and in the User Settings. I have tested a simple mail() script on the server, and that sends just fine: <code> &lt;?php $message = "Line 1\nLine 2\nLine 3"; $message = wordwrap($message, 70); mail('myemailhere@nospam.com', 'My Subject', $message); ?&gt; </code> PHP version is <code> 5.2.6-1+lenny9 </code> Where do I even begin with this? My google-fu is not strong today (I get a bunch of crappy posts that don't actually help)... I'd prefer not to have to resort to a plugin to fix this (although I'm happy to use a plugin to temporarily troubleshoot, if necessary).
Have you checked that wp_mail() works properly? CF7 might be using its own custom smtp interface or something like that, to work around issues in wp_mail().
How do I troubleshoot registration/password email errors?
wordpress
Using <code> wp_tag_cloud() </code> , how can I display a single tag cloud that incorporates both regular post tags and a custom taxonomy?
The following is a slightly modified version of the <code> wp_tag_cloud() </code> function: <code> function custom_wp_tag_cloud( $args = '' ) { $defaults = array( 'smallest' =&gt; 8, 'largest' =&gt; 22, 'unit' =&gt; 'pt', 'number' =&gt; 45, 'format' =&gt; 'flat', 'separator' =&gt; "\n", 'orderby' =&gt; 'name', 'order' =&gt; 'ASC', 'exclude' =&gt; '', 'include' =&gt; '', 'link' =&gt; 'view', 'taxonomy' =&gt; 'post_tag', 'echo' =&gt; true ); $args = wp_parse_args( $args, $defaults ); $tags = get_terms( $args['taxonomy'], array_merge( $args, array( 'orderby' =&gt; 'count', 'order' =&gt; 'DESC' ) ) ); // Always query top tags if ( empty( $tags ) ) return; foreach ( $tags as $key =&gt; $tag ) { if ( 'edit' == $args['link'] ) $link = get_edit_tag_link( $tag-&gt;term_id, $tag-&gt;taxonomy ); else $link = get_term_link( intval($tag-&gt;term_id), $tag-&gt;taxonomy ); if ( is_wp_error( $link ) ) return false; $tags[ $key ]-&gt;link = $link; $tags[ $key ]-&gt;id = $tag-&gt;term_id; } $return = wp_generate_tag_cloud( $tags, $args ); // Here's where those top tags get sorted according to $args $return = apply_filters( 'wp_tag_cloud', $return, $args ); if ( 'array' == $args['format'] || empty($args['echo']) ) return $return; echo $return; } </code> Use the <code> taxonomy </code> argument: <code> $args = array( 'taxonomy' =&gt; array( 'post_tag', 'custom_taxonomy' ) ); custom_wp_tag_cloud( $args ); </code>
How do I display a tag cloud with both post tags AND a custom taxonomy?
wordpress
I have an interesting problem I am trying to solve. Here is my situations: I have create a custom post type for "events". For each event post I require custom fields to be entered for the event start date/time. In addition, each event can be assigned to a custom taxonomy I have created specifically to assign each event to one or more "event categories" (my custom taxonomy). I have create a public template which calls all posts belong to this custom post type and am correctly filtering the query to ONLY display events were the event start/date and time is greater than todays date. All of the above is working correctly. The only thing I am currently having problems with is displaying all the events for a specific taxonomy term. In other words... along with each event listing I am including all terms associated with the event from my custom taxonomy (event categories). So, there issue here is that each taxonomy term (correctly) shows up as a link but when you select the term the corresponding terms archive page is not ordering the corresponding results by the event date/time custom field and it is not excluding events which are older than todays date. Based upon this page: http://codex.wordpress.org/images/1/18/Template_Hierarchy.png I have figure out that one is able to create a custom archive page for all terms belonging to a custom taxonomy by naming the archive file as follows: taxonomy-event_categories.php (where "event_categories") is the name for my custom taxonomy. Sooooooooo.... As mentioned the only thing I believe I need a solution for is the correct code to insert to achieve the two issues mentioned above. Here is the code I am using which works in display my event list correctly organized by the event start date/time while removing all events older than today. <code> &lt;?php //Get the metadata for each child page global $custom_metabox_event_dates; $meta1 = $custom_metabox_event_dates-&gt;the_meta(); $today = time(); $arrMonthNums = array("01" =&gt; "01", "02" =&gt; "02", "03" =&gt; "03", "04" =&gt; "04", "05" =&gt; "05", "06" =&gt; "06", "07" =&gt; "07", "08" =&gt; "08", "09" =&gt; "09", "10" =&gt; "10", "11" =&gt; "11", "12" =&gt; "12"); $arrMonthNames = array("01" =&gt; "JANUARY", "02" =&gt; "FEBRUARY", "03" =&gt; "MARCH", "04" =&gt; "APRIL", "05" =&gt; "MAY", "06" =&gt; "JUNE", "07" =&gt; "JULY", "08" =&gt; "AUGUST", "09" =&gt; "SEPTEMBER", "10" =&gt; "OCTOBER", "11" =&gt; "NOVEMBER", "12" =&gt; "DECEMBER"); query_posts('post_type=events&amp;showposts=-1&amp;meta_key=' . $custom_metabox_event_dates-&gt;get_the_name('combined_datetime') . '&amp;meta_compare=&gt;=&amp;meta_value=' . $today . '&amp;orderby=meta_value&amp;order=ASC'); ?&gt; &lt;?php if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;?php //Get all Events and run a check against current date global $custom_metabox_event_dates; global $custom_metabox_event_details; $meta1 = $custom_metabox_event_dates-&gt;the_meta(); $meta2 = $custom_metabox_event_details-&gt;the_meta(); $meta_start_date = $meta1['event_start_date']; $meta_end_date = $meta1['event_end_date']; $meta_start_time = $meta1['event_start_time']; $meta_end_time = $meta1['event_end_time']; $meta_location_city = $meta2['event_location_city']; $meta_event_type = $meta2['event_type']; $show_date = strtotime($meta_start_date); if($show_date &gt;= $today) { ?&gt; &lt;?php $show_month = date('m', $show_date); if ($arrMonthNums[$show_month] == $show_month) { echo "&lt;div id='category-events-list-month-title'&gt;EVENTS IN ".$arrMonthNames[$show_month]."&lt;/div&gt;"; $arrMonthNums[$show_month] = "printed"; } if($show_date == $today) { ?&gt; &lt;?php } ?&gt; &lt;div id="category-events-list-container-group"&gt; &lt;div id="category-events-list-container-left"&gt; &lt;div id="event-entry-list-date"&gt;&lt;?php echo $meta_start_date ?&gt;&lt;/div&gt; &lt;div id="event-entry-list-time"&gt;&lt;?php echo $meta_start_time ?&gt; - &lt;?php echo $meta_end_time ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;div id="category-events-list-container-right"&gt; &lt;div id="category-articles-list-title"&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php echo the_title(); ?&gt;&lt;/a&gt;&lt;/div&gt; &lt;div id="category-articles-list-excerpt"&gt; &lt;span&gt;EVENT TYPE: &lt;?php echo get_the_term_list($post-&gt;ID, 'event_types', '', ', ',''); ?&gt; &lt;/span&gt;&lt;br /&gt; &lt;span&gt;LOCATION: &lt;?php echo $meta_location_city ?&gt;&lt;/span&gt;&lt;br /&gt; &lt;?php echo substr(get_the_excerpt(),0,250); echo '... ' ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;?php endwhile; endif; ?&gt; </code> Please keep in mind that I am not asking how to change the query above so it just displays posts for one term... Rather, somehow I need to get the archive page to recognize which term was clicked and essentially pass that through the query along with the ordering/filtering I am doing above. I am assuming this is probably a simple answer which involves the "loop" which I have yet to master. UPDATED Here is the code for the archive page which needs to be modified so when a term is clicked from the results list above so it ONLY shows the same results but only for the term selected AND sorted by date/time AND eliminating any events earlier than todays date. <code> &lt;?php if (have_posts()) : ?&gt; &lt;?php $post = $posts[0]; // Hack. Set $post so that the_date() works. ?&gt; &lt;?php /* If this is a category archive */ if (is_category()) { ?&gt; &lt;div id="category-title-articles"&gt;Archive for the &amp;#8216;&lt;?php single_cat_title(); ?&gt;&amp;#8217; Category&lt;/div&gt; &lt;?php /* If this is a tag archive */ } elseif( is_tag() ) { ?&gt; &lt;div id="category-title-articles"&gt;Posts Tagged &amp;#8216;&lt;?php single_tag_title(); ?&gt;&amp;#8217;&lt;/div&gt; &lt;?php } ?&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;div id="category-articles-list-container-group"&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;div class="navigation"&gt; &lt;div class="alignleft"&gt;&lt;?php next_posts_link('&amp;laquo; Older Entries') ?&gt;&lt;/div&gt; &lt;div class="alignright"&gt;&lt;?php previous_posts_link('Newer Entries &amp;raquo;') ?&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php else : if ( is_category() ) { // If this is a category archive printf("&lt;h2 class='center'&gt;Sorry, but there aren't any posts in the %s category yet.&lt;/h2&gt;", single_cat_title('',false)); } else if ( is_date() ) { // If this is a date archive echo("&lt;h2&gt;Sorry, but there aren't any posts with this date.&lt;/h2&gt;"); } else if ( is_author() ) { // If this is a category archive $userdata = get_userdatabylogin(get_query_var('author_name')); printf("&lt;h2 class='center'&gt;Sorry, but there aren't any posts by %s yet.&lt;/h2&gt;", $userdata-&gt;display_name); } else { echo("&lt;h2 class='center'&gt;No posts found.&lt;/h2&gt;"); } get_search_form(); endif; ?&gt; </code> Thanks in advance, Chris
The most efficient way is probably to hook into the <code> pre_get_posts </code> action and add your time comparison there. This way you don't have to worry about the rest or the query options as they will still work. It should look like this (untested), and be placed in a plugin or theme functions file (not in the page template file, the query will already have been executed): <code> add_action('pre_get_posts', 'add_event_date_criteria'); function add_event_date_criteria(&amp;$query) { // We only want to filter on "public" pages // You can add other selections, like here: // - Only on a term page for our custom taxonomy if (!is_admin() &amp;&amp; is_tax('event_types')) { global $custom_metabox_event_dates; $query-&gt;set('meta_key', $custom_metabox_event_dates-&gt;get_the_name('combined_datetime')); $query-&gt;set('meta_compare', '&gt;='); $query-&gt;set('meta_value', time()); $query-&gt;set('orderby', 'meta_value'); $query-&gt;set('order', 'asc'); } } </code> You define the scope of this extra filter with the contents of the <code> if() </code> test. Currently we don't do it on admin pages (you wouldn't be able to access old content), and only do it on specific taxonomy pages. You should find out for yourself how wide or how narrow you want this. If you can't solve it this way, you can do the main query again without losing the "page specific query" by adding the different query vars to the main <code> $wp_query </code> objects, and calling <code> $wp_query-&gt;get_posts() </code> again. Since we did not call <code> $wp_query-&gt;parse_query() </code> , the page-specific query args will not be cleared. It would look like this: <code> global $custom_metabox_event_dates; $wp_query-&gt;set('meta_key', $custom_metabox_event_dates-&gt;get_the_name('combined_datetime')); $wp_query-&gt;set('meta_compare', '&gt;='); $wp_query-&gt;set('meta_value', time()); $wp_query-&gt;set('orderby', 'meta_value'); $wp_query-&gt;set('order', 'asc'); $wp_query-&gt;get_posts(); </code> You can place this in your template files (not <code> functions.php </code> , but <code> taxonomy-event_types.php </code> or other "real" template files). Remember that you "throw away" one database call this way, so it is not the most optimal solution.
Custom Taxonomy Template Post List with Sort Order
wordpress
I would like make a custom role that can only access a custom content type that I'm going to be creating in the admin. Is that possible and does any know of any examples or tutorias that I should check out to get started? Thanks, Paul
The <code> register_post_type </code> has a <code> capabilities </code> (or simple version: <code> capability_type </code> ) that you can use to specify a separate capability to create and edit posts of this type. If you set this, you can create a new role that has the capability to edit these custom posts, but not regular posts.
Can I make user role that can only access a certian content type?
wordpress
I'm creating som custom templates in Wordpress and I'm passing some data in the URL's. Currently my URL looks like this: http://www.mysite.com/designers/?id=43&amp;name=designer+name The URL contains designer ID and designer name. I would really like to use this: http://www.mysite.com/designers/designer+name/ My permalink structure is set to <code> /%category%/%postname%/ </code> My .htaccess file looks like this: <code> # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code> I've looked at http://codex.wordpress.org/Using_Permalinks , but not become any wiser. I got two questions: Is there any point in changing the above URL regarding SEO How can I get the "pretty" URL? UPDATE I'm adding some more info for clarification. I'm developing the site myself The template is 100% custom template Based on info from $_GET, I load data from my custom DB table and display this on page My site has an avarage of between 3-400 unique visitors per day. At peak I have 2000 unique visitors per day. I'm developing an online fashion magazine My URL is currently being created like this: <code> Url = get_permalink().'?bid='.$brand-&gt;id.'&amp;name='.$brand-&gt;name; </code> I've used similar method here: http://storelocator.no/search/?brandID=4673&amp;storeID=0&amp;brand=Moods+of+Norway Using Custom Post Type was an option I considered, but I needed my own table structurem because designers / brands are linked up against galleries (and more links to other tables to come). So saving brands data in WP POST table was not going to work. So I need to know this: What do I need to do with my Permalink structure? What do I need to do with my .htaccess file?
I don't know (or didn't know) much about the rewrite rules myself (but it seems nobody does ), but based on some other answers here, I got this to work. We add a new rewrite rule that matches <code> designers/designer_name/ </code> . We "flush" the rewrite rules so they get saved to the database, but make sure to do this only once, since it is an expensive operation. Now, we set up a pattern that will match our page and save the extra part in the <code> designer_name </code> query variable. Since WordPress does not know it must look at this variable, we hook into the <code> query_vars </code> filter and tell it to look at that too. Now, in the <code> page-designers.php </code> theme file, we can do <code> get_query_var('designer_name') </code> and it will give you the designer name. If you want extra stuff like paging ( <code> designer/designer_name/page/2 </code> ), you need to add an extra rewrite rule for that (or feeds, or whatever that starts with <code> designer/designer_name </code> ). But the basic stuff should work. <code> &lt;?php /* Plugin Name: WPA 3537 Plugin URI: stackexchange-url Need help with friendly URL's in Wordpress Version: 1.0 Author: Jan Fabry */ register_activation_hook(__FILE__, 'wpa3537_flush_rules'); function wpa3537_flush_rules() { add_rewrite_rule('designers/([^/]+)', 'index.php?pagename=designers&amp;designer_name=$matches[1]', 'top'); flush_rewrite_rules(false); } add_filter('query_vars', 'wpa3537_query_vars'); function wpa3537_query_vars($query_vars) { $query_vars[] = 'designer_name'; return $query_vars; } </code>
Need help with friendly URL's in Wordpress
wordpress
I have a .pot file that came with my Wordpress theme. Now I want to add strings to it, that weren't there in the original theme. How do I do that? Do I have to update the .pot file? but 1) How do I do that, and 2) How do I make sure that the strings that were translated won't get erased? (I'm currently using Poedit and I can't see a feature to add a string.)
I am using http://wordpress.org/extend/plugins/codestyling-localization/ Give it a chance i suggest :)
How do I add a new string to a .po or .pot file?
wordpress
The "word_count" function below returns different values depending on where its called from. Why? <code> add_action('save_post', 'my_custom_save', 10, 2); function myPlugin($post) { global $rockScore; global $text; $text = strip_tags($post-&gt;post_content); echo word_count($post); //returns "350" } function word_count($post) { global $text; $word_count = explode(' ', $text); $word_count = count($word_count); return $word_count; } function my_custom_save($postID, $post){ if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return $postID; } else { if($parent_id = wp_is_post_revision($postID)) { $postID = $parent_id; } echo word_count($post);die; //still returns "1" } } register_activation_hook(__FILE__, 'myPlugin'); </code>
Probably revisions. Check $post-> post_type.
Function returns different value when called from 'save_post' than when called on page load
wordpress
I'm not able to find the action handler page for the cforms plugin anywhere. I want to write some function in the action handler page of the cforms plugin using the post values.
In the main cforms plugin folder, find the file called <code> my-functions.php </code> . You can add functions to that file as needed. Its pretty well-commented. What you want to do is add a function called <code> my_cforms_logic </code> or <code> my_cforms_action </code> , which get triggered at several different hooks during form submission and processing. According to the docs, you can move the <code> my-functions.php </code> file (annd any css tweaks you make) into a separate folder called “cforms-custom” to protect your customizations from future upgrades...
cannot find cforms action handler page
wordpress
How can I best make WP link to the large version of the image in all posts (instead of the original one) without modifying all the data in the database? I'm probably looking for the best filter to attach to.
You can modify the content that is displayed on the site by hooking in to the <code> the_content </code> filter. However, this is where the hard work starts. You need to identify all the images, figure out the links to the large sizes, and replace them. This could be a costly operation, so you might want to save the post back to the database and set a (hidden) meta key to indicate you don't have to do it again next time. Now, some hints on how to do this: to get info on the attached images, you use <code> get_children() </code> and specify you only want attachments: <code> get_children($post-&gt;ID, array('post_type' =&gt; 'attachment')) </code> . Attachments are stored like posts, and you can request different sizes with <code> wp_get_attachment_image_src() </code> by passing the requested size ( <code> "large" </code> ).
Link to large image version instead of original?
wordpress
I have several functions that are called from inside a <code> save_post </code> function. However, all of the functions that use the <code> $post </code> object are returning incorrect values because it appears that the default value being passed to <code> save_post </code> is the post ID rather than the post object. How can I pass the post object to the <code> save_post </code> function in addition to the post ID? <code> add_action('save_post', 'my_save_function'); </code>
Do: <code> add_action('save_post', 'my_save_function', 10, 2); </code> And the <code> $post object </code> will be passed as second argument to your function: <code> function my_save_function($post_ID, $post) { </code>
How can I pass $post object to 'save_post' add_action?
wordpress
Can I use wp_schedule_event() to set up a cron job from within a widget? I tried, but I can't make it work, The problem seems to be the $hook parameter. The function I'm trying to hook is located within the widget class so my guess is that WP can't find it. neither of these work: <code> wp_schedule_event(time(), 'daily', 'my_widget_cron'); wp_schedule_event(time(), 'daily', array(&amp;$this, 'my_widget_cron')); </code> any ideas?
<code> wp_schedule_event </code> takes a hook as parameter, not a function. Try: <code> wp_schedule_event(time(), 'daily', 'my_daily_event'); add_action('my_daily_event', array(&amp;$this, 'my_widget_cron')); if ( !wp_next_scheduled( 'my_daily_event' ) ) { wp_schedule_event(time(), 'hourly', 'my_daily_event') } </code> If you remove the widget from the sidebar, the cron will still continue to run. You can run the following code (outside of the widget class) to clear it: <code> if ( !is_active_widget('your_widget_callback_function') &amp;&amp; wp_next_scheduled( 'my_daily_event' ) ) { wp_clear_scheduled_hook('my_daily_event'); } </code>
Schedule cron event from widget
wordpress
You can create a new page/post for this and set a custom publish date for it, but now the question is: How can you make a page to be available for a specified amount of time and replace it with something else after this? One usage example would be if you want to do a limited time offer and after this you want to replace or hide the page. As you can imagine I'm looking for a solution that would allow you schedule this, so you could be in vacation when the change happens ;)
If you made your special offers a custom post type you could set the 'scheduled' date to the day you wanted it to expire then use this code to auto publish it on schedule after you've changed the scheduled date. The 'future_show' line goes with my 'show' custom post type so if you had a 'deal' custom post type it would say 'future_deal'. <code> &lt;?php function sfn_setup_future_hook() { // Replace native future_post function with replacement remove_action('future_show','_future_post_hook'); add_action('future_show','publish_future_post_now'); } function publish_future_post_now($id) { wp_publish_post($id); } add_action('init', 'sfn_setup_future_hook'); ?&gt; </code> You can then set the post to expire if it's older than today on the server with the code below. It hooks into WordPress cron so you're not running it all the time but you'll notice a line commented out that runs it on init so you can test it. For testing comment out the first 3 lines and use the init action. Don't do this on production though. <code> &lt;?php // setting posts with current date or older to draft if (!wp_next_scheduled('sfn_expire_hook')){ wp_schedule_event( time(), 'hourly', 'sfn_expire_hook'); } add_action( 'sfn_expire_hook', 'sfn_show_expire'); function sfn_show_expire(){ global $wpdb; $server_time = date('mdy'); $result = $wpdb-&gt;get_results("SELECT * FROM $wpdb-&gt;posts WHERE post_type = 'show' AND post_status = 'publish'"); if( !empty($result)) foreach ($result as $a){ $show_time = get_the_time('mdy', $a-&gt;ID); if ( $server_time &gt; $show_time ){ $my_post = array(); $my_post['ID'] = $a-&gt;ID; $my_post['post_status'] = 'draft'; wp_update_post( $my_post ); } } // end foreach } // add_action( 'init', 'sfn_show_expire' ); ?&gt; </code> Don't forget to change my function prefix (sfn) to your own just to sandbox it's function from anything else. Edit I just also thought that you could change the SQL query to grab posts in a category of 'deal' and it would work the same way. Creating an entire post type then including it in the site/blog may be more work than is needed.
How to create pages that do change or expire after a specified amount of time?
wordpress
I create user with wp_create_user,after succesfully creating a user I need to set his status to be logged in?How to set his status to be logged in ?
Use <code> wp_signon() </code> . Ex: <code> $creds = array(); $creds['user_login'] = 'example'; $creds['user_password'] = 'plaintextpw'; $creds['remember'] = true; $user = wp_signon( $creds, false ); if ( is_wp_error($user) ) echo $user-&gt;get_error_message(); </code> See Codex for more details about <code> wp_signon() </code> .
Set user loggin status?
wordpress
When turning opn WP_DEBUG and WP_DEBUG_DISPLAY, I get tons of warnings and notices. I have tried to remove the warnings by doing a @ini_set('error_reporting', 1) to only show E_ERROR, but I still get tons of E_NOTICE. Is there someway to prevent all the warnings and notices and only show errors in HTML output?
Turn off WP_DEBUG because it overwrite your <code> ini_set </code> .
Prevent notice and warnings in error_reporting?
wordpress
I'm using my wordpress.com blog (not wordpress.org) and want to change the language of the blog. How can I do this?
I found it here http://en.support.wordpress.com/language-settings/
How to change the language of a wordpress.com blog?
wordpress
Back in May, I recall seeing a post on the WordPress Development blog by Alex M (Viper007bond.com) where he added functionality for Automatic Ticket/Revision/Diff Linking which allows for linking to Trac tickets, Trac revisions, and Trac diff comparisons. I am wanting to do the same thing with an internal WordPress blog and Trac that I have for my business. I haven't seen where this was released as a WordPress plugin so I was hoping that people could point me in the right direction on how to do this in how to do this integration between Trac and WordPress. Thanks.
Here's the source of the functionality. It's just a content filter and some basic regex that one of my coworkers at Automattic wrote. <code> add_filter( 'the_content', 'markup_wporg_links' ); add_filter( 'comment_text', 'markup_wporg_links' ); function markup_wporg_links( $content ) { $find = array( '/(\ |^)#(\d{3,6})(\b|$)/i', // core trac ticket #1234-core in http://core.trac.wordpress.org/ticket/ '/(\ |^)r(\d{3,6})(\b|$)/i', // core changeset r1234-core in http://core.trac.wordpress.org/changeset/1234 '/(\ |^)diff:@(\d{3,6}):(\d{3,6})(\b|$)/i', // core diff diff-core:@20:30 https://core.trac.wordpress.org/changeset?new=30&amp;old=20 ); $replace = array( '&lt;a href="http://core.trac.wordpress.org/ticket/$2"&gt;$0&lt;/a&gt;', // core trac ticket '&lt;a href="http://core.trac.wordpress.org/changeset/$2"&gt;$0&lt;/a&gt;', // core trac changeset '&lt;a href="http://core.trac.wordpress.org/changeset?new=$3&amp;old=$2"&gt;$0&lt;/a&gt;', // core diff ); preg_match_all( '#[^&gt;]+(?=&lt;[^/]*[^a])|[^&gt;]+$#', $content, $matches, PREG_SET_ORDER ); foreach ( $matches as $val ) $content = str_replace( $val[0], preg_replace( $find, $replace, $val[0] ), $content ); return $content; } </code> Modify it to suit your needs.
How to Integrate Trac and WordPress (as done on the WP Development blog)?
wordpress
When you click on "Posts" or "Pages", you get a paged listing of your posts or pages with the following columns: Title | Author | Categories | Tags | Date I have a plugin which gives an SEO score for each post and page. I would like to add two columns to the list view when viewing posts or pages, one for the post's "seo score" and one for the posts "seo keyword" so that the column listing becomes: Title | Author | Categories | Tags | Date | SEO Score | SEO Keywords
You add the column using the <code> manage_posts_column </code> filter , where you add two new array elements with a custom key name and the header name as the value. <code> add_filter('manage_posts_columns', 'add_seo_columns', 10, 2); function add_dummy_column($posts_columns, $post_type) { $posts_columns['seo_score'] = 'SEO score'; $posts_columns['seo_keyword'] = 'SEO keyword'; return $posts_columns; } </code> The function that displays each row, <code> _post_row() </code> , then fires the <code> manage_posts_custom_column </code> action for each column that it does not know. You hook into this function to display your own data. <code> add_action('manage_posts_custom_column', 'display_seo_columns', 10, 2); function display_seo_columns($column_name, $post_id) { if ('seo_score' == $column_name) { echo 'SEO score for post with ID ' . $post_id; } if ('seo_keyword' == $column_name) { echo 'SEO keyword for post with ID ' . $post_id; } } </code>
How can I add columns to the post edit listing to show my custom post data?
wordpress
I want to show a dropdown in the option's panel for choosing a "featured product category" which is a custom taxonomy. I do this way: <code> register_taxonomy("Catalogs", array("kmproduct"), array("hierarchical" =&gt; true, "label" =&gt; "Catalogs", "singular_label" =&gt; "catalog", "rewrite" =&gt; true )); </code> and in my <code> theme_options.php </code> i have: <code> ... array( "name" =&gt; "Homepage featured category", "desc" =&gt; "Choose a category from which featured posts are drawn", "id" =&gt; $shortname."_feat_cat", "type" =&gt; "select", "options" =&gt; $wp_tax, "std" =&gt; "Choose a category"), </code> and I can't get the taxonomies list: <code> $args=array( 'name' =&gt; 'Catalogs'); $output = 'names'; // or objects $taxonomies = get_taxonomies($args,$output); $wp_tax = array(); foreach ($taxonomies as $category_list ) { $wp_tax[$category_list-&gt;ID] = $category_list-&gt;name; } array_unshift($wp_tax, "Choose a category"); </code> What's wrong? I can't get it to work :(
A taxonomy is a group of terms . I think you registered a taxonomy Catalogs , and now you want to list all terms in this taxonomy. You do that with the function <code> get_terms() </code> , not <code> get_taxonomies() </code> . So your <code> $wp_tax </code> array should be filled like this: <code> $wp_tax = array(-1 =&gt; 'Choose a category'); $catalog_terms = get_terms('Catalogs'); if ($catalog_terms) { foreach ($catalog_terms as $catalog_term) { $wp_tax[$catalog_term-&gt;term_id] = $catalog_term-&gt;name; } } </code>
List taxonomies in a dropdown in theme's option panel
wordpress
I'm getting this message each time I activate my plugin: The plugin generated 80 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin. The only way I can suppress the message is to wrap my activation function code in a conditional (**see below). How should I rewrite this to prevent the alert? <code> function myPlugin($post) { echo "Whatever is here throws an unexpected output alert when the plugin isa activated"; //I can place code here without issue, but anything that is output via echo throws the alert. } register_activation_hook(__FILE__, 'myPlugin'); </code> Wrapping the function code in the conditional suppresses the alerts: <code> function myPlugin($post) { global $pagenow; if ( is_admin() &amp;&amp; $pagenow !== 'plugins.php' ) { echo "No more alerts when its wrapped this way"; } } ?&gt; </code>
Hi @Scott B : When you get this kind of message is usually means your plugin had a syntax error and was generating that kind of error messages because of how the loading on activation is handled, i.e. HTTP headers are sent after the error message is display. Your plugin's error message is loaded in an <code> &lt;iframe&gt; </code> ; have you done a "View Source" on the <code> &lt;iframe&gt; </code> to see if there's an obvious error message? Also, you should consider getting an HTTP debugger which can help with this kind of things: Windows has the excellent and free Fiddler . For Mac OS X there's HTTPScoop (not great, but inexpensive at US$15 .) There's also Charles for Windows/Mac/Linux ( US$50 - I may break down and buy it one day. Wish I could get Fiddler on Mac, but since Fiddler comes from Microsoft I don't hold my breath.) UPDATE Based on the comments below, here's a screen of me using "Inspect Element" in Safari (but you can do the same with Chrome and FireFox, or similar with IE and the Web Developer Toolbar): You can grab that <code> &lt;iframe&gt; </code> d URL and load it directly in your browser to make the process of debugging easier. Something in your plugin is sending q <code> header() </code> after an error message is thrown, that's what that error message means. BTW, I just added a stray character and hence syntax error in my plugin to get it to throw an error which is why you see the error as you do.
The plugin generated 80 characters of unexpected output!
wordpress
I am trying to use the FaceBook application RSS Grafitti to link my RSS feed from my Wordpress installation to a FaceBook Fanpage. It finds the feed OK, but cannot post to the Fan page because there is apparently no pubDate field in the RSS feed. I am not even sure where to find the file to edit in my WordPress installation. I have WordPress 3.0.1 installed on a shared Linux host.
Try feeding the app an atom feed instead. (i.e. /feed/atom/ instead of /feed/.) The needed field(s) might be in there. Else, there are a few hooks to add them via plugins (see the wp-includes/feed-*.php files).
Adding pub_Date to an RSS feed hosted on Wordpress
wordpress
What is the best way of getting a custom field value from a page which is not the one currently displayed? I know the title of the page i want to get custom field value from, but not the pageID. Thanks!
Use: <code> $meta = get_post_meta($id, $key, $single); </code> With $single set to true if you don't want WP to return an array for unique meta keys.
Get custom field value from not-current page
wordpress
Is there a way to add a custom field value (if it exists) to the permalink?
Here's how I'd do it. I'm just going to say, I haven't tested this code at all, so I don't know if it even works. It's more of a starting point for you. <code> function jpb_custom_meta_permalink( $link, $post ){ $post_meta = get_post_meta( $post-&gt;ID, '&lt;insert your meta key here&gt;', true ); if( empty( $post_meta ) || !is_string( $post_meta ) ) $post_meta = '&lt;insert your default value (could be an empty string) here&gt;'; $link = str_replace( '!!custom_field_placeholder!!', $post_meta, $link ); return $link; } add_filter( 'post_link', 'jpb_custom_meta_permalink', 10, 2 ); </code> You would also have to go to your permalinks and change them to include <code> '!!custom_field_placeholder!!' </code> , like so: <code> '/%year%/%monthnum%/!!custom_field_placeholder!!/%postname%/' </code> This will not add any significance to your permalinks, merely text. If you need to add meaning to the text that goes there, that's a lot more work.
Custom field values in permalink
wordpress
I would like to add a "Click to download" button to one of my WordPress plugins, and I'm not sure which hook to use. So far, hooking 'admin_init' to this code seems to work: <code> header("Content-type: application/x-msdownload"); header("Content-Disposition: attachment; filename=data.csv"); header("Pragma: no-cache"); header("Expires: 0"); echo 'data'; exit(); </code> This seems to work, but I just want to see if there is a best practice out there. Thanks, Dave
Hi @Dave Morris : If I understand you correctly you want to have a URL something like the following whose response to the browser will be the content you generate, i.e. your <code> .CSV </code> file and no generated content from WordPress? <code> http://example.com/download/data.csv </code> I think you are looking for the <code> 'template_redirect' </code> hook. You can find <code> 'template_redirect' </code> in <code> /wp-includes/template-loader.php </code> which is a file all WordPress developers should become familiar with; it's short and sweet and routes every non-admin page load so be sure to take a look at it. Just add the following to your theme's <code> functions.php </code> file or in another file that you <code> include </code> in <code> functions.php </code> : <code> add_action('template_redirect','yoursite_template_redirect'); function yoursite_template_redirect() { if ($_SERVER['REQUEST_URI']=='/downloads/data.csv') { header("Content-type: application/x-msdownload",true,200); header("Content-Disposition: attachment; filename=data.csv"); header("Pragma: no-cache"); header("Expires: 0"); echo 'data'; exit(); } } </code> Note the test for the <code> '/downloads/data.csv' </code> URL by inspecting <code> $_SERVER['REQUEST_URI'] </code> . Also note the added <code> ,true,200 </code> to your <code> header() </code> call where you set the <code> Content-type </code> ; this is because WordPress will have set the <code> 404 </code> "Not Found" status code because it doesn't recognize the URL. It's no problem though as the <code> true </code> tells <code> header() </code> to replace the <code> 404 </code> WordPress had set and to use the HTTP <code> 200 </code> "Okay" status code instead. And here's what it looks like in FireFox ( Note the screenshot doesn't have a <code> /downloads/ </code> virtual directory because after taking and annotating the screenshot it just seemed like a good idea to add a <code> '/downloads/' </code> virtual directory): UPDATE If you want the download to be handled from a URL that is prefixed with <code> /wp-admin/ </code> to give the user the visual indication that it is protected by a login you can do that as well; the description of one way follows. I encapsulated into a class this time, called <code> DownloadCSV </code> , and to created a user "capability" called <code> 'download_csv' </code> for the <code> 'administrator' </code> role (read about Roles and Capabilities here ) You could just piggyback off of the predefined <code> 'export' </code> role if you like and if so just search &amp; replace <code> 'download_csv' </code> with <code> 'export' </code> and remove the <code> register_activation_hook() </code> call and the <code> activate() </code> function. By the way, the need for a activation hook is one reason why I moved this to a plugin instead of keeping in the theme's <code> functions.php </code> file.* I also added a "Download CSV" menu option off the "Tools" menu using <code> add_submenu_page() </code> and linked it to the <code> 'download_csv' </code> capability. Lastly I chose the <code> 'plugins_loaded' </code> hook because it was the earliest appropriate hook I could use. You could use <code> 'admin_init' </code> but that hook is run much later (1130th hook call vs. the 3rd hook call) so why let WordPress do more throw-away work than it needs to? (I used my stackexchange-url ("Instrument Hooks plugin") to figure out which hook to use.) In the hook I check to ensure my URL starts with <code> /wp-admin/tools.php </code> by inspecting the <code> $pagenow </code> variable, I verify that <code> current_user_can('download_csv') </code> and if that passes then I test <code> $_GET['download'] </code> to see if it contains <code> data.csv </code> ; if yes we run practically the same code as before. I also remove the <code> ,true,200 </code> from the call to <code> header() </code> in the previous example because here WordPress knows it is a good URL so didn't set the 404 status yet. So here is your code: <code> &lt;?php /* Plugin Name: Download CSV Author: Mike Schinkel Author URI: http://mikeschinkel.com */ if (!class_exists('DownloadCSV')) { class DownloadCSV { static function on_load() { add_action('plugins_loaded',array(__CLASS__,'plugins_loaded')); add_action('admin_menu',array(__CLASS__,'admin_menu')); register_activation_hook(__FILE__,array(__CLASS__,'activate')); } static function activate() { $role = get_role('administrator'); $role-&gt;add_cap('download_csv'); } static function admin_menu() { add_submenu_page('tools.php', // Parent Menu 'Download CSV', // Page Title 'Download CSV', // Menu Option Label 'download_csv', // Capability 'tools.php?download=data.csv');// Option URL relative to /wp-admin/ } static function plugins_loaded() { global $pagenow; if ($pagenow=='tools.php' &amp;&amp; current_user_can('download_csv') &amp;&amp; isset($_GET['download']) &amp;&amp; $_GET['download']=='data.csv') { header("Content-type: application/x-msdownload"); header("Content-Disposition: attachment; filename=data.csv"); header("Pragma: no-cache"); header("Expires: 0"); echo 'data'; exit(); } } } DownloadCSV::on_load(); } </code> And here's a screenshot of the activated plugin: And finally here's a screenshot of triggering the download:
How can I force a file download in the WordPress backend?
wordpress
How can I make a separate RSS feed for each custom post type? I had searched the net for it and found suggestions to do something like this: http://www.yoursite.com/feed/?post_type=book I tried the above, but it just didn't work! It only takes me back to the custom post type archive page again... Does anybody knows where I went wrong or what I am missing??? FYI, I used the Custom Post Permalinks plugin to allow post type specific permalinks for post type archive pages. Not sure if this may affect the RSS feed problem. Cheers!
Okay, thanks to all who contributed to answering my question, but I had finally figured out the solution to my problem. Sorry for being naive but it turned out that I had a template_redirect action added to direct anything that's related to my post types to their respective template files . Something like this: <code> function my_template_redirect() { global $wp, $wp_query; if ( ( $wp-&gt;query_vars["post_type"] == "news" ) &amp;&amp; !is_single() ) { if (have_posts()) { include(TEMPLATEPATH . '/news.php'); die(); } else { $wp_query-&gt;is_404 = true; } } } add_action("template_redirect", 'my_template_redirect'); </code> It, apparently, also redirected my post-type feeds to the template files, thus "it only takes me back to the custom post type archive page again...' So I just added an extra filter to exclude feeds from this redirection, that is, I added !is_feed() in the if statement: <code> if ( ( $wp-&gt;query_vars["post_type"] == "news" ) &amp;&amp; !is_single() &amp;&amp; !is_feed() ) </code> ...and the feeds work as they should be again. I knew there was something wrong with the theme... Thanks again for the help, guys! :)
How to Make a Separate RSS Feed for Each Custom Post Type
wordpress
I used to have a blog on wordpress.com, now I've created my own site (using wordpress of course), on a privately hosted domain. I used to have a lot more traffic hitting my blog on wordpress.com than on my new site. I can see some other sites (not subdomains on wordpress.com) listed in "freshly pressed" rss feed. How can I do that on my site?
I just figured that this can be done with an Offsite Redirect upgrade. It's a paid service (12$ per year), so I won't try it for now, however, for the sake of stackexchange Q/A, I would like to get a comment from someone who actually used this.
"Connect" my personal website to wordpress.com
wordpress
I want this question to turn into a more of a wiki because people often have this question. What do you think are some useful and must-have plugins for a wordpress-based site? Currently, I'm in the early stages of setting up a blog and I'm looking around for great plugins and some good tips. Please do include one or more. Also, if it's already there, upvote it.
These are all plugins that I've used, and while I'm sure there's a lot of good plugins I've missed, but these are ones I've had experience with and would recommend as enhancing your WordPress blog. Akismet - this is included with WordPress and is (in my opinion) one of the essential plugins you will need once you start to receive pretty much any traffic - the bots won't be far behind. While it's not perfect, it goes a reasonably good way towards expunging the spam. All in One SEO - Does what it says on the tin. Some of the <code> &lt;meta&gt; </code> tags generated are ignored by many search engines now but most of the options inside of here will benefit you in some way or another. Contact Form 7 - Makes it really easy to add a contact form to your site, with the field that you want, not necessarily the 'standard' ones. For more advanced needs, it's possible to configure multiple forms. Offers easy integration with reCAPTCHA and Akismet. FD Feedburner - Feedburner is a really great tool for gauging statistics related to your feeds. This plugin handles the redirection of your feeds to Feedburner, and requires next-to-no configuration. Google Analyticator - This plugin makes it easy to add Google Analytics tracking to your blog, and includes dashboard integration. Also supports link tracking, so you can see the direction in which people left your blog. Google XML Sitemaps - Generates an XML sitemap of your sites contents. It's possibly one of the best ways to ensure that Google (+ others) indexes all of your sites content. Sitemaps are automatically built when changes are made, and search engines are pinged, which notifies them of the changes. It also has a pretty comprehensive set of options, meaning you can change almost everything about the generated sitemap. W3 Total Cache - W3TC is an awesome plugin for helping WordPress scale. It packs some pretty impressive features, including the redirection of your resources to a CDN (along with syncing the two) and the static-caching of your posts.
What are good plugins for beginners?
wordpress
I'm trying to have spacing show up between a paragraph and heading in the following excerpt: In my article series on handling extracurriculars, I coined the term Sovereign Zen philosophies. It builds off of Cal Newport’s Zen Valedictorian philosophy . Before you criticize this article as being a copycat, there are some subtle differences between both philosophies, namely the self-protective critical thinking components, and their applicability beyond schooling career. Definition Zen Valedictorian: A way of living to become less overloaded and less stressed without becoming less impressive However, the line break between career and definition isn't showing up properly even with two <code> &lt;br </code> > <code> &lt;br </code> > . How would you suggest dealing with this?Blockquote
Presentation layer is best handled by CSS. In this case that would probably be <code> margin-bottom </code> rule for your heading. Markup with <code> &lt;br /&gt; </code> is usually unreliable. WP mostly relies on <code> &lt;p&gt;&lt;/p&gt; </code> tags for paragraphs and not line breaks.
Line breaks not showing up properly
wordpress
I'm trying to create a custom meta box with multiple text fields. The idea is that there is initially one text box, then you can click the button 'Add New' and a another text box is added (using Ajax; no need to publish or update the post for the text box to be created). I'm using the following code (below), but it just doesn't work. I'm completely stuck; really need some help. I'm even willing to donate some cash if anyone can help me figure this out. http://pastebin.com/usRhiJJ4
If you end goal is to add text boxes dynamically, but still require the user to save/update the post, you don't need to use AJAX at all. Just name the text fields appropriately so an array of values is POSTed, then handle it in your save action. It may be helpful to save this array in a single post meta key, so you can just loop through it to output the meta box. Give an ID to the enclosing &lt;div&gt;, something like 'slideshow_metabox' Set your initial text boxes as so: <code> &lt;input type="text" style="position: relative; right: 0; width: 85%;" name="slideshow[]" value="&lt;?php echo $value; ?&gt;" /&gt; </code> And change your 'add button' onclick to be: <code> function() { jQuery('#slideshow_metabox').append('&lt;input type="text" style="position: relative; right: 0; width: 85%;" name="slideshow[]" value="" /&gt;'); } </code> Hope this helps.
Custom Metabox with Ajax in Edit Post - Stuck
wordpress
I've tried to search for a geo-blocking plugin for wordpress - didn't find anything. So thought to ask here if anyone knows of a geo-blocking solution for wordpress sites? Thanks.
If memory serves, Bad Behavior allows to configure a few aspects of geo-blocking. There might be a few wp.org plugins tagged as security that allow to implement geo-blocking too. That said, I don't think it's the right approach. The best is to hop over to askapache.com. There's tons of security-related, htaccess-based stuff over there. Geo-blocking is among them.
Geo Blocking in Wordpress - how can it be implemented?
wordpress
I have chosen from a variety of menus for my application only one and it was a wordpress 3.0.1 admin panel menu, but I can't get pass the functionality of it. If to be more distinct I can't understand how the sliding in this menu work. Is there a jQuery function for every element of the menu or they made it with no link to the specific menu item and how does it remember the state (is menu item open or closed)? I hope I asked this question in the correct place. Thank you all for help.
It's a rather open ended question... Basically, the core menu functionality are in: wp-amin/menu.php (initialize/display) wp-admin/js/common.dev.js (fold/unfold and store state scripts) wp-admin/includes/plugin.php (functions that allow plugins to add extra items) But these then make use of a wide variety of other WP functionality. If your goal is to create menu code for a separate app, as I'm suspecting, you're in for copying entire chunks of the WP code base so you might as well use WP altogether.
Mimicking admin panel menu from wordpress 3.0.1
wordpress
I want to install WP in 3 languages: en, ro, ru <code> mysite.com/en mysite.com/ro mysite.com/ru </code> I was not sure, but installed WP in the root folder. Now I need to redirect visitors to default language. Say "en". AND I don't need having 4 sites actually: <code> / </code> , <code> /en/ </code> , <code> /ro/ </code> , <code> /ru/ </code> , but 3. The situation is actually like this I can't "remove" the "/" site, actually
I use on the root site a small theme for redirect to the languages. A very small theme for locate the language of the users and redirect to the blog of this language. <code> &lt;?php // Browsersprache ermitteln function lang_get_from_browser($allowed_languages, $default_language, $lang_variable = NULL, $strict_mode = TRUE) { // $_SERVER['HTTP_ACCEPT_LANGUAGE'] verwenden, wenn keine Sprachvariable mitgegeben wurde if ( NULL === $lang_variable ) $lang_variable = $_SERVER['HTTP_ACCEPT_LANGUAGE']; // wurde irgendwelche Information mitgeschickt? if ( empty($lang_variable) ) return $default_language; // Den Header auftrennen $accepted_languages = preg_split('/,\s*/', $lang_variable); // Die Standardwerte einstellen $current_lang = $default_language; $current_q = 0; // Nun alle mitgegebenen Sprachen abarbeiten foreach ($accepted_languages as $accepted_language) { // Alle Infos dieser Sprache rausholen $res = preg_match( '/^([a-z]{1,8}(?:-[a-z]{1,8})*)'. '(?:;\s*q=(0(?:\.[0-9]{1,3})?|1(?:\.0{1,3})?))?$/i', $accepted_language, $matches ); if (!$res) continue; // Sprachcode holen und dann sofort in die Einzelteile trennen $lang_code = explode('-', $matches[1]); // Wurde eine Qualität mitgegeben? if ( isset($matches[2]) ) $lang_quality = (float)$matches[2]; else $lang_quality = 1.0; // Bis der Sprachcode leer ist... while (count ($lang_code)) { // mal sehen, ob der Sprachcode angeboten wird if (in_array ( strtolower( join('-', $lang_code) ), $allowed_languages) ) { // Qualität anschauen if ($lang_quality &gt; $current_q) { $current_lang = strtolower( join('-', $lang_code) ); $current_q = $lang_quality; break; } } // Wenn wir im strengen Modus sind, die Sprache nicht versuchen zu minimalisieren if ($strict_mode) break; // den rechtesten Teil des Sprachcodes abschneiden array_pop($lang_code); } } return $current_lang; } $allowed_langs = array('en', 'de'); $lang = lang_get_from_browser($allowed_langs, 'en', NULL, FALSE); if ( 'de' === $lang ) Header("Location: http://wpbasis.de/readme-de_DE.php"); else Header("Location: http://wpbasis.de/readme-en_US.php"); exit(); ?&gt; </code>
Multisite - how to remove the root '/' site?
wordpress
What I am trying to do is create a custom post type, custom meta box that inserts the values of it into an array of 'colors' or, 'p_clrs'. I have a jQuery script which works, allowing you to click a link to "Add Another Color", which adds another input field below the one which shows always by default (must show at least 1 colors metabox). The jQuery added input fields should store the values of each one that gets added, as another 'color' in the array of 'colors' which I'm trying to create. When on the newpost page or edit page for existing posts, the colors metabox needs to run a foreach loop to create a metabox foreach 'color' that exists in the 'p_clrs' variable. I am not good at all with arrays, and multi-arrays, and especially foreach loops. I hate foreach loops lol. I've gotten it all so close to working, I don't want to do it all over using taxonomies, and once I get this to foreach loop over each color of the array which I am trying to create here, I will be able to handle anything else I need to with this stuff. I just can't get over the array/foreach hump I'm stuck on here. This is my Product Class for my custom post type. This is what I have all the values for the posts info (including my other metaboxes which the codes aren't included here for them). <code> class TypeProducts { public $prod_meta_fields = array( 'title', 'description', 'product_type', 'post_tag', 'p_sku', 'p_price', 'p_discnt_price', 'p_weight', 'p_size_w', 'p_size_h', 'p_clrs' ); </code> Here is the method which also has my register_post_type() and register_taxonomy() codes but that isn't really needed for this so I left it out. After the register_ptype and _tax() functions are called, I add the actions for things that need to be added to the init and stuffs. <code> public function TypeProducts() { add_action( 'admin_init', array( &amp;$this, 'product_meta_boxes' )); add_action( 'wp_insert_post', array( &amp;$this, 'wp_insert_post' ), 10, 2 ); } </code> This method is what does all the inserting of information for each of the post form fields. It works for all my custom metaboxes too, *Except for the additional input fields that jQuery adds when you click the "Add Another Color" link/button. <code> public function wp_insert_post($post_id, $post = null) { if ($post-&gt;post_type == 'product') { // my custom post type is 'product' foreach ($this-&gt;prod_meta_fields as $key) { // loops over the $prod_meta_fields $value = @$_POST[$key]; if (empty($value)) { delete_post_meta($post_id, $key); continue; } if (!is_array($value)) { if (!update_post_meta($post_id, $key, $value)) { add_post_meta($post_id, $key, $value); } } else { delete_post_meta($post_id, $key); foreach ($value as $entry) add_post_meta($post_id, $key, $entry); } } } } </code> Here's the method for adding my metabox(es). Not sure whether I could/should do the foreach within this, looping over the array of $p_clrs values to add a metabox foreach color that exists, if there are more than one. Otherwise, there should just be one metabox displayed (at all times there should be at least 1). <code> function product_meta_boxes() { add_meta_box( 'products-price', 'Product SKU# &amp;amp; Price', array( &amp;$this, 'prod_price_box' ), 'product', 'side', 'high' ); add_meta_box( 'products-colors', 'Product Colors', array( &amp;$this, 'prod_colors_box' ), 'product', 'normal', 'high' ); } </code> Here's my method for outputting the metabox(es) itself, and also the jQuery script that adds and removes additional input fields which "could" potentially become metaboxes upon saving the post if the added boxes arent empty. Here's a picture of what I mean to give you an idea of what I'm talking about. Currently the first input shows on page load with any value which is stored if any. When clicking the Add Another link, it adds another input with the same value, but when saving a different value in any input field, it saves the value of the last input that has a value. And only shows one input upon reloading the page when you save it too. I need to show inputs for each added value that was there, which needs to also be inserted to the 'p_clrs' variable/array in order to do that foreach 'p_clrs' value that exists. Lost yet? <code> public function prod_colors_box() { global $post, $p_clr; $p_clr = array(); $p_clrs = get_post_meta( $post-&gt;ID, 'p_clr', true ); ?&gt; &lt;div id="p_colors"&gt; &lt;p&gt; &lt;label for="p_clr_1"&gt; &lt;strong&gt;Color:&lt;/strong&gt; &lt;input id="p_clr_1" name="p_clr" value="&lt;?php echo $p_clrs; ?&gt;" /&gt; &lt;/label&gt; &lt;/p&gt; &lt;/div&gt; &lt;h4&gt;&lt;a href="#" id="addClr"&gt;Add Another Color&lt;/a&gt;&lt;/h4&gt; &lt;script src="http://code.jquery.com/jquery-1.4.3.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function() { var clrDiv = $('#p_colors'); var j = $('#p_colors p').size() + 1; $('#addClr').live('click', function() { $('&lt;p&gt;&lt;label for="p_clr_' + j + '"&gt;&lt;strong&gt;Color:&lt;/strong&gt; &lt;input id="p_clr_' + j + '" name="p_clr" size="20" value="&lt;?php echo $p_clrs; ?&gt;" /&gt;&lt;/label&gt; &lt;a href="#" id="remClr"&gt;Remove&lt;/a&gt;&lt;/p&gt;').appendTo(clrDiv); j++; return false; }); $('#remClr').live('click', function() { if( j &gt; 2 ) { $(this).parents('p').remove(); j--; } return false; }); }); &lt;/script&gt; &lt;?php } </code> <code> } // end of TypeProducts{} Class </code> Thanks for any help anyone can give me, and sorry if this is a little crazy of a post. I had a hard time cutting/pasting the code into this textarea. It was being wonky for me. Let me know if my explanation of what I'm trying/need to do isn't entirely clear too. It's kind of difficult to easily describe without some sort of visual of it first.
You just have to modify the name attribute of the generated input fields from <code> p_clr </code> to <code> p_clr[] </code> . <code> $_POST['p_clr'] </code> will then be an array with the values of all the input fields. <code> public function prod_colors_box() { global $post, $p_clr; $p_clr = array(); $p_clrs = get_post_meta( $post-&gt;ID, 'p_clr' ); ?&gt; &lt;div id="p_colors"&gt; &lt;?php foreach( $p_clrs as $key =&gt; $p_clr ) { ?&gt; &lt;p&gt; &lt;label for="p_clr_&lt;?php echo $key; ?&gt;"&gt; &lt;strong&gt;Color:&lt;/strong&gt; &lt;input id="p_clr_&lt;?php echo $key; ?&gt;" name="p_clr[]" value="&lt;?php echo $p_clr; ?&gt;" /&gt; &lt;/label&gt; &lt;/p&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;h4&gt;&lt;a href="#" id="addClr"&gt;Add Another Color&lt;/a&gt;&lt;/h4&gt; &lt;script src="http://code.jquery.com/jquery-1.4.3.min.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(function() { var clrDiv = $('#p_colors'); var j = $('#p_colors p').size() + 1; $('#addClr').live('click', function() { $('&lt;p&gt;&lt;label for="p_clr_' + j + '"&gt;&lt;strong&gt;Color:&lt;/strong&gt; &lt;input id="p_clr_' + j + '" name="p_clr[]" size="20" value="&lt;?php echo $p_clrs; ?&gt;" /&gt;&lt;/label&gt; &lt;a href="#" id="remClr"&gt;Remove&lt;/a&gt;&lt;/p&gt;').appendTo(clrDiv); j++; return false; }); $('#remClr').live('click', function() { if( j &gt; 2 ) { $(this).parents('p').remove(); j--; } return false; }); }); &lt;/script&gt; </code>
How can I show/add/save custom metaboxes as an Array of values?
wordpress
I'm looking for a solution that would allow me to write tags inside posts and be sure that the visual editor or wordpress will not alter them. The same problem can apply for other specific HTML code that I may want to use. Disabling the visual editor is not an option, because in will render most edit operation too hard to use.
Add the following to your theme functions.php: <code> function fb_change_mce_options($initArray) { $ext = 'script[charset|defer|language|src|type]'; if ( isset( $initArray['extended_valid_elements'] ) ) { $initArray['extended_valid_elements'] .= ',' . $ext; } else { $initArray['extended_valid_elements'] = $ext; } return $initArray; } add_filter('tiny_mce_before_init', 'fb_change_mce_options'); </code>
How to configure Wordpress to be able to use tag inside posts?
wordpress
I am using WordPress mu 2.9.2 and have the same category structure on all my blogs. How do I add categories to all my blogs simultaneously? Is there a plugin that does this effectively?
You could write a script for that, here is something I wrote in Perl lately: first the sql statements to check if the term already exist and if not insert it: the prepared statements: <code> my $wts = $dbh-&gt;prepare( "SELECT term_id FROM $tb_wp_terms WHERE name = ?") or die "Couldn't prepare statement: " . dbh-&gt;errstr; my $wti = $dbh-&gt;prepare( "INSERT INTO $tb_wp_terms (name, slug) VALUES (?,?)") or die "Couldn't prepare statement: " . dbh-&gt;errstr; </code> then make the term taxonomy entry: the prepared statements: <code> my $wtts = $dbh-&gt;prepare( "SELECT term_taxonomy_id FROM $tb_wp_term_taxonomy WHERE term_id = ? AND taxonomy = '".$config{'wordpress.taxonomy_type'}."'") or die "Couldn't prepare statement: " . dbh-&gt;errstr; my $wtti = $dbh-&gt;prepare( "INSERT INTO $tb_wp_term_taxonomy (term_id, taxonomy, count) VALUES (?,?,1)") or die "Couldn't prepare statement: " . dbh-&gt;errstr; my $wtts_count = $dbh-&gt;prepare( "SELECT count FROM $tb_wp_term_taxonomy WHERE term_taxonomy_id = ? AND taxonomy = '".$config{'wordpress.taxonomy_type'}."'") or die "Couldn't prepare statement: " . dbh-&gt;errstr; my $wtti_count = $dbh-&gt;prepare( "UPDATE $tb_wp_term_taxonomy SET count = ? WHERE term_taxonomy_id = ? ") or die "Couldn't prepare statement: " . dbh-&gt;errstr; </code> And use the queries above with some code around it (you need to check for blogs that already have some of the categories). For MU only the blogs > 1 get a blog id in their table name: <code> my $tb_blogid = ""; if ( $config{'wordpress.wp_mu_blog_id'} &gt; 1 ) { $tb_blogid = "_" . $config{'wordpress.wp_mu_blog_id'}; } my $tb_posts = $config{'wordpress.prefix'} . $tb_blogid . "_posts"; my $tb_wp_terms = $config{'wordpress.prefix'} . $tb_blogid . "_terms"; my $tb_wp_term_taxonomy = $config{'wordpress.prefix'} . $tb_blogid . "_term_taxonomy"; my $tb_wp_terms_relationships = $config{'wordpress.prefix'} . $tb_blogid . "_term_relationships"; </code> So just loop through them.
Adding categories to all blogs at once
wordpress
I (will) have a multilingual (3 lang actually) site. I used WMPL some time, but this plugine made me sad... Finally, I decided to install each language a part. How should it be done? I have my <code> / </code> So, should I install <code> /en </code> <code> /fr </code> <code> /it </code> or <code> / </code> + <code> /fr </code> <code> /it </code> is there some plugin that will help me to synchronize content?
I would go for /en/ in order to prevent future issues and keep isolated the content that is not localizable. From my knowledge WPML does not support this yet.
Multiple install for multilanguage. How to?
wordpress
FeedWordPress is pulling in two, three, four, and as many as 15 copies of the same post when it updates (via manual cron triggers or via auto updates). It doesn't happen all the time, and it doesn't happen with every post. I also noticed that it occasionally says that a FWP post was "created locally on this site", even though it wasn't. Copies of that same post will sometimes say "local", and sometimes "syndicated". And one more strange behavior, it's actually posting stuff from one domain into another completely different domain, but it only seems to pull the post_title across, no content or categories. I'm on a WP Multi-site 3.0.1 install with FWP v2010.0905. I'm also using WP Super Cache if that might make a difference. Has anyone experienced any of this before? Does the duplicated posts FWP filter work properly? Thanks for your help, Dave Morris
You can use the "syndicated_post" hook that's available in FWP and hook in a function that checks for duplicate posts. <code> add_action('syndicated_post', 'fwp_check_duplicate'); </code> I started working on this a few months back but did not complete it. I basically got to the point of flagging potential duplicates and putting them in draft mode instead of publishing. <code> function fwp_check_duplicate ( $post ) { global $wpdb; $handle; $possible_duplicate; $query = "SELECT id,guid FROM $wpdb-&gt;posts WHERE post_title = '%s' AND post_date_gmt like %s"; $sql = $wpdb-&gt;prepare( $query, $post['post_title'], gmdate('Y-m-d', $post['epoch']['issued'])."%" ); $results = $wpdb-&gt;get_results( $sql, ARRAY_N); foreach ( $results as $result ) { if ( $result['guid'] != $post['guid'] ) { $possible_duplicate = true; } } if ($possible_duplicate) { $post['post_status'] = "draft"; } // Otherwise continue to process. return $post; } </code> Hope that helps.
FeedWordPress duplicated posts problem
wordpress
I have read the discussion on the performance of different permalinks on the wp hackers mailinglist, THIS forum and around Google. I could however not really deduce if the permalink structure I have been using for the past years is good or not: <code> /%postname%-%year%%monthnum%%day%.html </code> This combination put the postname directly after the / and the year,month,day combination makes it more unique since many postnames carry the same name. The html addition is something I have been using for the past 10 years on my blog (even pre wordpress) so that is legacy. I dont know if this is good for permance or bad for performance, how can i check this? (I have been running the blog for +10 years and there are about 10.000 posts with many links in) links: http://codex.wordpress.org/Using_Permalinks http://www.google.com/search?q=wordpress+category+permalink+performance http://ottopress.com/2010/category-in-permalinks-considered-harmful/ http://lists.automattic.com/pipermail/wp-hackers/2010-October/035458.html
You can check by looking at the size of the rewrite_rules option in the database. If it's small (which I believe it should with this structure), you're not using verbose rules. By contrast, if you see several lines per static page, you're using verbose rules and it's not good.
Performance of my permalink structure?
wordpress