question
stringlengths
0
34.8k
answer
stringlengths
0
28.3k
title
stringlengths
7
150
forum_tag
stringclasses
12 values
The code below is near the top of my functions.php and is set to run only when my theme is activated: <code> if ( is_admin() &amp;&amp; isset($_GET['activated'] ) &amp;&amp; $pagenow == 'themes.php' ) { </code> However, even though its creating the category "my-utilities", it is apparently not able to set the parent of the category1 and category2 items to the newly created category. Perhaps its too soon to call get_cat_id on the newly created category? I believe it has something to do with that, since the category's reparent on the 2nd time the theme is activated. This, I presume, is since the category that will be used as parent has been created previously, the routine has no problem finding its ID and using it as the parent for category1 and category2. What am I missing? <code> // with activate make sure theme's utility categories are present and parented correctly if ( is_admin() &amp;&amp; isset($_GET['activated'] ) &amp;&amp; $pagenow == 'themes.php' ) { if (file_exists(ABSPATH.'/wp-admin/includes/taxonomy.php')) { require_once(ABSPATH.'/wp-admin/includes/taxonomy.php'); if(!get_cat_ID('my-utilities')){wp_create_category('my-utilities');} //find out the ID of the newly created category, "my-utilities" $my_default_cat = my_cat(); if(!get_cat_ID('category1')){wp_create_category('category1',$my_default_cat);} if(!get_cat_ID('category2')){wp_create_category('category2',$my_default_cat);} //if the categories already existed, reparent them $myCategory1['cat_ID'] = get_cat_id('category1'); $myCategory1['category_parent'] = $my_default_cat; wp_update_category($myCategory1); $myCategory2['cat_ID'] = get_cat_id('category2'); $myCategory2['category_parent'] = $my_default_cat; wp_update_category($myCategory2); } } //utility category function my_cat() { if(get_cat_ID('my-utilities')) { return get_cat_ID('my-utilities'); } else { if(term_exists(1)) return "1"; else return get_option('default_category'); } } </code>
You're looking for this: <code> register_activation_hook( __FILE__, 'your_plugin_activate_function_name' ); </code> Edit: for a theme, you can use something like this instead: <code> $theme_version = get_option('my_theme_version'); switch ((string) $theme_version) { // an early alpha... run upgrade code case '0.1': // another version... run upgrade code case '0.5': // add other cases as needed... without any break statement. // if we're here and in the admin area (to avoid race conditions), // actually save whichever changes we did if (is_admin()) { update_option('my_theme_version', '1.0'); // do other stuff } // we're at the latest version: bail here. case '1.0': break; default: // install code goes here } </code>
Script only partially runs on theme activation, but runs fully on deactivation?
wordpress
I'm trying to add a custom feed format to my site (basically exporting data to an Excel file) and I'm getting confused by the feed caching settings. I can't figure out how to flush the cached feeds, or to turn off feed caching altogether while I'm in development. I've tried deleting all the <code> _transient_feed... </code> , <code> _transient_timeout_feed... </code> and <code> _transient_rss... </code> options, but I'm still seeing the cached feeds. And, based on some advice in this support forum thread , I tried on a whim adding this line to my wp-config.php: <code> define('MAGPIE_CACHE_AGE', 0); </code> (Obviously I'd like some caching of feeds, but it would help in development to be able to turn off the feed caching.) Anybody got any suggestions? Some clarification: Sorry, I think I wasn't clear enough in the initial question, and then I threw you all by referring to the magpie cache, which was completely on the wrong path. I was shooting blind at first. I'm adding a feed to my site using <code> add_feed() </code> . The function that generates the feed is using the PHPExcel class to write an excel spreadsheet. Then I'm setting appropriate headers for download, and outputting the .xls file data. I think my problem might actually be a browser caching issue. The urls that I'm trying to output my feeds from look this this: mysite.com/facility/ummc/?feed=master_log and the xls file that's generated is called Master_Log.xls. Adding a cache busting string to the url request can get around the cache, i.e. requesting a feed from mysite.com/facility/ummc/?feed=master_log&amp;now=12ag4oSduq344 ... I was just wondering if there was any way of disabling the cache altogether.
It definitely might be a caching issue. I find REDbot is excellent for quick check of how result is served and what are its caching settings.
How to flush feed? Or set timeout on feed so that it isn't cached?
wordpress
Is there anyway I can set what text should appear in the tags before get_header() is called in my .php files that are inside my theme's directory?
It depends on your theme how exactly <code> &lt;title&gt; </code> is generated. At least some of it should be generated by <code> wp_title() </code> function, output of which you can filter at <code> wp_title </code> hook.
Anyway to specify what should appear in in .php file?
wordpress
Is is possible to override the set # of blog posts to show per page (as defined under Reading Settings in the WordPress admin)? I want to make it so a custom loop that I am using will show an unlimited number.
The argument that controls how many posts are shown in the query is posts_per_page <code> &lt;?php query_posts( array( 'post_type' =&gt; 'post', 'posts_per_page' =&gt; -1 ) ); ?&gt; </code> Also to note is that there is a bug in the 3.0 branch which prevents the -1 integer from displaying all posts. It is fixed in 3.1 but a workaround would be to use a very high number instead of -1 see: http://core.trac.wordpress.org/ticket/15150
Override the default number of posts to show for a single loop?
wordpress
So I have this code that queries a custom plugin generated table in the wp database. It works perfectly as is. But I'm trying to adjust it to use $wpdb instead of the $con function I have set up. Here is the code that works perfectly, but not using $wpdb: <code> &lt;?php $q = strtolower($_GET["q"]); if (!$q) return; $isArabic = is_arabic($q); $con=mysql_connect("localhost","admin","*****"); if($con){ mysql_select_db("arabic_student",$con); } else{ die("Could not connect to database"); } mysql_query("SET NAMES utf8"); $sql = "SELECT DISTINCT en_word, ar_word FROM wp_enar_words WHERE en_word LIKE '$q%' OR ar_word LIKE '$q%'"; $rsd = mysql_query($sql) or die(mysql_error()); if($isArabic){ while($rs = mysql_fetch_array($rsd)) { $en_word = $rs['en_word']; $ar_word = $rs['ar_word']; echo "$ar_word\n"; } }else{ while($rs = mysql_fetch_array($rsd)) { $en_word = $rs['en_word']; $ar_word = $rs['ar_word']; echo "$en_word\n"; } } ?&gt; </code> Here is my noob attempt to use $wpdb: <code> global $wpdb; $sql = $wpdb-&gt;get_results("SELECT en_word, ar_word FROM wp_enar_words WHERE en_word LIKE '$q%' OR ar_word LIKE '$q%'"); $rsd = $wpdb-&gt;query('$sql'); </code> But it gets a Fatal error: Call to a member function get_results() on a non-object in.... So maybe missing something obvious but hoping I could get some guidance on how to port my existing code to using $wpdb. Thanks in advance! UPDATE: so I'm starting to think that the problem is that this code is being called with a jquery plugin. I'm using jquery autocomplete and calling the above php code to populate the form autocomplete: <code> $("#search_words").autocomplete("&lt;?php bloginfo('template_directory'); ?&gt;/search_ac.php", {}); </code> Could this be the problem? I'm confused because my original code that directly calls the database works perfectly, but once I use $wpdb, it no longer functions
Your error message means that $wpdb in your code is currently pointing to a null pointer. Either WP is not loaded, or you're missing a simple <code> global $wpdb; </code> statement, or both. If you need to load WP, include wp-load.php. Or better, in your JS, use ajaxurl: <code> url = ajaxurl + '?action=youraction' </code> alongside (assuming the above code): <code> add_action('wp_ajax_youraction', 'yourcode'); </code> there's an unauthenticated version of the same (see wp-admin/admin-ajax.php)
Have working sql query... trying to adjust it to use $wpdb
wordpress
I have a plugin that creates a custom post type called Squeeze Pages. It has various short codes users can enter to make a squeeze page but I'm not sure how I can go about making the squeeze pages have a custom design, completely different from the homepage. Is this possible? If so, how can it be done?
The code below retrieves the custom post type of the currently displayed content and then decides wheter to print on of your stylesheets. Everything happens depending on your page name. You could also <code> var_dump($ctp_obj_name); </code> or <code> printr($ctp_obj_name); </code> and look what else the custom post type object has to offer and decide what you'll use instead of the name. The following should reside in your functions.php or in some file included from there: <code> add_action( 'init', 'print_squeeze_style' ); function print_squeeze_style() { define( 'YOUR_PATH', get_bloginfo('stylesheetpath').'/squeeze_css_dir/' ); // define css folder for squeeze here $post_type = 'your_custom_post_type'; // define custom post type name here // ID of post type currently displayed $ctp_ID = get_the_ID(); // retrieve the whole ctp object of the current "post" $ctp_obj = get_post_type( $ctp_ID ); $ctp_obj_name = $ctp_obj-&gt;name; // get name $ctp_obj_type = $post-&gt;post_type; // type // file name depending on Custom Post Type Page Name if ( $ctp_obj_name == 'page name A' ) { $file = 'filename_a.css'; } elseif ( $ctp_obj_name == 'page name B' ) { $file = 'filename_b.css'; } else { $file = 'filename_default.css'; } // Register the stylesheet for printing if ( post_type_exists( $post_type ) ) wp_register_style( 'squeeze-css', YOUR_PATH.$file, false, '0.0', 'screen' ); // print styles depending on Custom Post Type Page Name // Then output/print style in head if ( $ctp_obj_type == $post_type ) { add_action( 'wp_head', wp_print_styles( 'squeeze-css' ) ); } } </code> As stated below (please upvote previous Answers too), you'll need an filter on the body_class() function output to do stuff like <code> body.squeeze div.wrapper div.post .some_element_class </code> <code> add_filter( 'body_class', 'body_class_for_squeeze' ); function body_class_for_squeeze( $classes ) { $post_type = 'your_custom_post_type'; // define custom post type name here // ID of post type currently displayed $ctp_ID = get_the_ID(); // retrieve the whole ctp object of the current "post" $ctp_obj = get_post_type( $ctp_ID ); $ctp_obj_name = $ctp_obj-&gt;name; // get name $ctp_obj_type = $post-&gt;post_type; // type // abort if we're not on a squeeze page if ( $ctp_obj_type !== $post_type ) return; $classes[] .= 'squeeze'; return $classes; } </code>
Custom Post Type to override theme's CSS & HTML from Plugins Dir?
wordpress
In my website , I allow to the new user to write posts. but the problem is when the user write post. the state of post is publish. it is appear in front page. I want to read it before the publish , I mean I want to approve it if it is useful or refuse it if it unuseful. I wish you understand me. Thank you very much ,
What role are you assigning to those users? According to Roles and Capabilities documentation in Codex it should be <code> Contributor </code> for users that are allowed to write posts, but not publish them.
How do I manage my users post before publish?
wordpress
There is lots of information out there on how to customize meta boxes added with add_meta_box(), such as enabling WYSIWYG editors on textareas and uploading images. What I have yet to find is a way to reuse WordPress 3.1 Internal Linking feature. Many of my custom fields contain urls to other pages on the site. The new Internal Linking feature would make it a lot easier for my users to find a page URL rather than having to remember it of cut &amp; paste it. Is the new Internal Linking feature reusable in conjunction with add_meta_box()?
WordPress 3.1 Internal Linking feature was coded as a TinyMCE editor plugin so its not really a widget or a meta box but you can code your own meta box and reuse the functiona needed for that. The files you need to look at are /wp-includes/js/tinymce/wp-mce-link.php /wp-includes/js/tinymce/plugins/wplink/js/wplink.js and maybe a few more but these are the main files you will need to achieve this functionality. Side note: I can tell you that up until now when ever i needed to let my user add a url to a post or a page as a custom field i always created a dropdown select with the names of my posts and there id as value, then when i needed to show that link i'd call <code> get_the_permalink(selected_ID); </code> . Now i know that this won't work in all cases but its an option and i wanted to post it here for future reference. Hope this helps, Ohad.
Use WP 3.1 Internal Linking 'widget' as a meta_box
wordpress
I know I can get a categories ID by calling get_cat_ID('category-slug'), however, what is the method to call to determine if a category exists by ID when you don't know the slug? In other words, I need to determine if category id 1 exists. What's the function for this? Can I just use if(get_category(1)) {//do something?}
There is <code> category_exists() </code> function, but it seems to be for internal use in admin so you can try <code> term_exists() </code> instead.
How do I determine if a category exists by ID?
wordpress
I am managing a WP 3.0.4 site where every post has the profile of the author appended. Where is the setting to disable this?
There's no exact "setting" in the backend/Admin UI. You'll have to edit your template files (the php files that are in your theme folder). Search for something like <code> &lt;a href=""&gt;&lt;/a&gt; </code> where you got one (or more) of the php (wp native) function or variable: <code> the_author_posts_link(); </code> <code> $curauth-&gt;user_url; </code> <code> get_the_author(); </code> <code> get_author_posts_url(); </code> ... or something theme specific Helpful is always a link to the download of your theme or some template code.
Disable author profile in post
wordpress
I want to change the default "Excerpts are optional hand-crafted summaries of your content that can be used in your theme. Learn more about manual excerpts." help text below the Excerpt input area to something more meaningful for my Custom Post Type. I've done something similar with Post Title, using a "translation" filter, but how would I do this with the post excerpt? Here is my current code: <code> add_filter('gettext', 'custom_rewrites', 10, 4); function custom_rewrites($translation, $text, $domain) { </code> <code> global $post; $translations = &amp;get_translations_for_domain($domain); $translation_array = array(); switch ($post-&gt;post_type) { case 'model': $translation_array = array( 'Enter title here' =&gt; 'Enter model name here', 'Excerpt' =&gt; "Byline", 'Excerpts are optional hand-crafted summaries of your content that can be used in your theme.' =&gt; "Foobar" ); break; } if (array_key_exists($text, $translation_array)) { return $translations-&gt;translate($translation_array[$text]); } return $translation; } </code> The third translation isn't working?
This description is generated by <code> post_excerpt_meta_box() </code> function and is not passed through any explicit filters. It is however echoed by translation-related <code> _e() </code> function and so passes through <code> gettext </code> filter (which from your question you are already familiar with). As for limiting it to your CPT, I think current post type in admin is held in global <code> $post_type </code> variable you can check.
How do I filter the excerpt metabox description in admin?
wordpress
I am looking for a way where, the users of my website will subscribe to a post, and when my post will be edited or updated they will be emailed by my posts contents, My post contains, article, Twitter Updates, a Video How will the users get notification when my posts get updated and also when someone comments on posts
Try this two plugins: Post Notification Subscribe2
Subscribe to email
wordpress
I need some help. I want the same as on this site: http://www.123ipad.nl/ (this is my website) When you go to the home url you come to a page in stead of the newspage. The newspages are in the submap /ipad So i have two questions: 1: how do i get the newspages in the submap /ipad 2: How do i set my first created page permalink as homepage? Same as on this image: where you see nothing after <code> http://www.123ipad.nl/ </code> )
please make yourself comfortable with the settings WordPress has to offer regarding your Homepage or Startpage as some call it. Those are not configured via that permalink setting of a specific page (as your image shows) but with options on the Settings Reading SubPanel (Wordpress Codex) . Probably Creating a Static Front Page (Wordpress Codex) is exactly what you're looking for. This might not answer all your questions but might be helpful for a start.
How to set a page as homepage in stead of the newspages?
wordpress
I'm using the following code to create drop-down menu and filter button for two custom taxonomies assigned to a custom post type called Page Content (full previous code stackexchange-url ("here")): <code> function parse_query($query) { global $pagenow; $qv = &amp;$query-&gt;query_vars; if ($pagenow=='edit.php' &amp;&amp; isset($qv['taxonomy']) &amp;&amp; $qv['taxonomy']=='locations' &amp;&amp; isset($qv['term']) &amp;&amp; is_numeric($qv['term'])) { $term = get_term_by('id',$qv['term'],'locations'); $qv['term'] = $term-&gt;slug; } if ($pagenow=='edit.php' &amp;&amp; isset($qv['taxonomy']) &amp;&amp; $qv['taxonomy']=='page_sections' &amp;&amp; isset($qv['term']) &amp;&amp; is_numeric($qv['term'])) { $term = get_term_by('id',$qv['term'],'page_sections'); $qv['term'] = $term-&gt;slug; } } // Add filter drop-down menu for the custom taxonomies function restrict_manage_posts() { global $typenow; global $wp_query; if ($typenow=='page_content') { $taxonomy = 'locations'; $locations = get_taxonomy($taxonomy); wp_dropdown_categories(array( 'show_option_all' =&gt; __("Show All {$locations-&gt;label}"), 'taxonomy' =&gt; $taxonomy, 'name' =&gt; $taxonomy, 'orderby' =&gt; 'name', 'selected' =&gt; $wp_query-&gt;query['term'], 'hierarchical' =&gt; true, 'depth' =&gt; 3, 'show_count' =&gt; true, // This will give a view 'hide_empty' =&gt; true, // This will give false positives, i.e. one's not empty related to the other terms. TODO: Fix that )); } if ($typenow=='page_content') { $taxonomy = 'page_sections'; $page_sections = get_taxonomy($taxonomy); wp_dropdown_categories(array( 'show_option_all' =&gt; __("Show All {$page_sections-&gt;label}"), 'taxonomy' =&gt; $taxonomy, 'name' =&gt; $taxonomy, 'orderby' =&gt; 'name', 'selected' =&gt; $wp_query-&gt;query['term'], 'hierarchical' =&gt; true, 'depth' =&gt; 3, 'show_count' =&gt; true, // This will give a view 'hide_empty' =&gt; true, // This will give false positives, i.e. one's not empty related to the other terms. TODO: Fix that )); } } YourSite_PageContent::on_load(); } </code> But I'm getting the following warning: <code> Parse error: syntax error, unexpected T_STRING, expecting T_FUNCTION in /home/alex/www/wpac/wp-content/themes /prominent/functions/custom-post-types.php on line 181 </code> This is line 181: <code> YourSite_PageContent::on_load(); </code>
You're missing a closing brace on the final if condition. ;)
Creating a drop-down and filter button for two custom taxonomies assigned to a custom post type
wordpress
i have a custom post type called 'auctions', and i'd like to be able to visually differentiate auctions from posts and pages in the backend by assigning a different background color to the auction post type. this could be easily achieved if i had a way to assign a body class to admin pages pertaining to this specific post type, except i'm not sure as to how i'd go about that :). any help would be greatly appreciated. thanks!
Easy and your css to overwrite the default style like this <code> add_action('admin_print_styles', 'auctions_admin_print_styles_332'); function auctions_admin_print_styles_332(){ if ((isset($_GET['post_type']) &amp;&amp; $_GET['post_type'] == 'auctions') || (isset($post_type) &amp;&amp; $post_type == 'auctions')){ //include your css file using wp_enqueue_style() somthing like wp_enqueue_style( 'handle name', plugins_url('/style.css', __FILE__), array(), '1.0' ); // or a more hackish way would be to echo out the css style tag } } </code> so the class you are looking for is actualy an id "wpwrap" so you can use something like this: <code> &lt;style type="text/css"&gt; #wpwrap{background-color: #FFF;} &lt;/style&gt; </code> Hope this helps
changing body background color for custom post type in admin backend
wordpress
I'm trying to get an image from Google but... wp_remote_get returns me: <code> Could not open handle for fopen() to https://ajax.googleapis.com/ajax/services/search/images? v=1.0&amp;q=whatever.whatever&amp;key=MYKEYWHICHIDONTPOST&amp;userip=127.0.0" </code> I don't know why: when I enter the url directly I do get results. all other wp_remote_gets in the same class work ok so yes php.ini allow=ok this is the code i run: <code> $referer_url = get_bloginfo('url'); $referer = $parsed_url[host]; $google_images_url = self::GOOGLE_IMAGES_URL . "&amp;q=" . $url_to_look_for . "&amp;key=" . $key . "&amp;userip=" . $_SERVER['REMOTE_ADDR']; $response = wp_remote_get($google_images_url, array( 'headers' =&gt; array( 'Referer' =&gt; $referer))); </code> hmmm
Yep, I experienced that under some network configurations <code> https </code> links fail (my case was behind proxy server). You can use Core Control plugin to test available HTTP transports and disable glitchy one. In my case bumping transport to curl solved issue.
Why Do I get "wp_remote-get: could not handle for fopen()"?
wordpress
I have a custom post type that uses a custom taxonomy. I'm imposing a limit of a single term to each post (using a custom meta box drop down on the edit post screen for the CPT). The term for the taxonomy is assigned using the standard wp_set_object_terms() function. How can I make the taxonomy column sortable (using WP 3.1rc3)? This post by Scribu got me almost there. However, since I'm not using a numeric value stored in a meta key, the {name}_column_orderby function will not work for me. How can I create sortable columns within the manage-edit screens, when the information that I'm listing does not come from the post_meta table?
See the follow-up post: http://scribu.net/wordpress/sortable-taxonomy-columns.html
Sortable admin columns, when data isn't coming from post_meta
wordpress
I have a page that I access at /category/tasks and the file is located at wp-content/themes/my-theme/tasks.php. I would like to make it so I can add a flag after tasks and pick up the query strong in tasks.php. This works fine when I access the page with /category/tasks/?when=upcoming. Can someone tell me how to use rewrite_rules_array so it will send the variable through the query string using the URL structure /category/tasks/upcoming?
Try this: <code> function when_rewrite_rules( $wp_rewrite ) { $new_rules = array(); $new_rules['category/tasks/(\d*)$'] = 'index.php?when=$matches[1]'; $wp_rewrite-&gt;rules = $new_rules + $wp_rewrite-&gt;rules; } add_filter('generate_rewrite_rules','when_rewrite_rules'); </code>
Need help with rewrite_rules_array
wordpress
I just created a custom post type "publication" with the slug "publications". Now im stuck trying to view all the publications index in a URL like: http://www.myExampleSite.com/publications Do I have to create some custom layouts for it, and how it will be using an index clone of twentyten theme, maybe using get_template_part? Thanks in advanced.
In WordPress 3.1 virtual directory is created for you custom post type and so you don't really need to do anything but if you are on a earlier version then you will need to make a few step: which you have done most but you will need to change loop-publication.php and add your custom post type to the query args or replace the loop with your custom loop that includes the custom post type in the args something like this: <code> &lt;?php $loop = new WP_Query( array( 'post_type' =&gt; 'publication', 'posts_per_page' =&gt; 10 ) ); ?&gt; &lt;?php while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;?php the_title( '&lt;h2 class="entry-title"&gt;&lt;a href="' . get_permalink() . '" title="' . the_title_attribute( 'echo=0' ) . '" rel="bookmark"&gt;', '&lt;/a&gt;&lt;/h2&gt;' ); ?&gt; &lt;div class="entry-content"&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; </code> now since you want to view the list on http://www.myExampleSite.com/publications add this code to the very top of your publications.php <code> &lt;?php /* Template Name: publications */ ?&gt; </code> then create a page and change its slug to 'publications' and select publications as page template. and you are set to go.
Custom post type index (maybe using get_template_part)
wordpress
I know by watching the akismet plugin source how to show a custom message on the plugins page, but I want my message to appear only once after my plugin is activated. How could i do this?
The easiest way would be to check for an stub get_option something like <code> $run_once = get_option('run_once'); if (!$run_once){ //show your custom message here // then update the option so this message won't show again update_option('run_once',true); } </code> hope this helps
How to show custom message once on plugin activation?
wordpress
I use the following custom loop to display a custom post type with the custom taxonomy: <code> &lt;?php // Create and run custom loop $custom_posts = new WP_Query(); $custom_posts-&gt;query('post_type=page_content&amp;page_sections=Apps'); while ($custom_posts-&gt;have_posts()) : $custom_posts-&gt;the_post(); ?&gt; &lt;div class="block-1"&gt; &lt;?php the_post_thumbnail('large'); ?&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; </code> Right now it reads: retrieve ONLY posts with the page_content custom post type and the App custom taxonomy. Is it possible to make it read: retrieve ONLY posts with the page_content custom post type, the Front Page custom taxonomy, and the Apps custom taxonomy? EDIT: This didn't work: <code> &lt;?php // Create and run custom loop $custom_posts = new WP_Query(); $custom_posts-&gt;query('post_type=page_content&amp;page_sections=Front Page, Apps'); while ($custom_posts-&gt;have_posts()) : $custom_posts-&gt;the_post(); ?&gt; &lt;div class="block-1"&gt; &lt;?php the_post_thumbnail('large'); ?&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; </code>
In versions less the 3.1 you can't query more then one taxonomy using wp_query, query_posts or get_posts. However you can create your own sql query which you can see an examstackexchange-url ("enter link description here")ple here or use scribu's plugin http://scribu.net/wordpress/query-multiple-taxonomies/ To make it work.
Listing only custom post types with two required categories?
wordpress
I'm using the following code to display posts on my category page but would like to carry the same format through on to the second page of the category as at the moment it moves to the second page but doesn't show the older posts. <code> &lt;?php query_posts('showposts=3&amp;cat=1461'); while (have_posts()) : the_post(); echo "&lt;div class=column-post&gt;"; echo "&lt;div class=category-thumb&gt;&lt;a href="; echo get_permalink(); echo "&gt;"; the_post_thumbnail(array (185,152)); echo "&lt;/a&gt;&lt;/div&gt;"; echo "&lt;div class=category-title&gt;&lt;a href="; echo get_permalink(); echo "&gt;"; the_title(); echo "&lt;/a&gt;&lt;/div&gt;"; echo "&lt;div class=category-desc&gt;"; the_excerpt(); echo "&lt;/div&gt;"; echo "&lt;div class=category-more&gt;&lt;a href="; echo get_permalink(); echo "&gt;"; echo "&lt;img src="; bloginfo('template_directory'); echo "/images/more.png&gt;"; echo "&lt;/a&gt;&lt;/div&gt;"; echo "&lt;/div&gt;"; endwhile;?&gt; &lt;/div&gt; &lt;div class="divider"&gt;&lt;/div&gt; &lt;div class="3-column-holder"&gt; &lt;?php query_posts('showposts=3&amp;offset=3&amp;cat=1461'); while (have_posts()) : the_post(); echo "&lt;div class=column-post&gt;"; echo "&lt;div class=category-thumb&gt;&lt;a href="; echo get_permalink(); echo "&gt;"; the_post_thumbnail(array (185,152)); echo "&lt;/a&gt;&lt;/div&gt;"; echo "&lt;div class=category-title&gt;&lt;a href="; echo get_permalink(); echo "&gt;"; the_title(); echo "&lt;/a&gt;&lt;/div&gt;"; echo "&lt;div class=category-desc&gt;"; the_excerpt(); echo "&lt;/div&gt;"; echo "&lt;div class=category-more&gt;&lt;a href="; echo get_permalink(); echo "&gt;"; echo "&lt;img src="; bloginfo('template_directory'); echo "/images/more.png&gt;"; echo "&lt;/a&gt;&lt;/div&gt;"; echo "&lt;/div&gt;"; endwhile;?&gt; &lt;/div&gt; &lt;div class="divider"&gt;&lt;/div&gt; </code>
First make sure you've set your posts per page to 6 in the Reading settings - as I can see you're displaying 2 columns of 3 posts. Then you need to add the page variable to the query_posts attributes, by adding this before you query posts: <code> $paged = (get_query_var('page')) ? get_query_var('page') : 1; </code> and then changing the query_posts function calls to: <code> query_posts('showposts=3&amp;cat=1461&amp;paged='.$paged); </code> and <code> query_posts('showposts=3&amp;offset=3&amp;cat=1461&amp;paged='.$paged); </code> You'll also want to cheange you links to the previous and next pages by using something like the next_posts and prev_posts tags or you can simply make it yourself by adding /page/2 (for example) to the end of the category permalink - if you're using pretty URLs of course. It would probably be a good idea to check that you've got more than 3 posts to display before running the query for the second column too.
Showing different posts on category pages
wordpress
The following code provided by stackexchange-url ("Mike Schinkel"), creates a custom post type and a custom taxonomy. It makes the taxonomy to show up in the custom post type's column. Finally, it inserts some default terms. I would like to insert a second taxonomy for the custom post type (Page Content) called: Locations . (this second custom taxonomy should also show up in the column of the custom post type) How can I modify the code to archive that? <code> &lt;?php /** * Create the Page Content custom post type and the Page Section custom taxonomy */ add_action('init', 'my_init_method'); if (!class_exists('YourSite_PageContent')) { class YourSite_PageContent { static function on_load() { add_action('init',array(__CLASS__,'init')); add_filter('manage_page_content_posts_columns', array(__CLASS__,'manage_page_content_posts_columns')); add_filter('manage_posts_custom_column', array(__CLASS__,'manage_posts_custom_column'),10,2); add_action('restrict_manage_posts', array(__CLASS__,'restrict_manage_posts')); add_filter('parse_query', array(__CLASS__,'parse_query')); } static function init() { register_post_type('page_content',array( 'labels' =&gt; array( 'name' =&gt; __( 'Page Content' ), 'singular_name' =&gt; __( 'Page Content' ), 'add_new_item' =&gt; 'Add New Page Content', 'edit_item' =&gt; 'Edit Page Content', 'new_item' =&gt; 'New Page Content', 'search_items' =&gt; 'Search Page Content', 'not_found' =&gt; 'No Page Content found', 'not_found_in_trash' =&gt; 'No Page Content found in trash', ), 'public' =&gt; true, 'hierarchical' =&gt; false, 'taxonomies' =&gt; array( 'page_sections'), 'supports' =&gt; array('title','editor','thumbnail','custom-fields'), 'rewrite' =&gt; array('slug'=&gt;'page_content','with_front'=&gt;false), )); register_taxonomy('page_sections','page_content',array( 'hierarchical' =&gt; true, 'labels' =&gt; array( 'name' =&gt; __( 'Page Sections' ), 'singular_name' =&gt; __( 'Page Section' ), 'add_new_item' =&gt; 'Add New Page Section', 'edit_item' =&gt; 'Edit Page Section', 'new_item' =&gt; 'New Page Section', 'search_items' =&gt; 'Search Page Section', 'not_found' =&gt; 'No Page Sections found', 'not_found_in_trash' =&gt; 'No Page Sections found in trash', 'all_items' =&gt; __( 'All Page Sections' ), ), 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'page_sections' ), )); if (!get_option('yoursite-page-content-initialized')) { $terms = array( 'Footer', 'Header', 'Front Page Intro', 'Front Page Content', ); foreach($terms as $term) { if (!get_term_by('name',$term,'page_sections')) { wp_insert_term($term, 'page_sections'); } } update_option('yoursite-page-content-initialized',true); } } function manage_page_content_posts_columns($columns){ $new = array(); foreach($columns as $key =&gt; $title) { if ($key=='author') // Put the Page Sections column before the Author column $new['page_sections_column'] = 'Page Sections'; $new[$key] = $title; } return $new; } function manage_posts_custom_column( $column,$post_id ) { global $typenow; if ($typenow=='page_content') { $taxonomy = 'page_sections'; switch ($column) { case 'page_sections_column': $page_sections_column = get_the_terms($post_id,$taxonomy); if (is_array($page_sections_column)) { foreach($page_sections_column as $key =&gt; $page_sections) { $edit_link = get_term_link($page_sections,$taxonomy); $page_sections_column[$key] = '&lt;a href="'.$edit_link.'"&gt;' . $page_sections-&gt;name . '&lt;/a&gt;'; } echo implode(' | ',$page_sections_column); } break; } } } function parse_query($query) { global $pagenow; $qv = &amp;$query-&gt;query_vars; if ($pagenow=='edit.php' &amp;&amp; isset($qv['taxonomy']) &amp;&amp; $qv['taxonomy']=='page_sections' &amp;&amp; isset($qv['term']) &amp;&amp; is_numeric($qv['term'])) { $term = get_term_by('id',$qv['term'],'page_sections'); $qv['term'] = $term-&gt;slug; } } function restrict_manage_posts() { global $typenow; global $wp_query; if ($typenow=='page_content') { $taxonomy = 'page_sections'; $page_sections = get_taxonomy($taxonomy); wp_dropdown_categories(array( 'show_option_all' =&gt; __("Show All {$page_sections-&gt;label}"), 'taxonomy' =&gt; $taxonomy, 'name' =&gt; $taxonomy, 'orderby' =&gt; 'name', 'selected' =&gt; $wp_query-&gt;query['term'], 'hierarchical' =&gt; true, 'depth' =&gt; 3, 'show_count' =&gt; true, // This will give a view 'hide_empty' =&gt; true, // This will give false positives, i.e. one's not empty related to the other terms. TODO: Fix that )); } } } YourSite_PageContent::on_load(); } </code> EDIT (What I've done so far with no PHP skills): By modyfing the code this is what I've done so far: <code> &lt;?php /** * Create the Page Content custom post type and the Page Section custom taxonomy */ add_action('init', 'my_init_method'); if (!class_exists('YourSite_PageContent')) { class YourSite_PageContent { static function on_load() { add_action('init',array(__CLASS__,'init')); add_filter('manage_page_content_posts_columns', array(__CLASS__,'manage_page_content_posts_columns')); add_filter('manage_posts_custom_column', array(__CLASS__,'manage_posts_custom_column'),10,2); add_action('restrict_manage_posts', array(__CLASS__,'restrict_manage_posts')); add_filter('parse_query', array(__CLASS__,'parse_query')); } static function init() { register_post_type('page_content',array( 'labels' =&gt; array( 'name' =&gt; __( 'Page Content' ), 'singular_name' =&gt; __( 'Page Content' ), 'add_new_item' =&gt; 'Add New Page Content', 'edit_item' =&gt; 'Edit Page Content', 'new_item' =&gt; 'New Page Content', 'search_items' =&gt; 'Search Page Content', 'not_found' =&gt; 'No Page Content found', 'not_found_in_trash' =&gt; 'No Page Content found in trash', ), 'public' =&gt; true, 'hierarchical' =&gt; false, 'taxonomies' =&gt; array( 'page_sections'), 'supports' =&gt; array('title','editor','thumbnail','custom-fields'), 'rewrite' =&gt; array('slug'=&gt;'page_content','with_front'=&gt;false), )); register_taxonomy('locations','page_content',array( 'hierarchical' =&gt; true, 'labels' =&gt; array( 'name' =&gt; __( 'Locations' ), 'singular_name' =&gt; __( 'Page Section' ), 'add_new_item' =&gt; 'Add New Page Section', 'edit_item' =&gt; 'Edit Page Section', 'new_item' =&gt; 'New Page Section', 'search_items' =&gt; 'Search Page Section', 'not_found' =&gt; 'No Page Sections found', 'not_found_in_trash' =&gt; 'No Page Sections found in trash', 'all_items' =&gt; __( 'All Page Sections' ), ), 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'locations' ), )); register_taxonomy('page_sections','page_content',array( 'hierarchical' =&gt; true, 'labels' =&gt; array( 'name' =&gt; __( 'Page Sections' ), 'singular_name' =&gt; __( 'Page Section' ), 'add_new_item' =&gt; 'Add New Page Section', 'edit_item' =&gt; 'Edit Page Section', 'new_item' =&gt; 'New Page Section', 'search_items' =&gt; 'Search Page Section', 'not_found' =&gt; 'No Page Sections found', 'not_found_in_trash' =&gt; 'No Page Sections found in trash', 'all_items' =&gt; __( 'All Page Sections' ), ), 'query_var' =&gt; true, 'rewrite' =&gt; array( 'slug' =&gt; 'page_sections' ), )); if (!get_option('yoursite-page-content-initialized')) { $terms = array( 'Footer', 'Header', 'Front Page Intro', 'Front Page Content', ); foreach($terms as $term) { if (!get_term_by('name',$term,'page_sections')) { wp_insert_term($term, 'page_sections'); } } update_option('yoursite-page-content-initialized',true); } } function manage_page_content_posts_columns($columns){ $new = array(); foreach($columns as $key =&gt; $title) { if ($key=='author') // Put the Page Sections column before the Author column $new['page_sections_column'] = 'Page Sections'; $new[$key] = $title; } return $new; } function manage_posts_custom_column( $column,$post_id ) { global $typenow; if ($typenow=='page_content') { $locations_taxonomy = 'locations'; $page_sections_taxonomy = 'page_sections'; switch ($column) { case 'locations_column': $locations_column = get_the_terms($post_id,$locations_taxonomy); if (is_array($locations_column)) { foreach($locations_column as $key =&gt; $locations) { $edit_link = get_term_link($locations,$locations_taxonomy); $locations_column[$key] = '&lt;a href="'.$edit_link.'"&gt;' . $locations-&gt;name . '&lt;/a&gt;'; } echo implode(' | ',$locations_column); } break; case 'page_sections_column': $page_sections_column = get_the_terms($post_id,$page_sections_taxonomy); if (is_array($page_sections_column)) { foreach($page_sections_column as $key =&gt; $page_sections) { $edit_link = get_term_link($page_sections,$page_sections_taxonomy); $page_sections_column[$key] = '&lt;a href="'.$edit_link.'"&gt;' . $page_sections-&gt;name . '&lt;/a&gt;'; } echo implode(' | ',$page_sections_column); } break; } } } function parse_query($query) { global $pagenow; $qv = &amp;$query-&gt;query_vars; if ($pagenow=='edit.php' &amp;&amp; isset($qv['taxonomy']) &amp;&amp; $qv['taxonomy']=='page_sections' &amp;&amp; isset($qv['term']) &amp;&amp; is_numeric($qv['term'])) { $term = get_term_by('id',$qv['term'],'page_sections'); $qv['term'] = $term-&gt;slug; } } function restrict_manage_posts() { global $typenow; global $wp_query; if ($typenow=='page_content') { $taxonomy = 'page_sections'; $page_sections = get_taxonomy($taxonomy); wp_dropdown_categories(array( 'show_option_all' =&gt; __("Show All {$page_sections-&gt;label}"), 'taxonomy' =&gt; $taxonomy, 'name' =&gt; $taxonomy, 'orderby' =&gt; 'name', 'selected' =&gt; $wp_query-&gt;query['term'], 'hierarchical' =&gt; true, 'depth' =&gt; 3, 'show_count' =&gt; true, // This will give a view 'hide_empty' =&gt; true, // This will give false positives, i.e. one's not empty related to the other terms. TODO: Fix that )); } } } YourSite_PageContent::on_load(); } </code> I'm still struggling with this line: <code> function manage_page_content_posts_columns($columns){ $new = array(); foreach($columns as $key =&gt; $title) { if ($key=='author') // Put the Page Sections column before the Author column $new['locations_column'] = 'Locations'; $new['cb'] = '&lt;input type="checkbox"&gt;'; $new['title'] = 'Title'; $new['page_sections_column'] = 'Page Sections'; $new[$key] = $title; } return $new; } </code> I can't manage to place Page Sections before Locations. How to solve this?
I use the following in my filter hook <code> manage_edit-&lt;post-type&gt;_columns </code> <code> add_filter( 'manage_edit-visitor_columns', array( &amp;$this, '_wp_filter_visitor_columns' ) ); public function _wp_filter_visitor_columns( $columns ) { $columns = array( 'cb' =&gt; '&lt;input type="checkbox" /&gt;', 'title' =&gt; 'Name', 'type' =&gt; 'Type', //'state' =&gt; 'Current State', 'id' =&gt; 'Visitor ID', 'acct' =&gt; 'Using Account', ); return $columns; } </code> And to filter the column view, I use the following: <code> add_action( 'manage_posts_custom_column', array( &amp;$this, '_wp_filter_visitor_column_view' ) ); public function _wp_filter_visitor_column_view( $column ) { global $post; if ( $column == "type" ) { //$terms = get_the_term_list( $post-&gt;ID, 'v_types', '', ', ', '' ); //echo strip_tags( $terms ); $terms = wp_get_object_terms( $post-&gt;ID, 'v_types' ); echo $terms[0]-&gt;name; } elseif ( $column == "state" OR $column == "workstation" ) { $workstation = get_post_meta( $post-&gt;ID, 'v_workstation', true ); if ( $column == "workstation" ) echo $workstation; elseif ( $column == "state" ) echo 'Not coded....'; } elseif ( $column == "id" ) { echo get_post_meta( $post-&gt;ID, 'v_id', true ); } elseif ( $column == "acct" ) { $terms = wp_get_object_terms( $post-&gt;ID, 'v_accounts' ); echo $terms[0]-&gt;name; } } </code> I hope this helps you.
Adding a second custom taxonomy to a custom post type (both shown in its table)?
wordpress
I've seen some examples that use $_post instead of $post. What's the difference and when would you use $_post instead of $post? Example: <code> if (have_posts()) : while (have_posts()) : the_post(); if(!in_category("some-category", $_post )) { do_something(); } </code>
I'm not certain, but if you're talking about $_post as seen here: http://codex.wordpress.org/Function_Reference/in_category It's referring to a post ID so they've probably added the underscore to avoid confusion. The $post variable is a post object with all the details of the post. However, $_POST is a global PHP variable containing all the values sent from a form: http://php.net/manual/en/reserved.variables.post.php
When would you use $_post instead of $post?
wordpress
Easy question. Where does the self-hosted WordPress store version information?
If you need to get the wordpress version in your script, there is a global variable: <code> $wp_version </code> (right now it's something like <code> '3.1-RC3-17376' </code> ) It contains the wordpress version. If you need to acquire if from a file, you can read it from <code> /wp-includes/version.php </code> : <code> function getWPVersion() { $path = '/path/to/wp-install'; include $path.'/wp-includes/version.php'; return $wp_version; } </code> Wordpress Version Variables There is more information available in that file: <code> $wp_version </code> - The WordPress version string ('3.1-RC3-17376') <code> $wp_db_version </code> - Holds the WordPress DB revision, increments when changes are made to the WordPress DB schema (17056) <code> $tinymce_version </code> - The TinyMCE version string ('3393') <code> $manifest_version </code> - Holds the cache manifest version ('20111113') <code> $required_php_version </code> - Holds the required PHP version ('4.3') <code> $required_mysql_version </code> - Holds the required MySQL version ('4.1.2')
Where does WordPress store version number?
wordpress
I have a site where i'm using the All-In-One Cufon (Wordpress Plugin) , but having some issues getting it to render properly in IE. The website: [removed] The Problem: It works fine so far in Firefox and the other browsers like Chrome. Even in internet explorer the first time the site loads it works fine but when i refresh the page or visit any other pages by clicking a link on the site it stops working (The text is still visible but cufon rendering doesn't work) :o I have been trying to fix this since the past day without any success. I'm not 100% sure but i think it used to work fine awhile back but i just recently noticed this odd behavior and have no clue what could be making this happen. My first thought was a conflict of a plugin, but i tried disabling ALL the plugins except the cufon and it still does the same thing. Is anyone aware / experienced similar issue with their websites? and knows the solution? thanks in advance.
The issue seems to have been resolved in the latest Release Candidate of IE9.
wordpress site | All-in-one-cufon IE Issue
wordpress
I own a network of 100+ Wordpress based websites. All website are separate installations of Wordpress and are on different servers. I would like to create one contact form have it shown in the sidebar all of my Wordpress websites and capture the responses in one database (instead of getting 100's of emails). Ideally the form would be created and hosted in one place and then embedded into the other blogs (via iframe or other method?). That way I'd only have to make changes to the form in one place and have them apply to all sites. I know there are countless plugins for creating contact forms, but none that would seem to address this situation. Any help would be greatly appreciated. Further, I'm not opposed to hiring someone to help with this situation if it's beyond the scope of this websites. All the best, JB
the easiest way i can think of is to use a plugin that creates a form by shortcode like contact form 7 for example and I'll break it in to easy steps. Create the form on your main site or what ever site you would like to manage the forms data through. Create a page template with no header or footer just a plain loop and call <code> the_content </code> . Create a new page , add the Form's shortcode to it and set the template as your new page template. Get the URL of that page and create an iframe to it. On each site you would like to show the form just add the Iframe code to a sidebar text widget. and that should do it. Oh wait, you will probably need to add Contact form 7's Javascripts and css and i just read your question again and you are looking to save this forms in to database and since this plugin does'nt save to database on its own you can use an extenstion plugin called Contact Form 7 to Database or use a different forms plugin all together. Hope this helps
How do I add the same contact form to multiple wordpress sites and capture the response in one place or database?
wordpress
I need to pass a localized multidimensional javascript object to a page. The object is constructed using php and represents some wp-theme settings. I cant find a way to utilize wp_localize_script for this, as it will not parse multidimensional arrays. Instead I've come up with the solution to use a html5 data-* attribute for this and then using jQuery to retrieve it, hoping for this method to provide x-browser compatibility. So on the page where I need to access the localized data I let php output: <code> &lt;div id="localized" style="display:none" data-localized='{"user": "Doe", "skills": {"html":5, "css":4, "php":3} }'&gt; </code> I then get that localized data using: <code> var my_localazed_data = $('#localized').data('localized'); </code> It works fine. But my concern here is: 1) Is this browser compatible? 2) Are there any security concern to be aware of as compared to using wp_localize_script?
Q: 1.) Is this browser compatible? Yes, for all browsers supporting jQuery data() . jQuery is generally supported by most modern browsers. Q: 2) Are there any security concern to be aware of as compared to using wp_localize_script? <code> wp_localize_script() </code> is mainly doing the same but it's keeping the data on the serverside and not within the DOM. As always, making use of javascript and interacting with the DOM has security implications. You need to follow the rules to properly en- and de-code any arbitrary data safely so that injections can not introduce unintended behaviour.
security concerns if using html data-* attribute for l10n?
wordpress
WP_DEBUG is telling me: Notice: Undefined index: no_cat_base in myplugin.php on line 20 Here's the lines of code where I'm pulling the value of "no_cat_base" from my options array called "myoptions"... <code> $myoptions = get_option('my_settings'); if($myoptions['no_cat_base']){//This is line 20} </code> Is the correct fix for this... <code> if ( isset($myoptions['no_cat_base'])){//do something} </code>
just to be on the safe side use: <code> if (array_key_exists('no_cat_base', $myoptions) &amp;&amp; isset($myoptions['no_cat_base'])){ //do your thing } </code>
Undefined index error on options array element?
wordpress
I've got a working piece of javascript that contains an object literal. But I need to localize it, and I'm ytrying to figure out how to rewrite it so that I can get wp_localize_script() to accet it, and output the correct format. The non-localized (non dynamic) version looks like this: <code> var layoyt_config = { 'header' : 1 , 'footer' : 1 , 'ls' : {'sb1':1} , 'rs' : {'sb1':1,'sb2':1} , 'align' : 'center' }; </code> Now, to have those values generated by php (based on some wp_settings) I want to use wp_localize_script, so I can take it from there: <code> var layoyt_config = my_localized_data.layoyt_config; </code> And to get that data in to that object property I 'thought' I could do this, but obviously not: <code> $data = array( 'layout_config' =&gt; { 'header' : 1 , 'footer' : 1 , 'ls' : {'sb1': 1} , 'rs' : {'sb1': 1,'sb2': 1} , 'align' : 'center' } ); wp_localize_script('my-script-handle', 'my_localized_data', $data); </code> As this will cause PHP parse error I've tried to rewrite the json to array syntax, as wp_localize_script will convert that back to object notation, but this also does not work for me: <code> $data = array( 'layout_config' =&gt; array( 'header' =&gt; 1 , 'footer' =&gt; 1 , 'ls' =&gt; array('sb1'=&gt;1) , 'rs' =&gt; array('sb1'=&gt;1,'sb2'=&gt;1) , 'align' =&gt; 'center' ) ); wp_localize_script('my-script-handle', 'my_localized_data', $data); </code> And while this runs smoothly trhough the php parser, I do not get the expected output in my page source, as my_localized_data.layout_config becomes a String "Array", here is the output: <code> &lt;script type='text/javascript'&gt; /* &lt;![CDATA[ */ var wpkit_localized_data = { layout_config: "Array" }; /* ]]&gt; */ &lt;/script&gt; </code> So.. How can I do this (or do I just have to accept that I must 'flatten' my object into discrete vars like: <code> lc_header = '1'; ls_ls_sb1 = '1'; etc... </code>
Indeed, <code> wp_localize_script() </code> is simple , it just adds quotes around the values and escapes the content, expecting all of them to be strings. However, there is the <code> l10n_print_after </code> key of the array, which will be printed without any interference at all. It can be used to execute arbitrary code after the strings are passed. You can use it to pass your extra data. <code> $data = array( 'layout_config' =&gt; { 'ls' : {'sb1': 1} } ); $reshuffled_data = array( 'l10n_print_after' =&gt; 'my_localized_data = ' . json_encode( $data ) . ';' ); wp_localize_script('my-script-handle', 'my_localized_data', $reshuffled_data); </code> You will end up with code like this: <code> var my_localized_data = {}; // What is left of your array my_localized_data = {'layout_config': {'ls': {'sb1': 1}}}; // From l10n_print_after </code>
pass object/JSON to wp_localize_script
wordpress
I am calling recent comments into my template with <code> $comment-&gt;post_title </code> the variable length is specified like this : <code> SUBSTRING(comment_content,1,180) </code> how could I write a conditional statement just for comments that exceed the limits of the vairable > 180 ? I was thinking It would be good to have a ... for longer comments and a more link.
By using a function to perform that: <code> recent_comment_text_more($comment_content) </code> that function would look like (in case you're using PHP, part of your code looks from another language): <code> function recent_comment_text_more($comment_content, $more_href) { if (strlen($comment_content) &gt; 180) { $comment_content = substr($comment_content, 0, 177) . sprintf('&lt;a href="%s"&gt;... (more)&lt;/a&gt;', $more_href); } return $comment_content; } </code> Good luck! Multibyte charset safe variant As pointed out in a comment, e.g. for UTF-8, see mb_internal_encoding() for specifying the encoding to use: <code> function recent_comment_text_more($comment_content, $more_href) { if (mb_strlen($comment_content) &gt; 180) { $comment_content = mb_substr($comment_content, 0, 177) . sprintf('&lt;a href="%s"&gt;... (more)&lt;/a&gt;', $more_href); } return $comment_content; } </code>
Return count for characters in the comment and perform action based on the length
wordpress
An item in SideBarOther shows up on the main article listing page, but when I select an article (same page layout, the article replaces the listing), the item isn't there. There are two items in SideBarOther, and only the 2nd one has this problem (see code below). If I remove the first one, it is correctly gone from from both the listing page and article page, and the 2nd one still only shows up on the listing page. I'm using an unmodified "News Magazine Theme 640" theme. <code> &lt;a href="http://www.facebook.com/pages/[our-page]/[our number]" title="[our name]" target="_blank"&gt;&lt;img src="../pics/fbook_button.jpg" boder="0" alt="[our name]"&gt;&lt;/a&gt; &lt;script src="http://connect.facebook.net/en_US/all.js#xfbml=1"&gt;&lt;/script&gt;&lt;fb:like href="http://www.facebook.com/pages/[our name]/[our number]" layout="box_count" show_faces="false" width="50"&gt;&lt;/fb:like&gt; </code> NO, I am not confusing which item is not appearing - the local directory reference ../pics on the first item works on all pages. The Facebook Like button is the one that isn't appearing on all pages. This is not hosted by Wordpress, rather Wordpress v. 2.92 is installed on our website. (I tried the official wordpress forum, and got no reply.) Thanks UPDATE I "viewed page source" in Firefox, and THE CODE IS THERE on the article page, and it's IDENTICAL to the listing page. So why isn't it displayed??? I tried the Opera browser, same results. I added another copy of the first widget, and two of them appear on the listing page, and on the article page - the box automatically adjusted to accommodate them.
There was a conflict with the Facebook Share plugin. If you add the <code> &lt;script type="text/javascript" src="http://connect.facebook.net/en_US/all.js#xfbml=1"&gt;&lt;/script&gt; </code> code somewhere before the Facebook Share code, the like button then works, and the share button still works.
Button in SideBarOther widget not showing up on all pages
wordpress
I've placed the string below into my custom permalinks input but it does not appear to have any effect... /%category%/%postname%/ I'm trying to insure that my post links are in the form of /category-name/post-name
Without a link to the site in question, it's hard to understand the exact problem. However, if the issue is the actual word "category" is being includes (i.e. example.com/category/category-name/post-name) then I would use this plugin (it's one I use on almost every site) http://wordpress.org/extend/plugins/wp-no-category-base/
How to change permalinks to show categoryname/post-name?
wordpress
I develop a plugin that has a not too small number of settings. So far, there has been a fixed number of them, so I store them in a Wordpress option. Now I consider letting users define (an arbitrary number of) styles, that is sets of options. Since these will still be rather general options, none of the categories listed in the Codex really fits. Storing all that stuff in one option is clearly not a good idea, but creating a whole database tables does not feel right, either. What are your recommendations? Note that I post one idea I have as an answer in order to separate it from the question. Would mark the question CW, but that seems to be disabled here?
The hierarchy of storing data roughly goes like this (from less functional/complex to more): Transients API Options API Settings API Database Tables Custom file cache Since from your description Options are too limited and database too complex, I would look at Settings.
How to store a medium amount of options?
wordpress
While moving a client's WP site to a new host (single site, not multi), I found that Dashboard> > Users lists two admin accounts (above the detailed shows All(2) Administrator (2) ) but only shows one in the detailed list below; and only one admin account shows in the wp_users table with the ID of 1. Where is this extra admin account? And how do I remove it? (No need to warn me about security: there are no signs of hacking to the account, and in moving to the new host, all passwords have been changed, security tweaked up, fresh 3.0.4 core files uploaded and the database dump shows only one admin.)
That's typically the result of users deleting accounts directly in the database. The functions that count users queries to the usermeta table to determine how many users are of a given type, when users do manual deletion they often forget to remove relational data left in the meta table, which in turn throws off the counts. Images below are to show how what i've said above is true(though i'll admit there's always a chance this isn't the problem you're experiencing). Two admins Deleting a user record Viewing the list of admins after user record deletion If you want to check the installation for redundant user meta, you could find user IDs that don't have a corresponding record in the users table in PhpMyAdmin using some SQL. <code> SELECT DISTINCT user_id FROM wp_usermeta WHERE NOT EXISTS(SELECT ID FROM wp_users WHERE ID = user_id) </code> If you'd like that query wrapped into some WP ready code, just ask.. :)
Two admins in Users and one in the database?
wordpress
I'm trying to modify the display of the <code> edit-comments.php </code> admin page and I'm not seeing any filters in it comparable to <code> manage_posts_columns </code> etc. Is there an easy way to do this? I'm thinking the only real way to go about doing this is to extend WP_Comments_List_Table with my own class, overwrite the <code> get_columns </code> and other related functions, and just add my own page to the admin menu which uses this new class in the same way that edit-comments.php uses WP_Comments_List_Table . Is there an easier way to do this that I'm just not seeing?
I'm afraid that there is no easy way to get that done yet because the only hook i found is manage_comments_custom_column and that is an action hook and not a filter hook so you can't add columns like manage_posts_columns. so as far as i can tell the long way here is the only way. but you can almost duplicate the default edit-comments.php and extending small classes like wp_post_comments_list_table and more.
Are there any filters to add additional columns to the list table on edit-comments.php?
wordpress
I have a custom post type called movies and I need to quickly switch the template that displays the movies cpt on the front end via a link. How can this be done? Files I have: single-movies.php template-movieslanding.php template-movieswholesale.php Functionality: A link group is displayed on each of the three templates as demonstrated below. These links are only displayed to logged in staff. The staff are not technical in the least and need a simplistic solution. Views: Overview | Landing Page | Wholesale When each link is clicked I need to switch to that template. All templates use the same custom post type. Thanks! ~Matt
you can do it like this: <code> //add movies_view to query vars add_filter('query_vars', 'my_query_vars'); function my_query_vars($vars) { // add movies_view to the valid list of variables $new_vars = array('movies_view'); $vars = $new_vars + $vars; return $vars; } </code> then add a template redirect based on that query_var: <code> add_action("template_redirect", 'my_template_redirect'); // Template selection function my_template_redirect() { global $wp; global $wp_query; if ($wp-&gt;query_vars["post_type"] == "movies") { // Let's look for the property.php template file in the current theme if (array_key_exists('movies_view', $wp-&gt;query_vars) &amp;&amp; $wp-&gt;query_vars['movies_view'] == 'overview'){ include(TEMPLATEPATH . '/single-movies.php'); die(); } if (array_key_exists('movies_view', $wp-&gt;query_vars) &amp;&amp; $wp-&gt;query_vars['movies_view'] == 'landing'){ include(TEMPLATEPATH . '/template-movieslanding.php'); die(); } if (array_key_exists('movies_view', $wp-&gt;query_vars) &amp;&amp; $wp-&gt;query_vars['movies_view'] == 'wholesale'){ include(TEMPLATEPATH . '/template-movieswholesale.php'); die(); } } } </code> then add this var to your links For Overview add ?movies_view=overview to the url For Landing Page add ?movies_view=landing to the url For Wholesale add ?movies_view=wholesale to the url Hope this helps
How to quickly switch custom post type singular template?
wordpress
After changing themes I get <code> Fatal error: Call to undefined function add_editor_style() in /mydir/wp-content/themes/evolve/functions.php on line 8 </code> I cannot even login to the administration panel
Simply Delete or rename the theme's directory.
How do I manually revert back to my old theme?
wordpress
Currently I am working on Wordpress and I want to know can I add 1 more page in admin panel appearance menu so that it looks like this: ? <code> Appearance Themes Widgets Menus Editor </code> I want to add one more page after Editor like "Theme option".
You'd use the add_theme_page() function. Basically, it's the same as adding any other settings page, but instead of add_options_page(), you use add_theme_page(). More info: http://codex.wordpress.org/Creating_Options_Pages http://codex.wordpress.org/Settings_API http://codex.wordpress.org/Adding_Administration_Menus
How to add another page in appearance tab of admin panel?
wordpress
I just got WP running on my own server. I am not trying to lock things down more. What permissions should the db user have to my WP db?
If you did want to lock things down.... a normal wordpress site will usually only require the database user to have SELECT, INSERT, UPDATE and DELETE. If you want to use the automatic update feature it will also require CREATE and ALTER. Some plugins may require other permissions but most won't.
What are the recommended database permissions for WordPress?
wordpress
I'm looking to see if there is already a plugin that does a gallery slide show like Huffington Post does where it shows either one image or video then you click next to see the next one. There is no need for a rating system. I'm hoping there is so I don't have to figure out how to make one :) http://www.huffingtonpost.com/lee-brenner/viral-videos-2010_b_801501.html Other examples: http://bleacherreport.com/articles/437878-larissa-riquelme-and-the-25-hottest-superfan-photoshoots/page/1 http://www.businessinsider.com/super-bowl-commercials-super-bowl-xlv-2011-2#volkswagen--the-force-1 FOUND A SOLUTION USING NEXTGEN: Actually someone found this post and they found the solution :) http://gregrickaby.com/2010/07/add-an-anchor-to-nextgen-gallery-image-browser.html
FOUND A SOLUTION USING NEXTGEN: Actually someone found this post and they found the solution :) http://gregrickaby.com/2010/07/add-an-anchor-to-nextgen-gallery-image-browser.html
Looking for WordPress Slideshow Gallery Plugin
wordpress
I'm combining two of my plugins into one. I'd like to make the activation routine of the second plugin a checkbox selection in the settings panel of the new plugin. However, I'm unsure how to execute functions when the options are submitted. How can I do this? The my-plugin-options.php is basically this... <code> &lt;form method="post" action="options.php"&gt; &lt;?php wp_nonce_field('update-options'); ?&gt; //options form goes here &lt;input type="hidden" name="action" value="update" /&gt; &lt;input type="hidden" name="page_options" value="check1, check2, check3, etc" /&gt; &lt;p class="submit"&gt; &lt;input type="submit" class="button-primary" value="&lt;?php _e('Save Changes') ?&gt;" /&gt; &lt;/p&gt; &lt;/form&gt; </code> And its called from my main plugin file with this... <code> function my_settings_admin() { include_once dirname(__FILE__) . '/my-plugin-options.php'; } add_options_page( 'My Plugin Settings', 'My Plugin Settings', 'manage_options', 'my-plugin-options.php', 'my_settings_admin', $my_plugin_dir.'/favicon.png', 'top'); </code>
If you are using the Settings API , then I'd say to add a check and function call for it in your sanitization callback (from register_setting).
How can I add function calls to my plugin's options.php default submit routine?
wordpress
Specifically, I am making a custom rss feed. I have modeled it after the rss2 feed that is in the wp-includes folder. I can successfully retrieve all posts using the standard query_posts('posts_per_page=-1'). Here is how I am attempting to get just the ones posted in the past year: <code> $today = date('Y-m-d'); $newdate = strtotime ( '-1 year' , strtotime ( $today ) ) ; $ayearago = date( 'Y-m-d' , $newdate ); function filter_where($where = '') { $where .= " AND post_date &gt;= '" . $ayearago . "'"; return $where; } add_filter('posts_where', 'filter_where'); query_posts($query_string); </code> Yes this returns only posts from 2011 forward. Can someone help me figure out why? Here is the main source code from my custom feed page called feed-postlist.php: <code> /** * Custom RSS Feed * * @package WordPress */ header('Content-Type: ' . feed_content_type('rss-http') . '; charset=' . get_option('blog_charset'), true); $more = 1; echo '&lt;?xml version="1.0" encoding="'.get_option('blog_charset').'"?'.'&gt;'; ?&gt; &lt;rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/" xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:sy="http://purl.org/rss/1.0/modules/syndication/" xmlns:slash="http://purl.org/rss/1.0/modules/slash/" &lt;?php do_action('rss2_ns'); ?&gt; &gt; &lt;?php $today = date('Y-m-d'); $newdate = strtotime ( '-1 year' , strtotime ( $today ) ) ; $ayearago = date( 'Y-m-d' , $newdate ); function filter_where($where = '') { $where .= " AND post_date &gt;= DATE('" . $ayearago . "')"; return $where; } add_filter('posts_where', 'filter_where'); query_posts('posts_per_page=-1'); ?&gt; &lt;channel&gt; &lt;title&gt;&lt;?php bloginfo_rss('name'); wp_title_rss(); ?&gt;&lt;/title&gt; &lt;atom:link href="&lt;?php self_link(); ?&gt;" rel="self" type="application/rss+xml" /&gt; &lt;link&gt;&lt;?php bloginfo_rss('url') ?&gt;&lt;/link&gt; &lt;description&gt;&lt;?php bloginfo_rss("description") ?&gt;&lt;/description&gt; &lt;lastBuildDate&gt;&lt;?php echo mysql2date('D, d M Y H:i:s +0000', get_lastpostmodified('GMT'), false); ?&gt;&lt;/lastBuildDate&gt; &lt;language&gt;&lt;?php echo get_option('rss_language'); ?&gt;&lt;/language&gt; &lt;sy:updatePeriod&gt;&lt;?php echo apply_filters( 'rss_update_period', 'hourly' ); ?&gt;&lt;/sy:updatePeriod&gt; &lt;sy:updateFrequency&gt;&lt;?php echo apply_filters( 'rss_update_frequency', '1' ); ?&gt;&lt;/sy:updateFrequency&gt; &lt;?php do_action('rss2_head'); ?&gt; &lt;?php while( have_posts()) : the_post(); ?&gt; &lt;item&gt; </code> Thanks, Ryan
Hi @Ryan Long: You have two problems: You need to wrap the result of <code> date( 'Y-m-d' , $newdate ); </code> in a SQL <code> DATE() </code> function, and You define <code> $ayearago </code> outside of the <code> filter_where() </code> function so it's not in scope within the function. You need to move the code that sets <code> $ayearago </code> into the <code> filter_where() </code> function like this: <code> function yoursite_filter_where($where = '') { $today = date('Y-m-d'); $newdate = strtotime ( '-1 year' , strtotime ( $today ) ) ; $ayearago = date( 'Y-m-d' , $newdate ); $where .= " AND post_date &gt;= DATE('{$ayearago}')"; return $where; } </code> Let me know if that works for you...
How do I correctly get all posts within the last year using the query_posts function?
wordpress
I have been looking for hours for an example on how to do this. I have 2 simple taxonomies, Type, Size. I need to create a custom form with the 2 taxonomies available as Select list/filter. Please help! tx in advance <code> &lt;form role="search" method="get" id="searchform" action="&lt;?php bloginfo('home'); ?&gt;"&gt; &lt;input type="text" value="" name="s" id="s" /&gt; &lt;?php function get_terms_dropdown($taxonomies, $selectname,$args){ $myterms = get_terms($taxonomies, $args); $selected = "selected"; $output ="&lt;select name='".$selectname."'&gt;&lt;option selected='".$selected."'&gt;Select&lt;/option&gt;'"; foreach($myterms as $term){ //$term_taxonomy=$term-&gt;$taxonomies; $term_slug=$term-&gt;slug; $term_name =$term-&gt;name; $output .="&lt;option value='".$term_slug."'&gt;".$term_name."&lt;/option&gt;"; } $output .="&lt;/select&gt;"; return $output; } $taxonomies = array('location'); $taxonomies2 = array('function'); $taxonomies3 = array('sector'); $args = array('order'=&gt;'ASC','hide_empty'=&gt;false); echo "&lt;br /&gt;".get_terms_dropdown($taxonomies,'location' ,$args)."&lt;br /&gt;"; echo get_terms_dropdown($taxonomies2,'function' ,$args)."&lt;br /&gt;"; echo get_terms_dropdown($taxonomies3, 'sector' ,$args)."&lt;br /&gt;"; ?&gt; &lt;input type="submit" id="searchsubmit" value="Search" /&gt; &lt;/form&gt; </code>
take a look at scribu Query Multiple Taxonomies plugin it creates a drill-down navigation widget
WP Search using taxonomy terms
wordpress
I need to add an additional filter based on a category for posts that have a custom post_type. For example, I have a page located at <code> /category/tasks </code> that lists all tasks. I need to make it so I can have additional pages that filter even further like <code> /category/tasks/current </code> , <code> category/tasks/future </code> , <code> /category/tasks/past </code> . I can figure out how to get the query to work, I just am not sure how to pick up the type of filter from the URL. (currently it goes to a page not found error when adding the additional word after /tasks)
If I'm understand the question right.... first login to the admin section. then click on "categories" its in the "Posts" accordion box. When your there you'll see all your categories. Next, following your example, you need to make "current", "future", and "past" all children of "tasks". this should achieve the desired URL. Let me know if I can help any more.
How to detect filter in URL in Category page?
wordpress
I'm really at loss as to why this isn't working: I am using a shortcode to display a query on a custom post type + taxonomy, this is the segment of it: <code> // - arguments - $args = array( 'post_type' =&gt; 'customposttypename', 'taxonomyname' =&gt; 'alpha', 'post_status' =&gt; 'publish', ); // - query - $my_query = null; $my_query = new WP_query($args); while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); // - variables - $custom = get_post_custom($post-&gt;ID); </code> ... and then variables keep going. The thing is though, when I run the loop, it shows me all of the default post content (i.e. title, content, etc.), but refuses to show custom post type content and halts on the last line above (line 145), i.e. <code> $custom = get_post_custom($post-&gt;ID); </code> giving me the following error.. Notice: Undefined variable: post in C:\xampplite...\functions.php on line 145 Notice: Trying to get property of non-object in C:\xampplite...\functions.php on line 145 Then down here it shows me the title, content, etc. normally (just no custom post type content) Anybody have a clue what' I'm doing wrong? Thank you!
Notice: Trying to get property of non-object Would indciate that <code> $post </code> has no scope inside your function. One simple solution here would be to globalise <code> $post </code> so it has scope, effectively fixing the error. However, whenever you create a query, or run the loop and call <code> the_post </code> method this gives you access to the WordPress template tags . Rather then put in global statements you could call <code> get_the_ID() </code> which should of course contain the given post's id(ie. the current post for that iteration of the loop). Update your problem line to read.. <code> $custom = get_post_custom( get_the_ID() ); </code> And that should clear up the problem, of course noting giving <code> $post </code> scope inside the function would also work, it just wouldn't look as poetic!.. ;) Small side question back to the asker, what are you looking for when you call <code> get_post_custom </code> , are you checking for some particular meta keys, or looping over every meta item you find? There may be some room for improvement there(if you're interested).
Custom Post Type Loop within Shortcode
wordpress
So basically I have custom post types set up, and one of these is called Packages. It's for a web design/SEO company. I need the nav link Packages to show in the navigation and all of the child links for the link Packages will be all of the posts inside the Packages custom post type. If that's too confusing, just tell me and I can explain more. What I need to know is how can I make the posts in the Packages custom post type to show as the child pages of the Products page. Any way this can be done? Preferably with PHP or jQuery. Edit: This is what I have so far: <code> &lt;?php $pages = get_pages('parent=0'); foreach ($pages as $pagg) { $key = 'childpages'; $id = get_the_ID(); $args = array( 'post_type' =&gt; 'products' ); $loop = new WP_Query( $args ); if(get_post_meta($id, $key, true) == 'products') : $option = '&lt;li&gt;&lt;a href="'.get_page_link($page-&gt;ID).'"&gt;'; $option .= $pagg-&gt;post_title; $option .= '&lt;/a&gt;'; $option .= '&lt;ul class="children"'; while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); $option .= '&lt;li&gt;'; $option .= the_title(); $option .= '&lt;/li&gt;'; endwhile; $option .= '&lt;/ul&gt;&lt;/li&gt;'; else : $option = '&lt;li&gt;&lt;a href="'.get_page_link($page-&gt;ID).'"&gt;'; $option .= $pagg-&gt;post_title; $option .= '&lt;/a&gt;&lt;/li&gt;'; endif; echo $option; } ?&gt; </code> If the page has a custom field of <code> childpages </code> with the value <code> products </code> , display them as the child pages. Will this even work?
Hi @ Jared One idea is to look at the <code> 'rewrite' </code> argument for custom post types. You can also create a <code> [shortcode] </code> and create a page in your functions.php file for displaying the Packages.
Custom Post Types set up, how do I style the main slug page?
wordpress
Hey Folks I have a page called Journal that I would like to filter all my posts from a specific post category.I created a function but am not sure how to do it. I tried get_post etc but it throws a format error and am also now sure what I should be ammending. I realize that I could do this in the main template tag but I would rather use a function if possible. <code> function JournalPage() { if(is_page("Journal")) { } } add_filter('the_content', 'JournalPage'); </code>
You need to query them: (for more info see inline comments) <code> /** * Template Name: Journal */ // define( 'TEXTDOMAIN', 'your_textdomain_string' ); // To be sure, we reset the query, so nothing get's lost wp_reset_query(); global $wp_query; $query_cat = new WP_Query( array( 'orderby' =&gt; 'date comment_count' // date = default, 2nd param = comment_count ,'order' =&gt; 'ASC' ,'post_type' =&gt; 'post' ,'post_status' =&gt; 'publish' ,'category_name'=&gt; 'slug_of_cat' // change value here ) ); if ( $query_cat-&gt;have_posts() ) : while ( $query_cat-&gt;have_posts() ) : $query_cat-&gt;the_post(); // check for password if ( post_password_required() ) : the_content(); elseif ( current_user_can('manage_options') ) : // see codex roles &amp; caps for more info // display some decent message here if restricting accessability to the post // or place something like echo '&lt;span class="whatever"&gt;'.sprintf(__(You can %1$s this page), TEXTDOMAIN), edit_post_link( __('edit', TEXTDOMAIN), '&amp;nbsp;', ')', $post_id ).'&lt;/span&gt;'; return; else : // here goes your content endif; endwhile; else : // else; no posts _e( 'Nothing published so far.', TEXTDOMAIN ); endif; // endif; have_posts(); wp_rewind_posts(); // for a sec. query </code>
Posts on a Page using functions.php
wordpress
I need to display something of a mini author statistic in my sidebar on the single posts page. I'm using the PHP code widget, to allow me to insert PHP code into a widget. What I've done is run a loop in the sidebar like this: <code> &lt;?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?&gt; &lt;ul&gt; &lt;li&gt; &lt;?php echo 'Posts made: ' . get_usernumposts(4); ?&gt; &lt;p&gt; Author Rank: &lt;?php the_author_meta('user_level'); ?&gt; &lt;br&gt; Author's Name: &lt;?php the_author_meta('display_name'); ?&gt; &lt;br&gt; User ID: &lt;?php the_author_meta('ID'); ?&gt; &lt;/p&gt; &lt;/li&gt; &lt;?php endwhile; else: ?&gt; &lt;p&gt;&lt;?php _e('No posts by this author.'); ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; </code> So that shows the number of user posts for the author ID '4'. And yes, the function still works properly though it's deprecated. I obviously need something a bit more dynamic, as the author data varies post to post, so a static ID is not going to do the trick. I've no idea why there isn't something like <code> &lt;?php the_author_meta('post_count'); ?&gt; </code> I suppose that would be too convenient. I've seen a lot of queries that select post counts in various ways, all of which either aren't what I need or do not work in or outside of my loop in the sidebar. My first thought, though I am no expert with PHP is to assign a variable to the value of usernumposts that pulls the data from the value of <code> &lt;?php the_author_meta('ID'); ?&gt; </code> I don't know if this is possible at all, but it would certainly achieve my goals. So can this be done? How? And if not - what are my other options? Thanks!
To get the number of posts published by a user i found the solution was to call <code> count_user_posts() </code> , passing in the appropriate user id. <code> &lt;?php echo 'Posts made: ' . count_user_posts( get_the_author_meta('ID') ); ?&gt; </code> In translation ready form. <code> &lt;?php printf( 'Posts made: %d', count_user_posts( get_the_author_meta('ID') ) ); ?&gt; </code> Storage in a variable. <code> &lt;?php $user_post_count = count_user_posts( get_the_author_meta('ID') ); ?&gt; </code>
Show author post count in sidebar - Variable
wordpress
The wordpress function is used for submitting data programatically. Standard fields to submit to incude the content, excerpt, title, date and many more. What there is no documentation for is how to submit to a custom field. I know it is possible with the <code> add_post_meta($post_id, $meta_key, $meta_value, $unique); </code> function. What I don't know is how to include that into the standard wp_insert_post function. <code> &lt;?php $my_post = array( 'post_title' =&gt; $_SESSION['booking-form-title'], 'post_date' =&gt; $_SESSION['cal_startdate'], 'post_content' =&gt; 'This is my post.', 'post_status' =&gt; 'publish', 'post_type' =&gt; 'booking', ); wp_insert_post( $my_post ); ?&gt; </code> Any ideas, Marvellous
Hi @ Robin I Knight If you read the documentation for <code> wp_insert_post </code> , it returns the post ID of the post you just created. If you combine that with the following function <code> __update_post_meta </code> (a custom function I acquired from this site and adapted a bit) <code> /** * Updates post meta for a post. It also automatically deletes or adds the value to field_name if specified * * @access protected * @param integer The post ID for the post we're updating * @param string The field we're updating/adding/deleting * @param string [Optional] The value to update/add for field_name. If left blank, data will be deleted. * @return void */ public function __update_post_meta( $post_id, $field_name, $value = '' ) { if ( empty( $value ) OR ! $value ) { delete_post_meta( $post_id, $field_name ); } elseif ( ! get_post_meta( $post_id, $field_name ) ) { add_post_meta( $post_id, $field_name, $value ); } else { update_post_meta( $post_id, $field_name, $value ); } } </code> You'll get the following: <code> $my_post = array( 'post_title' =&gt; $_SESSION['booking-form-title'], 'post_date' =&gt; $_SESSION['cal_startdate'], 'post_content' =&gt; 'This is my post.', 'post_status' =&gt; 'publish', 'post_type' =&gt; 'booking', ); $the_post_id = wp_insert_post( $my_post ); __update_post_meta( $the_post_id, 'my-custom-field', 'my_custom_field_value' ); </code>
WP insert post PHP function and Custom Fields
wordpress
I've created a WordPress 3.0 site w/ MultiSite enabled and the BuddyPress plugin installed (latest available versions of each). Initially, the site did not have a captcha enabled and now there are hundreds of spam accounts created. By default, the Super Admin panel for Users only shows 15 users at a time. I need to delete several hundred users and going through this page by page is monotonous. Is there plugin available which would assist with bulk user deletion? I'd like to be able to select and delete a few hundred users at a time (or even better do a regex search by username). Thanks.
Super Admin > Users. Screen Options (top right) > Show on screen __ users. Be careful, listing hundreds of users could kill your server. Heh!
Bulk User Deletion
wordpress
( Moderator's note: Title was originally: "query/database optimisation") I'm written a function for a custom "filter" search panel that allows users to select terms from up to four custom taxonomies. I'm running the queries directly against the database and the query is averaging half a second to execute (with terms for all four taxonomies and one result returned). This seems pretty slow to me. I was wondering if there's anything I can do to either optimise the query or even the database to make this more efficient/faster. Perhaps writing a view, even? I have experience with MS-SQL but not much with MySQL and I'm not sure how things are different. Here's my function code: <code> function filter_resources($phase,$wa,$aus,$topics){ global $wpdb; $querystr=" SELECT * FROM $wpdb-&gt;posts A LEFT JOIN $wpdb-&gt;term_relationships B ON(A.ID = B.object_id) LEFT JOIN $wpdb-&gt;term_taxonomy C ON(B.term_taxonomy_id = C.term_taxonomy_id) LEFT JOIN $wpdb-&gt;terms D ON(C.term_id = D.term_id) LEFT JOIN $wpdb-&gt;term_relationships BB ON(A.ID = BB.object_id) LEFT JOIN $wpdb-&gt;term_taxonomy CC ON(BB.term_taxonomy_id = CC.term_taxonomy_id) LEFT JOIN $wpdb-&gt;terms DD ON(CC.term_id = DD.term_id) LEFT JOIN $wpdb-&gt;term_relationships BBB ON(A.ID = BBB.object_id) LEFT JOIN $wpdb-&gt;term_taxonomy CCC ON(BBB.term_taxonomy_id = CCC.term_taxonomy_id) LEFT JOIN $wpdb-&gt;terms DDD ON(CCC.term_id = DDD.term_id) LEFT JOIN $wpdb-&gt;term_relationships BBBB ON(A.ID = BBBB.object_id) LEFT JOIN $wpdb-&gt;term_taxonomy CCCC ON(BBBB.term_taxonomy_id = CCCC.term_taxonomy_id) LEFT JOIN $wpdb-&gt;terms DDDD ON(CCCC.term_id = DDDD.term_id) WHERE A.post_type = 'resources' AND A.post_status = 'publish' AND C.taxonomy = 'phase-of-learning' AND D.term_id = '$phase' AND CC.taxonomy = 'wa-curriculum' AND DD.term_id = '$wa' AND CCC.taxonomy = 'australian-curriculum' AND DDD.term_id = '$aus' AND CCCC.taxonomy = 'topics' AND DDDD.term_id = '$topics' ORDER BY A.post_date DESC"; return $wpdb-&gt;get_results($querystr,OBJECT); } </code> Thanks!
Hi @goatlady: While this is really a MySQL question it does help to understand the WordPress SQL schema and also I love trying to optimize SQL queries so rather than send you off to stackexchange-url ("StackOverflow") I'll try to answer you here. You may still want to post it over there to get some other opinions. And while I don't fully understand your requirement I think I understand what you are asking I think I do so I'd like to present the following to see if it meets your needs better. I don't have your data so it is a little hard for me to very that it indeed works but like I said, I think it meets your needs: <code> function filter_resources($phase,$wa,$aus,$topics){ global $wpdb; $sql =&lt;&lt;&lt;SQL SELECT t.slug,p.* FROM wp_posts p INNER JOIN wp_term_relationships tr ON p.ID=tr.object_id INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN wp_terms t ON tt.term_id = t.term_id WHERE 1=1 AND p.post_type = 'resources' AND p.post_status = 'publish' AND t.term_id IN (%d,%d,%d,%d) AND CONCAT(tt.taxonomy,'/',t.term_id) IN ( 'phase-of-learning/%s', 'wa-curriculum/%s', 'australian-curriculum/%s', 'topics/%s' ) GROUP BY p.ID HAVING COUNT(*)=4 ORDER BY p.post_date DESC SQL; $sql = $wpdb-&gt;prepare($sql, $phase,$wa,$aus,$topics, // For the %d replacements $phase,$wa,$aus,$topics // For the %s replacements ); $results = $wpdb-&gt;get_results($sql,OBJECT); return $results; } </code> Basically this gives you all posts where all of your taxonomy terms are applied and it does so by doing a freeform query to match all posts that have the taxonomy/terms applied but limits to only those posts that have all terms applied grouping by <code> wp_post.ID </code> and finding all records for which the post is joined 4 times. When you run a MySQL <code> EXPLAIN </code> the optimization looks pretty good compared to what you had; many fewer tables joined. Hopefully this was the logic you needed. Caching with the Transients API And if you are trying to improve performance you might also consider caching the results in a "transient" for a limited amount of time (1 hour, 4 hours, 12 hours or more?) This blog post describes how to use the WordPress Transients API : Overview of WordPress’ Transients API Here's the basic logic for transients: <code> define('NUM_HOURS',4); // Time to cache set for your use case $data = get_transient( 'your_transient_key' ); if( !$data ) { $data = // Do something to get your data here set_transient( 'your_transient_key', $data, 60 * 60 * NUM_HOURS ); } </code> To use transients in your <code> filter_resources() </code> function it might instead look like this: <code> define('RESOURCE_CACHE_HOURS',4); function filter_resources($phase,$wa,$aus,$topics){ $resources = get_transient( 'yoursite_filtered_resources' ); if(!$resources) { global $wpdb; $sql =&lt;&lt;&lt;SQL SELECT t.slug,p.* FROM wp_posts p INNER JOIN wp_term_relationships tr ON p.ID=tr.object_id INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN wp_terms t ON tt.term_id = t.term_id WHERE 1=1 AND p.post_type = 'resources' AND p.post_status = 'publish' AND t.term_id IN (%d,%d,%d,%d) AND CONCAT(tt.taxonomy,'/',t.term_id) IN ( 'phase-of-learning/%s', 'wa-curriculum/%s', 'australian-curriculum/%s', 'topics/%s' ) GROUP BY p.ID HAVING COUNT(*)=4 ORDER BY p.post_date DESC SQL; $sql = $wpdb-&gt;prepare($sql, $phase,$wa,$aus,$topics, // For the %d replacements $phase,$wa,$aus,$topics // For the %s replacements ); $resources = $wpdb-&gt;get_results($sql,OBJECT); $hours = RESOURCE_CACHE_HOURS * 60 * 60; set_transient( 'yoursite_filtered_resources', $resources, $hours); } return $resources; } </code> UPDATE Here's another take on the code that is attempting to handle the cases where less than four criteria are selected by the user: <code> define('RESOURCE_CACHE_HOURS',4); function filter_resources($phase,$wa,$aus,$topics){ $resources = get_transient( 'yoursite_filtered_resources' ); if(!$resources) { $terms = $taxterms = array(); if (!empty($phase)) $taxterms[$phase] = 'phase-of-learning/%s'; if (!empty($wa)) $taxterms[$wa] = 'wa-curriculum/%s'; if (!empty($aus)) $taxterms[$aus] = 'axustralian-curriculum/%s'; if (!empty($topics)) $taxterms[$topics] = 'topics/%s'; $count = count($taxterms); $having = ($count==0 ? '' : "HAVING COUNT(*)={$count}"); $values = array_keys(array_flip($tax_terms)); $values = array_merge($values,$values); // For %d and $s $taxterms = implode("','",$taxterms); $terms = implode(',',array_fill(0,$count,'d%')); global $wpdb; $sql =&lt;&lt;&lt;SQL SELECT t.slug,p.* FROM wp_posts p INNER JOIN wp_term_relationships tr ON p.ID=tr.object_id INNER JOIN wp_term_taxonomy tt ON tr.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN wp_terms t ON tt.term_id = t.term_id WHERE 1=1 AND p.post_type = 'resources' AND p.post_status = 'publish' AND t.term_id IN ({$terms}) AND CONCAT(tt.taxonomy,'/',t.term_id) IN ('{$taxterms}') GROUP BY p.ID {$having} ORDER BY p.post_date DESC SQL; $sql = $wpdb-&gt;prepare($sql,$values); $resources = $wpdb-&gt;get_results($sql,OBJECT); $hours = RESOURCE_CACHE_HOURS * 60 * 60; set_transient( 'yoursite_filtered_resources', $resources, $hours); } return $resources; } </code>
Optimize Multiple Taxonomy Term MySQL Query?
wordpress
Is there a way (plugin, or something else) to set it where there is a drop down on the "New Post" page that allows you to choose a post type and the fields change allowing you to filter what content you are putting into a post without confusing a user by having 20 different custom fields on the "New Post" page. Also, is there a plugin or other that can make custom fields with different value types (textarea, list, file upload, etc)?
This was asked over and over: stackexchange-url ("Add custom field automatically to custom page types") stackexchange-url ("Redesigning Custom Post Type “Add New” page") and if you are not into coding the you can use plugins like Simple fields More Fields Verve Meta Boxes hope this helps
How to change what the post creation page looks like?
wordpress
Is there a way to mark a plugin as "never upgrade this plugin" ? I stackexchange-url ("can't upgrade my OpenID plugin"), and this prevents me from clicking the otherwise convenient "Upgrade All Plugins" button.
Hi @ripper234: Either 1.) edit the plugin header comment in the main plugin file and change the <code> Version: </code> value to something like 999, or 2.) move the plugin to the "Must Use" plugin directory: <code> /wp-content/mu-plugins </code> . Here's an example from <code> /wp-content/plugins/akismet/akismet.php </code> of the plugin header comment for Akismet: <code> /* Plugin Name: Akismet Plugin URI: http://akismet.com/ Description: Used by millions, Akismet is..... Version: 2.5.2 Author: Automattic Author URI: http://automattic.com/wordpress-plugins/ License: GPLv2 */ </code> Here's a blog post that explains the "Must Use" plugins (albeit I don't understand why he chose the title he chose): Creating a custom functions plugin for end users
Disable a plugin from ever upgrading?
wordpress
I can't find much documentation on using XML-RPC and custom post types. I have a specific requirement that remote posting and management (the client has an in-house cms) must be used for a custom post type.
@keatch is correct that out-of-the-box WP XML-RPC does not support post types other than 'post' and 'page'. However, a quick stroll through the code indicates that this may be relatively easy to change. In WP 3.0.4, <code> xmlrpc.php </code> , line 1989, we have the function <code> mw_newPost() </code> (which does the heavy lifting). At line 2005 there is an <code> if-else </code> checking the post type, but it would be easy to extend by inserting additional checks starting at line 2021. Then at line 2059 we have a <code> switch($post_type) </code> that would also be easy to extend. And ... that's about it for insert. At line 2196 the data is wrapped up and inserted, and at line 2213 the custom fields are attached to the post and nothing else seems to care about <code> post_type </code> . There are probably a few more places to extend for other commands, but just search on <code> post_type </code> (without the '$') and look to see if it will make any difference. Note well: this is a core WP file and any hacks thereto are going to get overwritten by the next update to core. On the other hand, these are mostly trivial changes and you could make sure that the client notifies you before they do an update to core. Reply to Comment: Life is more complicated than Rarst's comment would make it seem. And the excellent answer he pointed to is solving a problem significantly simpler that what your question appears to be asking about. In kongo09's comment to Rarst's own answer in that thread he observed that 'there is probably no help' coming in this area. Custom Posts are a bit of an afterthought in the WP code. When you look at the logic in a number of places you see code that originally said "do this thing with a post". When pages came along that code had to be expanded to deal with posts and pages. And then it had to be expanded again to deal with customs posts. This is a classic programming evolution: 1, 2, many. The xmlrpc code is one of the places that is stuck at "2" (and sometimes even at "1"). In trying to add functionality to core code, you are stuck choosing between several possible paths, all of which have their downsides. Submit a request/bug ticket and wait for it to be fixed by the core team. This may take some time and your client may not be willing to wait. Ref. kongo09's statement. Fix the code yourself and submit a patch. Reapply your patch with each new update to core while you wait for it to be accepted. This is sort of what I was suggesting, although I handwaved the details. Managing the revisions across possibly conflicting changes will be easier if you use something like Mercurial's MqMerge. I wouldn't try this with SVN. Check each merge carefully because this is the type of code that can get totally hosed across revs. Copy a substantial amount of the core xmlrpc code, make your changes, and hook it in via the <code> xmlrpc_methods </code> filter mentioned in the post he linked to. This means you have effectively forked the code. Although it makes for an "easy update" it is also an easy way to miss crucial security changes made to the code you forked. This is a not insignificant problem as simply googling on "wordpress xmlrpc security" will show you. Note that 3.0.1 and 3.0.2 both had XML security issues. You're probably going to be forced to do #3 or #2 in spades because the more you look at the WP section of xmlrpc, the more you realize how haphazard it is regarding what you can do with what type of objects E.g. using the WP xml interface you can only create a page, but the MW method <code> mw_newPost() </code> (invoked by the WP method <code> wp_newPost() </code> ) permits new pages or new posts, but not new custom posts -- and so it goes. To fully support custom posts will require a significant effort and keeping it in sync with changes to the core may be problematic, regardless of the method you choose. Update - 2 weeks later: So a friend just asked me a question that was almost exactly the same as Jeremy's. It forced me to take a really hard look at the XMLRPC code to see how we can make the changes but avoid the "modify core" problem raised by Rarst. It turns out that there are a very large number of undocumented <code> do_action() </code> hooks plus (more importantly for these purposes) a mentioned-but-undocumented <code> apply_filters('xmlrpc_methods', $this-&gt;methods); </code> (line 203) that allows for arbitrary modification/addition/deletion of methods. I still maintain that the XMLRPC code is a swamp, but this particular <code> apply_filter() </code> lets you take a left turn out of the swamp without modifying core code.
XML-RPC and Custom Post Types
wordpress
I've been having some issues with my Wordpress install allowing me to access subdirectories, specifically a CodeIgniter install at mydomain.com/codeigniter. I know that technically it should work just fine as-is and recognize folders as they are created. However, this is not happening. I suspect it has something to do with a plugin, but I've tried disabling all of them and the problem still occurs (directs me to the Wordpress 404 page). I've found a solution in the meantime, however. If I create a subdomain, something changes and everything works like it should, accessing the folder both via the direct path and via the subdomain name. Any help? I've tried all sorts of fun stuff with my .htaccess files in both directories, but changing them doesn't do anything. Update: Here's the Wordpress .htaccess in the root folder: <code> DirectoryIndex index.php index.htm index.html AddHandler application/x-httpd-php52 .php .php5 .php4 .php # BEGIN WordPress &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_URI} !^/?codeigniter/ RewriteRule . /index.php [L] &lt;/IfModule&gt; # END WordPress </code> And the CodeIgniter .htaccess file in the /codeigniter/ subdirectory. <code> DirectoryIndex index.php index.htm index.html AddHandler application/x-httpd-php52 .php .php5 .php4 .php &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase /codeigniter RewriteCond $1 !^(index\.php|images|robots\.txt) RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ index.php?/$1 [L,QSA] &lt;/IfModule&gt; </code>
Even though static files and directories do work with a mod_rewrite'd wordpress installation in the servers root you might need to exclude your CodeIgniter subdirectory from that mod_rewrite lineup. You can do so by placing an additional .htaccess file into the CodeIgniter directory and disable mod_rewrite in there: <code> &lt;IfModule mod_rewrite.c&gt; RewriteEngine off &lt;/IfModule&gt; </code> Related: apache - Disable mod_rewrite for subdirectory This normally does the job for me. But it can be less trivial in case that subdirectory needs a mod_rewrite configuration on it's own (as some PHP Frameworks need). To understand how the apache configuration works, please see Configuration Files (Apache Manual) and AllowOverride directive (Apache Manual) .
Wordpress .htaccess subdirectory problem
wordpress
The last time I stackexchange-url ("asked a question that required an opinion response"), I was awarded the dubious tumbleweed badge. I'm fearful of adding to my collection, but here goes :) I'm considering writing an option into my theme that would force all pages and posts to have a .html extension and all category landing pages to have URLs without the category base name in them. For this reason, I'd like to get opinions on how feasible it is to switch between my custom URL structure and the WordPress default structure, in the event the site owner wants to revert back after changing to the new structure. In the new structure a category landing page would be addressed without the category base name in the url like so: site.com/blue-widgets This would normally be written: site.com/category/blue-widgets And for this to work, I'm also requiring that all posts and pages end in an extension like .html so as to differentiate between categories and posts of the same name. For example, site.com/blue-widgets.html
WordPress › WP No Category Base « WordPress Plugins correctly reverts permalinks because it doesn't alter them in the first place.
If I remove Category base from my URLs, how difficult will rollback be?
wordpress
I'm seeing this box in the "Edit Post" page, using the Simple Facebook Connect plugin 0.25 and WordPress 3.0.4: If you can see this, then there is some form of problem showing you the Facebook publishing buttons... All other Facebook-related plugins are disabled. How can I debug this? Posted an issue .
I added "http://" in the Facebook URL (See the issue for more details).
Problem with Simple Facebook Connect
wordpress
Is there any way to allow logged-in users to post comments without them being held for moderation, while requiring that any comment from anonymous users be approved? I have developed a system for users who are members of our organization to log in automatically with their LDAP accounts, and would like for any of them to be able to comment without their comments being held for moderation. However, I want all anonymous third-party comments to be held for moderation. I don't see any way to do that with the current comment options - I can either hold all comments for moderation, hold all comments by users without 2 approved comments, or require users to log in to comment. How can I achieve this?
Here you go, paste this code in your themes <code> functions.php </code> file: <code> function loggedin_approved_comment($approved) { // No need to do the check if the comment is already approved anyway. if (!$approved) { if (is_user_logged_in()) { // Note: 1/0, not true/false $approved = 1; } } return $approved; } // Action allows the comment automatic approval to be over-ridden. add_action('pre_comment_approved', 'loggedin_approved_comment'); </code> Make sure to enable Comment Moderation inside the Settings-panel of your WordPress install.
Hold comments for moderation only if user is not logged in
wordpress
Is there a built in function to load scripts only for particular template? At them moment I am doing like so: <code> if (is_page('portfolio') || is_page('gallery')){ wp_register_script('jScrollpane', get_bloginfo('stylesheet_directory') . '/js/jquery.jscrollpane.min.js'); wp_enqueue_script('jScrollpane'); } </code> and it works as long as I call the pages "portfolio" and "gallery". I would like to have it more reusable, how can I achieve that? Thank you in advance
You can use <code> is_page_template('template.php') </code> and just replace template.php with your template name.
Load scripts only for selected template
wordpress
Is it possible to allow people to utilize their email as their username?
As far as i know it should be possible to login with your email with wp 3.1, which will come soon. Using an email as username is already possible. "@" and "." are allowed characters for usernames. Hope that helps.
Allowing an email as the username?
wordpress
I'm using the Share and Follow plugin on my site. I like it for the most part, but the "interactive share buttons" - the ones that appear at the front of the post - are on the first line of my post. This might be OK, except that it shoves the images that are at the beginning of the majority of my posts out of alignment (on both my main page and individual posts). I would much prefer that the buttons appear under the title, but before the first line of content in my post. But because it's a plugin, I can't figure out how to change where the buttons appear.
Since it's a plugin you probably don't want to edit it directly as then it will revert every time the plugin is updated. It looks like the problem is that the style has a float:left on it. <code> &lt;div style="float:left; padding-top: 10px; padding-right: 10px; padding-bottom: 10px; padding-left: 10px; " class="interactive_left"&gt; </code> If you remove that float:left you get exactly what you want. Unfortunately for you the style is inline instead of part of a style sheet so I think your only option might be to find that bit of code in the plugin and edit it directly. You could ask the plugin author to move it to a stylesheet to make that easier but it's really up to them.
Moving Share Buttons from a Plugin
wordpress
Is there a way to prove information to Facebook so I can control what the title and description information is that comes up when pasting the front page of my blog on facebook? Right now, it seems to grab a random post... not the latest... for th information. I'd prefer to either set the information myself for the front page OR insure that it shows information from my 1st/featured post. How can I get control over this? (again, this isn't related to a "like" button, or anything... but posting the root URL straight to a Facebook status. Sharing the whole site, not a post.)
Have you tried adding the Open Graph metadata? http://developers.facebook.com/docs/opengraph/ I think that should give Facebook the right hints.
How to control Facebook share information for the front page?
wordpress
Currently creating a plugin with cURL and I need a place that will work for most WordPress servers (Unix or Windows) to store my cookie file. Anyone have a suggestion or best practices? I've been googling for a while now and I think I found something about wp_temp_dir, but googling that keyword gives me only a thousand and one results about solving some install error.
Transients seem to be appropriate storage. Just note that if you will generate a lot of this and they will be disposable then you stackexchange-url ("will need to cleanup old transients"). As for your cURL/filename issue - it is bad practice to use cURL directly in WordPress. WP provides HTTP API that abstracts remote requests. Unfortunately it is bit poorly documented. As far as I understand you pass cookies in arguments array with <code> cookies </code> key to its functions.
WordPress Plugin: Where should I put my cookies for cURL?
wordpress
I work at a radio station that has several WP user roles -- for simplicity sake, let's say Admin, Programmer, Subscriber, in decreasing order of ability. Currently, Admin users need to approve comments left by Programmer users. How do I auto-approve Programmer-level comments, without letting that user level administrate comments globally? Thank you!
Role Approved Comment plugin http://wordpress.org/extend/plugins/role-approved-comment/ This plugin will allow any specified role to have their comments automatically approved.
Capability for allowing user to post own comments without moderation
wordpress
I came across stackexchange-url ("this question") while writing this question. I have one question that extends upon that question. I figured out that you use the <code> get_delete_post_link </code> filter to create a new url for my actions (or a similar function -- In any case, I'm using that one with the boolean at the end). Only thing is, I don't know how to capture the event now. Some help would be appreciated considering I can't find many examples of post row actions on Google. :-/ <code> public function _wp_filter_get_delete_post_link( $post_id, $deprecated, $force_delete = false ) { if ( ! empty( $deprecated ) ) { _deprecated_argument( __FUNCTION__, '3.0.0' ); } $post = &amp;get_post( $post_id ); if ( ! $post ) return; if ( strcmp($post-&gt;post_type, "visitor") ) return; $post_type_object = get_post_type_object( $post-&gt;post_type ); if ( !$post_type_object ) return; if ( !current_user_can( $post_type_object-&gt;cap-&gt;delete_post, $post-&gt;ID ) ) return; // http://localhost/wordpress/wp-admin/post.php?post=163&amp;action=trash&amp;_wpnonce=a56abdcbb3 $action = ( $force_delete ? 'logout' : 'login' ); $delete_link = add_query_arg( 'action', $action, admin_url( sprintf( $post_type_object-&gt;_edit_link, $post-&gt;ID ) ) ); return wp_nonce_url( $delete_link, "$action-{$post-&gt;post_type}_{$post-&gt;ID}" ); } </code> And, if you're needing some more information on how I'm using it, here's some more code: <code> public function _wp_post_row_actions( $actions, $post ) { if ( $post-&gt;post_type == 'visitor' ) { //unset( $actions['edit'] ); unset( $actions['inline hide-if-no-js'] ); unset( $actions['trash'] ); unset( $actions['view'] ); $state = get_post_meta( $post-&gt;ID, 'v_state', true ) === 'in'; if ( $state ) { $actions['trash'] = get_delete_post_link( $post-&gt;ID, '', true ); // Logout // get_delete_post_link } else { $actions['trash'] = get_delete_post_link( $post-&gt;ID ); // Login } } return $actions; } </code> EDIT: Well, the above isn't complete. I just noticed that it doesn't actually generate a link which is weird. So, I guess what I'm asking is for a way to customize the Post Row Actions for my custom post type by adding a "Logout/Login" link in place of the <code> $actions['trash'] </code> link.
The main problem is that $actions accepts the whole anchor tag for the link and get_delete_post_link function outputs just the url. So if You are just looking to replace the label "Trash" then you can use the post_row_actions filter hook with a simple function Something like this <code> add_filter('post_row_actions','my_action_row') function my_action_row(){ if ($post-&gt;post_type =="visitor"){ //remove what you don't need unset( $actions['inline hide-if-no-js'] ); unset( $actions['trash'] ); unset( $actions['view'] ); //check capabilites $post_type_object = get_post_type_object( $post-&gt;post_type ); if ( !$post_type_object ) return; if ( !current_user_can( $post_type_object-&gt;cap-&gt;delete_post, $post-&gt;ID ) ) return; //the get the meta and check $state = get_post_meta( $post-&gt;ID, 'v_state', true ); if ($state == 'in'){ $actions['trash'] = "&lt;a class='submitdelete' title='" . esc_attr(__('Delete this item permanently')) . "' href='" . get_delete_post_link($post-&gt;ID, '', true) . "'&gt;" . __('Logout') . "&lt;/a&gt;"; }else{ $actions['trash'] = "&lt;a class='submitdelete' title='" . esc_attr(__('Delete this item permanently')) . "' href='" . get_delete_post_link($post-&gt;ID, '', true) . "'&gt;" . __('Login') . "&lt;/a&gt;"; } } return $actions; } </code> This will generate a logout if the meta is "IN" and login if other wise but both links will delete the post. and i would add a check to see if the post is already in the trash. But its a start and i hope it helps.
Custom Post Row Actions
wordpress
For some reason the below code works until I hit the third page and gives 404. Is it possible to fix it without using any plugins? <code> &lt;?php $temp = $wp_query; $wp_query = null; $wp_query = new WP_Query('cat='. $id .'&amp;posts_per_page=4&amp;paged='.$paged); while ($wp_query-&gt;have_posts()) : $wp_query-&gt;the_post(); ?&gt; &lt;?php get_the_content() ?&gt; &lt;?php endwhile; ?&gt; &lt;?php if ( $wp_query-&gt;max_num_pages &gt; 1 ) : ?&gt; &lt;?php previous_posts_link( __( 'Previous', 'themename' ) ); ?&gt; &lt;?php next_posts_link( __( 'Next', 'themename' ) ); ?&gt; &lt;?php endif; ?&gt; &lt;?php $wp_query = null; $wp_query = $temp;?&gt; </code>
Try creating a new instance of WP_Query and at the end use wp_reset_query(); like this: <code> &lt;?php $my_query = new WP_Query(); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $my_query-&gt;query('cat='. $id .'&amp;posts_per_page=4&amp;paged='.$paged); while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt; &lt;?php get_the_content() ?&gt; &lt;?php endwhile; ?&gt; &lt;?php if ( $my_query-&gt;max_num_pages &gt; 1 ) : ?&gt; &lt;?php previous_posts_link( __( 'Previous', 'themename' ) ); ?&gt; &lt;?php next_posts_link( __( 'Next', 'themename' ) ); ?&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_query(); ?&gt; </code>
Broken category pagination
wordpress
I'm writing a plugin for work because our main website is being ported to WordPress eventually. I've got multiple custom post types planned for this plugin and would like to group them all into one main menu. Basically, I want the "Visitors" link to be placed under "Argus Admin". The other links aren't necessary to be added as I can "hack" those wherever I want. <code> $v_args = array( 'labels' =&gt; array ( 'name' =&gt; 'Visitors', 'singular_name' =&gt; 'Visitor', 'add_new_item' =&gt; 'Register New Visitor', // TODO: http://codex.wordpress.org/Function_Reference/register_post_type#Arguments ), 'public' =&gt; true, 'publicly_queryable' =&gt; false, 'exclude_from_search' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; 'argus', // TODO: This doesn't work... 'hiearchical' =&gt; false, 'supports' =&gt; array( '' ), 'register_meta_box_cb' =&gt; array ( &amp;$this, '_wp_visitor_meta_box_cb' ), ); register_post_type( $post_type, $v_args ); </code> This my menu page that I created: <code> add_menu_page( 'Argus', 'Argus Admin', 'manage_options', 'argus', array( &amp;$this, '_wp_argus_main_panel' ), '', -1 ); </code>
You got it right but you need to wait for WordPress 3.1 where its actually implemented. if you can't wait you can change 'show_in_menu' to false and use add_submenu_page() function define 'argus' as top page and add the Visitors "manually" under Argus Admin menu. so your code would be: <code> $v_args = array( 'labels' =&gt; array ( 'name' =&gt; 'Visitors', 'singular_name' =&gt; 'Visitor', 'add_new_item' =&gt; 'Register New Visitor', ), 'public' =&gt; true, 'publicly_queryable' =&gt; false, 'exclude_from_search' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; 'flase', 'hiearchical' =&gt; false, 'supports' =&gt; array( '' ), 'register_meta_box_cb' =&gt; array ( &amp;$this, '_wp_visitor_meta_box_cb' ), ); register_post_type( $post_type, $v_args ); </code> and then <code> add_menu_page( 'Argus', 'Argus Admin', 'manage_options', 'argus', array( &amp;$this, '_wp_argus_main_panel' ), '', -1 ); add_submenu_page( argus, 'Visitors', 'Visitors', 'manage_options' , 'visitors' , 'edit.php?post_type=visitors'); </code> Hope this Helps
Custom Post Type Menus
wordpress
I have a loop to show my custom post type of 'case_studies'. It originally showed all posts until I wanted to just show 3 specific posts. The problem is that it only shows the first post in my list of 'p=54,49,44'. What am I doing wrong? <code> $case_studies = new WP_Query(); $count = 0; $case_studies-&gt;query('post_type=case_studies&amp;p=54,49,44'); while($case_studies-&gt;have_posts()) : $case_studies-&gt;the_post(); $count++; $custom = get_post_custom($post-&gt;ID); $case_studies_image_url = $custom['second_image'][0]; </code>
I think you need to change: <code> $case_studies-&gt;query('post_type=case_studies&amp;p=54,49,44'); </code> to <code> $case_studies-&gt;query_posts( array( 'post__in' =&gt; array( 54, 49, 44 ) ) ); </code> I'd look at this page for LOTS more examples. http://codex.wordpress.org/Function_Reference/query_posts . when your there search for "Multiple Posts/Pages Handling". Hope this helps, I'm still new to wordpress.
Query of custom post types only shows first post
wordpress
I want to add &amp; reset default value for my theme options while activate and deactivate a theme More clearly something like this <code> if(theme active) add_option(); // add new option to the theme and register default setting for one time only if(theme deactivate) delete_option(); // reset current option and delete default setting for one time only </code> Question How know is theme active or not? What a function or hook for this one. Let me know
Hi @haha: I think what you are looking for was answered here: <a href="stackexchange-url Theme Activate Hook
How to add or delete default value theme options while activate and deactivate theme
wordpress
I've read a couple questions/answers on here but still am a little bit confused. My goal: To have domain1.com and domain2.com under one wordpress installation but have different content (separate blogs) accessible through one admin login (domain1.com/wp-admin). I currently have GoDaddy hosting but I'm using document root for another site so I currently have wordpress installed in a sub-directory. Do I need to have wordpress installed in doc root? I hear terms like MultiSite and Create a Network but I see them as basically the same thing. Am I wrong in thinking this? What do I need to do to accomplish this goal? What steps do I need to follow first? How do I point the 2 domain names to one installation? Thanks in advance.
Hi @centr0: "MultiSite" and "Create a Network" are the same thing in WordPress 3.x. Follow the steps found in Create a Network in a new subdirectory and this tutorial by Otto should show you have to map domains using the WordPress MU Domain Mapping plugin ("MU" is the legacy description of Multisite, just ignore that confusion.) It will be much easier to do this on a new install than try to do in an existing install. Though you can do it, you will have a lot more pain to try to convert an existing install. Better just to export then import any existing content. And if at all possible, get a different hosting account. Most of the WordPress people on the Linkedin WordPress group talk about how GoDaddy overloads servers and you especially don't want an overloaded shared server for Multisite. Maybe you'll consider getting a new account for this? I'm a fan of A Small Orange web hosting in no small part due to the fact they have a US$25/ year account with 150Mb of storage (and they have been my webhost for 5+ years.) But almost any website will do you better than GD.
Multiple blogs, different domain names, one install to rule them all
wordpress
I have a couple blogs / wordpress sites that I post pictures on. I have noticed that most of the pictures I post with the nextgen gallery plug in never show up in google images search. Is there a way to fix this?
Have you filled out the "alt" tags properly. The chances of being indexed are less if the tag is not included. Additionally, the file name for the image should not be "quor7b.jpg" unless it's a photo of a Quor7b. The file name should also reflect the image (e.g. rose.jpg).
SEO images in Nextgen Galleries
wordpress
When you register a custom column like so: <code> //Register thumbnail column for au-gallery type add_filter('manage_edit-au-gallery_columns', 'thumbnail_column'); function thumbnail_column($columns) { $columns['thumbnail'] = 'Thumbnail'; return $columns; } </code> by default it appears as the last one on the right. How can I change the order? What if I want to show the above column as the first one or the second one? Thank you in advance
You are basically asking a PHP question, but I'll answer it because it's in the context of WordPress. You need to rebuild the columns array, inserting your column before the column you want it to be left of : <code> add_filter('manage_posts_columns', 'thumbnail_column'); function thumbnail_column($columns) { $new = array(); foreach($columns as $key =&gt; $title) { if ($key=='author') // Put the Thumbnail column before the Author column $new['thumbnail'] = 'Thumbnail'; $new[$key] = $title; } return $new; } </code>
Change order of custom columns for edit panels
wordpress
Is there any way to check whether the user has an SEO plugin installed, so as if they do not I can insert my metas etc.
Hi @Liam: , What you are going to need to do is create a list of the top SEO plugins and themes and then document how each implements meta and develop a strategy for each. And/or maybe you can ask your users upon activation if they are using an SEO plugin much like Akismet asks users to enter an API key.
Check if SEO plugin installed
wordpress
How can I allow each user to manage their own terms for a custom taxonomy when logged in on edit-tags page? user will only show &amp; manage terms that only created by him not others for a custom taxonomy. But Admin and editor can manage all. How can I do that? Any help will be appreciated. Thanks.
Thanks for the AWESOME solution MikeSchinkel :D I just did the following updates in the code and it worked like a charm: <code> add_filter('list_terms_exclusions', 'yoursite_list_terms_exclusions', 10, 2); function yoursite_list_terms_exclusions( $exclusions ) { $currentScreen = get_current_screen(); if( current_user_can( 'my_custom_capability_assigned_to_specific_users' ) &amp;&amp; !current_user_can( 'manage_options' ) // Show everything to Admin &amp;&amp; is_object( $currentScreen ) &amp;&amp; $currentScreen-&gt;id == 'edit-&lt;my_taxonomy&gt;' &amp;&amp; $currentScreen-&gt;taxonomy == '&lt;my_taxonomy&gt;' ) { // Get term_id's array that you want to show as per your requirement $terms = implode( ',', $term_id ); $exclusions = ( empty( $exclusions ) ? '' : $exclusions ) . ' AND' . ' t.`term_id` IN (' . $terms . ')'; } return $exclusions; } </code>
Multiple users – only allow them to manage their own terms for custom taxonomy when logged in
wordpress
I need to display a list of current tasks. Each task has a custom post_type and a start date and end date. Can someone tell me how to modify my query so it will pick up any tasks that have a start date in the past and an end date in the future? (There's another meta_key named 'end_date') Here's my query: <code> $todays_date = time(); $args = array ('post_type' =&gt; 'tasks', 'meta_key' =&gt; 'start_date', 'meta_compare' =&gt; '&gt;', 'meta_value' =&gt; $todays_date, 'orderby' =&gt; 'meta_value' ); $tasks = get_posts($args); </code> The problem with the query above is that it's showing tasks that in the future, but haven't started yet.
change your query a bit: <code> $todays_date = time(); $args = array ('post_type' =&gt; 'tasks', 'meta_key' =&gt; ''end_date, 'meta_compare' =&gt; '&lt;', 'meta_value' =&gt; $todays_date, 'orderby' =&gt; 'meta_value' ); $tasks = get_posts($args); </code> and then for each one of this posts get the start_date meta and compare with $today something like: <code> $today = strtotime($today); foreach ($tasks as $task_post){ $start = strtotime(get_post_meta($task_post-&gt;ID, start_date, true)); if ($today &gt; $start){ //to task stuff here } } </code> Hope this helps.
Custom query for custom post_type
wordpress
I have the following query in WordPress to call custom post meta, everything is working fine, with one exception, whichever query is second is echoing nothing. Sorry for the WordPress post, but for those unfamiliar the ' <code> get_post_meta($post-&gt;ID </code> ' is retrieving the post ID for the first one and then echoing the same for the second, I need to close the first query but don't know how. <code> &lt;h3 class="body_heading"&gt; &lt;?php $soon_events = get_post_meta($post-&gt;ID, 'coming_soon_events', true); if ($soon_events) : echo $soon_events; endif; ?&gt; &lt;/h3&gt; &lt;h3 class="body_heading clear"&gt; &lt;?php $feat_events = get_post_meta($post-&gt;ID, 'featured_events', true); if ($feat_events) : echo $feat_events; endif; ?&gt; &lt;/h3&gt; </code>
Try <code> &lt;?php wp_reset_query(); ?&gt; </code> after each function. See Function Reference/wp reset query « WordPress Codex
Non-Closing PHP Query in WordPress Loop
wordpress
Can I create a template and load it without associating a page/post to it in WordPress? The template will list custom posts in XML. [update] I have a jquery carousel that loads an XML file through ajax. I am storing each slide as a custom post type call 'carousel_slide'. I want to create an XML feed with these custom post types. At first I created the feed outside wordpress, including wp-load.php and using WP_Query. This worked fine but I now realize that I need a multi-lingual plugin (WPML) to be loaded as well. This is why I want to create a wp template instead. However if I create a template, I need to assign a page to it to be able to load it. I'd rather not create an empty page simply to be able to call a template. I am new to WordPress development and might have overlooked an obvious solution.
The basic answer - you can easily load template (or any PHP file really) with *drumroll* <code> load_template() </code> . :) As for best way to implement your custom feed, I think it would make sense to do it by analogue with native WP feeds. You register feed name and handler function with <code> add_feed() </code> and load template in that handler. Example: <code> add_action('init','custom_feed_setup'); function custom_feed_setup() { add_feed('custom-post-type-xml', 'custom_feed_template'); } function custom_feed_template($input) { load_template('whatever'); } </code>
How to load a template without it being assigned to a page/post?
wordpress
I've a problem with permission. Is there a specific permission to let an user with Editor Role, manage the custom menu of a theme, and only this options? The item that is under Appereance -> Menu, to be clear. I'm using the capability plugin. Must I write a custom hook to enable only the use of custom menu editor ? TIA Edit: I've code a simple solution. See below my answer!
You need to give the editor role the 'edit_theme_options' permission, but that will also unlock other theme options like widgets to those users.
Manage custom menu for an Editor?
wordpress
I'm using custom permalinks "/%category%/%postname%/". Whenever a post title contains quotes or apostrophes they appear in the URL. Can someone tell me how prevent them from appearing in the slug? I am running WordPress 3.0.4.
In WordPress, "---" and " -- " become em-dashes (&#8212; <code> &amp;#8212; </code> ) and "--" becomes an en-dash (&#8212; <code> #8212; </code> ). The sanitize_title_with_dashes() function doesn't catch these. That function uses the databased copy, but the title displayed to the user always goes through a texturize function. So if we replace en/em dashes on their way into the database, the net result will be the same and avoid these bad URL cases the titles are re-texturized. <code> add_action( 'title_save_pre', 'do_replace_dashes' ); function do_replace_dashes($string_to_clean) { # The html entities (&amp;#8211; and &amp;#8212;) don’t actually work but I include them for kicks and giggles. $string_to_clean = str_replace( array('&amp;#8212;', '—', '&amp;#8211;', '–', '‚', '„', '“', '”', '’', '‘', '…'), array(' -- ',' -- ', '--','--', ',', ',,', '"', '"', "'", "'", '...'), $string_to_clean ); return $string_to_clean; } </code>
How to prevent apostrophes and quotes from appearing in permalinks?
wordpress
I've been told by my clients that scheduled jobs are not run some times as expected. I never questioned myself about how wp_cron actually works, I thought it was kinda self-explanatory. But now I doubt it. Codex says that timestamp argument is: the first time that you want the event to occur. This must be in a UNIX timestamp format. I know that wp_cron triggers events when someone visits the site. But what if the visit happens little bit after the time hardcoded in timestamp? Will that event still trigger? Or pass?
Yes, the event will trigger when the wp-cron process gets run. If something is preventing wp-cron from running, then it won't trigger at all. If you're having it not work, then something about your server configuration is preventing it from working. For these cases, you can generally work around them by adding this define to your wp-config file: <code> define('ALTERNATE_WP_CRON', true); </code>
wp_schedule_event will it run if timestamp has passed?
wordpress
I have my own custom post type under: wordpress/custom But when I open any item of this post type they open in: wordpress/archives/custom/title Why there's 'archives' and how to get rid of this from my urls? The taxonomy is registered like below: <code> register_taxonomy("our_frontpage_types", array("frontpage"), array("hierarchical" =&gt; true, "label" =&gt; "Categories", "singular_label" =&gt; "Category", "rewrite" =&gt; true)); </code> And the post is registered like: <code> add_action('init', 'fp_register'); </code> UPDATE * Ok, now I know it was a problem with permalinks, BUT /%category%/%postname% is far from perfection. Is there something like %section%/%postname%?
WordPress will add archives base in the url if it thinks that the page an archive and when i had the problem it was because i named the custom post type and my custom taxonomy the same, is that the case?
Custom post type items open in archives?
wordpress
Currently, in my plugin description, I'm hardcoding... To customize options &lt;a href="options-general.php?page=my-plugin-admin.php"> click here&lt;/a> Is there a dynamic method to call the plugin options page?
You're looking for a plugin settings link that's dynamically generated. This would be one approach. http://wpengineer.com/1295/meta-links-for-wordpress-plugins/
Can I dynamically create a link to my plugin settings/options page from my plugin description?
wordpress
Frustration! Is there an easy to change the RSS title link using the RSS widget to link to the feed instead of the blog itself? It can't be this hard.. I could easily hard code this but I want to keep it as modular as possible.
I don't see any easy way in source. That link is retrieved from feed by SimplePie method and is not passing through any deliberate filters. And it gets concatenated with rest of title after that is passed through filter, not before. The only idea I have is to filter it in <code> esc_url() </code> function at <code> clean_url </code> hook, but that will only work nicely if link is unique and won't break elsewhere... Or will take some messy hook juggling to target it precisely.
Changing RSS title link to link to feed instead of blog
wordpress
I have a custom page type set up called 'Products' and I need each of these post to automatically have multiple custom fields to set up a table of features/prices for the individual product pages. Is there any way this can be done? Thanks.
Hi @ Jared I too had a question about this. Luckily, stackexchange-url ("Chris_O") answered it for me. You may also want to check out stackexchange-url ("this question"), too. Here's an example of what I've done with meta boxes and you can see it's quite easy.
Add custom field automatically to custom page types
wordpress
How to add default values for theme options? Currently I use basic option from this site The sample will stored option value in serialize on database. When we activate the theme, there is no value in database at first time until we click Save Changes button. Now I want add default value when theme activate something like this. <code> option_id blog_id option_name option_value autoload 152 0 theme_data a:16:{s:12:"html_doctype";s:1:"1";s:14:"header_fav... yes </code> Or how do I tweak current sample option to save not in serialize to database <code> option_id blog_id option_name option_value autoload 152 0 html_doctype 1 yes </code> Let me know.
Loop over your array of options and generate a set of defaults from that.. Let's imagine your array looks something like this.. (but obviously bigger).. <code> $your_options = array( array( 'name' =&gt; 'option-one', 'desc' =&gt; 'Option one description', 'type' =&gt; 'text', 'std' =&gt; 'default_value' ), ..and so on.. for each option.. ); </code> First check if you have options, if not, it's the first install so you can set defaults. <code> $my_var_that_holds_options = get_option( 'your_theme_options_name' ); if( !$my_var_that_holds_options ) { // Do code to setup defaults } </code> The code to setup defaults will of course go where i've put <code> // Do code to setup defaults </code> . First, create an array to hold the defaults and loop over the options array to build the new defaults array. <code> $defaults = array(); foreach( $your_options_var as $option_data ) { $defaults[$option_data['name']] = $option_data['std']; } </code> By the end you'll have an array of option names and default values, which you can then send to the database. <code> update_option( 'your_theme_options_name', $defaults ); </code> If you code needs to loop over the options to set boxes checked, etc.. simply call get_option again after you've saved the defaults.. <code> $my_var_that_holds_options = get_option( 'your_theme_options_name' ); </code> Or use the defaults array. <code> $my_var_that_holds_options = $defaults; </code> I've had to be quite general with the example, because the approach will differ depending on how your options array is structured. The important factor here is to ensure your array of options holds a "default" value(std in the example) for each option else you've got nothing to form your default values from. I've converted themes to do this a handful of times, if you have trouble implementing this feel free to pastebin your file with the options array and i'll take a look.
Wordpress theme options and insert default value for serialize data
wordpress
I am not sure how WordPress cache the queries. I had the impression that whenever I execute a query through wpdb class, it gets cached. For example, on codex under Select a Row and Select a Var, it says the whole query is cached for later use. And I think which means if more data is requested in another query, partials or full results of which are already in wpdb cache, then those are used and a query doesn't happen(in case of full results already in cache). Am I correct in understanding? I was trying something and I found that I can't use the cache. For reference, I was listing the recent comments the current user has made. I used <code> get_comments() </code> but since it only has post id in the results, I used <code> get_the_title() </code> inside the loop for displaying them. Obviously this is expensive in terms of query, so I though I can cache the required rows of post table by querying them beforehand so that <code> get_the_title() </code> does no actual query. I did something like <code> $query = implode( ' OR ID = ', $collect_post_ids ); $query = 'SELECT * FROM '.$wpdb-&gt;prefix.'posts WHERE ID = '.$query.';'; $wpdb-&gt;get_results( $query ); // just cache it </code> but that didn't help. <code> get_the_title() </code> is still doing queries. Most likely its me who has misunderstood how WP Cache works. So where I am wrong? Here is the full code for reference - http://ashfame.pastebin.com/BpxjHiQr
Nope, doesn't work like that. The database-related caching is minimal and mostly covers using precisely same queries during single page load. Best way to cache persistently database and/or computationally intensive results is using Transients API to store results for fitting period of time.
Does a query executed through wpdb class get cached?
wordpress
I've just installed wordpress on our Rackspace server - I've set wordpress up for Multisite as I have done many times before. The main wordpress site at the root functions fine - however when I add a new site and click on either 'backend' or 'visit' I get 'page not found'. Pages in the main site seem to work fine with the default permalink settings but not custom such as /%category%/%postname%/ I think this must be a server issue but am a bit stumped. Any suggestions appreciated!
Yeah the server is not reading the htaccess file properly. may need AllowOverride FileInfo Options in the httpd.conf file for that vhost.
Wordpress 3.0 Multisite - Child sites and backends appearing blank
wordpress
I have my own custom post type, and 15 items there. This code shows all the items: <code> &lt;?php $loop = new WP_Query( array( 'post_type' =&gt; 'my_post_type', 'posts_per_page' =&gt; 15 ) ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; (...) </code> When I change posts_per_page to "5" there should be 3 pages, but it displays only 5 items and there are no other pages (or at least I don't know how to access them). This code displays nothing: <code> &lt;?php if ( $wp_query-&gt;max_num_pages &gt; 1 ) : ?&gt; {menu or any html code} &lt;?php endif; ?&gt; </code> Maybe I do something wrong? I have the whole code/loop in page-myposttype.php file. I've tried this code: <code> $temp = $wp_query; $loop= null; $paged = get_query_var('paged') ? get_query_var('paged') : 1; $loop = new WP_Query( array( 'post_type' =&gt; 'my_post_type', 'paged' =&gt; $paged, 'posts_per_page' =&gt; 2 ) ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; </code> But no luck... When I type wordpress/my_post_type/page/2 (page/3 etc.) manually I see other pages and they work &amp; look fine. But I'm unable to echo the default navi... :(
Answered a question that's virtually identical to this very recently on the WordPress.org forums. Custom Post Type Archive Page - Pagination Isn't Working I've provided a work-around / fix in that thread that should also work for you to. :) EDIT: You also need to add the paging parameter to your query.. Eg. <code> $args = array( 'post_type' =&gt; 'my_post_type', 'paged' =&gt; get_query_var('paged') ? get_query_var('paged') : 1, 'posts_per_page' =&gt; 15, ); $loop = new WP_Query; $loop-&gt;query( $args ); </code> I reformatted the code to make it a little more readable, end result will be the same.
Paging doesn't work?
wordpress
This is a repost of a question asked on stackoverflow, and was referred to this site: My client wants to create a form on his new WP site that when filled out and submitted will be submitted to his admin post queue to approve and if he approves gets posted on his site in the "blog" (which is actually a bunch of guitar like tabs). The form would be custom and have custom fields. Below is the form, but in the old design before I did a refresh on it. So, how hard would this be? He does not want it in the WP admin panel which i began to do, but outside in a page like /contribute
you can use plugins fro the front-end posting: Post From Site uCan Post WP User Frontend Or you can create the form yourself <code> &lt;!-- New Post Form --&gt; &lt;div id="postbox"&gt; &lt;form id="new_post" name="new_post" method="post" action=""&gt; &lt;p&gt;&lt;label for="title"&gt;Title&lt;/label&gt;&lt;br /&gt; &lt;input type="text" id="title" value="" tabindex="1" size="20" name="title" /&gt; &lt;/p&gt; &lt;p&gt;&lt;label for="description"&gt;Description&lt;/label&gt;&lt;br /&gt; &lt;textarea id="description" tabindex="3" name="description" cols="50" rows="6"&gt;&lt;/textarea&gt; &lt;/p&gt; &lt;p&gt;&lt;?php wp_dropdown_categories( 'show_option_none=Category&amp;tab_index=4&amp;taxonomy=category' ); ?&gt;&lt;/p&gt; &lt;p&gt;&lt;label for="post_tags"&gt;Tags&lt;/label&gt; &lt;input type="text" value="" tabindex="5" size="16" name="post_tags" id="post_tags" /&gt;&lt;/p&gt; &lt;p align="right"&gt;&lt;input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /&gt;&lt;/p&gt; &lt;input type="hidden" name="action" value="new_post" /&gt; &lt;?php wp_nonce_field( 'new-post' ); ?&gt; &lt;/form&gt; &lt;/div&gt; &lt;!--// New Post Form --&gt; </code> and process it <code> if( 'POST' == $_SERVER['REQUEST_METHOD'] &amp;&amp; !empty( $_POST['action'] ) &amp;&amp; ($_POST['action']== 'new_post')) { if (isset ($_POST['title'])) { $title = $_POST['title']; } else { echo 'Please enter a title'; } if (isset ($_POST['description'])) { $description = $_POST['description']; } else { echo 'Please enter the content'; } $tags = $_POST['post_tags']; $new_post = array( 'post_title' =&gt; $title, 'post_content' =&gt; $description, 'post_category' =&gt; $_POST['cat'], 'tags_input' =&gt; $tags, 'post_status' =&gt; 'draft' ); wp_insert_post($new_post); } </code> And make sure to check for nonce and sanitization of the form fields. UPDATE According to your gist code and comment change your function to this: <code> if( 'POST' == $_SERVER['REQUEST_METHOD'] &amp;&amp; !empty( $_POST['action'] ) &amp;&amp; ($_POST['action']== 'new_post')) { $has_errors = false; if (isset ($_POST['title'])) { $title = $_POST['title']; } else { echo 'Please enter a title'; $has_errors = true; } if (isset ($_POST['performer'])) { $performer = $_POST['preformer']; } else { echo 'Please enter a performer'; $has_errors = true; } if (isset ($_POST['composer'])) { $composer = $_POST['composer']; } else { echo 'Please enter a composer'; $has_errors = true; } if (isset ($_POST['tablature'])) { $tablature = $_POST['tablature']; } else { echo 'Please enter the content'; $has_errors = true; } $tags = $_POST['post_tags']; if (!$has_errors){ //save &lt;title&gt; by: &lt;preformer&gt; $title .= " by: " .$performer; //save Composed by: &lt;composer&gt; Performed by: &lt;performer&gt; &lt;tablature&gt; $content = "&lt;h4&gt;Composed by: ". $composer."&lt;/h4&gt;&lt;br/&gt;&lt;h4&gt;Performed by: ".$performer."&lt;/h4&gt;&lt;br/&gt;".$tablature; $new_post = array( 'post_title' =&gt; $title, 'post_content' =&gt; $content, 'post_category' =&gt; $_POST['cat'], 'tags_input' =&gt; $tags, 'post_status' =&gt; 'draft' ); $pid = wp_insert_post($new_post); //save email and submmiter as post meta in custom fields update_post_meta($pid, 'submiter_email', urldecode($_POST['email'])); update_post_meta($pid, 'submiter_name', urldecode($_POST['submitter'])); } } </code>
Anonymous Postings
wordpress
I have a number of slugs and items in my custom category: SLUG - number video - 5 items music - 5 items [no-slug] - 5 items empty - 0 items blabla - 0 items I want to list all non-empty slugs (otpionally with number of items next to them), like: [ video (5) ] [ music (5) ] [ other (5) ] (empty and blabla omitted) Anyone knows how to do that? All I know is how to get a slug for particular item: <code> &lt;?php $slug = $terms[0]-&gt;slug; ?&gt; </code> UPDATE My taxonomy registration: functions.php <code> register_taxonomy("op", array("portfolio"), array( "hierarchical" =&gt; true, "label" =&gt; "Categories", "singular_label" =&gt; "Category", "rewrite" =&gt; true, )); </code> page-portfolio.php <code> $taxonomy = "op"; function get_taxonomy_list_html($taxonomy) { $term_links = array(); foreach(get_terms('Category') as $term) { if (!empty($term-&gt;slug) &amp;&amp; $term-&gt;count&gt;0) { $link = get_term_link($term,$taxonomy); $term_links[] = "[ &lt;a href='{$link}'&gt;{$term-&gt;name}&lt;/a&gt; ({$term-&gt;count}) ]"; } } return implode(' ',$term_links); } </code> Displays nothing :(
Hi @Wordpressor: Sounds pretty simple so I'm concerned I misunderstand, but in case I did understand correctly here's a function; just pass the taxonomy to it like this: <code> echo get_taxonomy_list_html('category') </code> : <code> function get_taxonomy_list_html($taxonomy) { $term_links = array(); foreach(get_terms($taxonomy) as $term) { if (!empty($term-&gt;slug) &amp;&amp; $term-&gt;count&gt;0) { $link = get_term_link($term,$taxonomy); $term_links[] = "[ &lt;a href='{$link}'&gt;{$term-&gt;name}&lt;/a&gt; ({$term-&gt;count}) ]"; } } return implode(' ',$term_links); } </code>
Listing all slugs?
wordpress
Can someone tell me how to get the time zone that is set in the WordPress Admin? For example, if the blog is set to Eastern time, I need this exact string to print out: US/Eastern This is for a function that lives in functions.php in my theme.
if you need the gmt_offset then <code> &lt;?php echo get_option('gmt_offset'); ?&gt; </code> this will give you an integer like 2 or -2 . and if you need the timezone string use <code> &lt;?php echo get_option('timezone_string'); ?&gt; </code> this will give you a string like America/Indianapolis
How to get WordPress Time Zone setting?
wordpress
here is what i have so far. function zip_gallery() { global $post; $images = get_children(array('post_parent' => get_the_ID(), 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_mime_type' => 'image', )); if ($images) { $save = $post-> post_title; $zip = new ZipArchive; if ($zip-> open($save . '.zip', ZIPARCHIVE::CREATE) === true) { foreach ($images as $image) { $file = wp_get_attachment_url($image-> ID, 'full', false, false); $filename = pathinfo($file); $zip-> addFile($file, $filename); } $zip-> close(); } } } can someone shed some light on what im doing wrong.
<code> ZipArchive-&gt;addFile() </code> method expects local path to file, while <code> wp_get_attachment_url() </code> returns URL. You need to build local path for file from URL or in other way.
get images from post and make a zip
wordpress
I am working on a client site which is a very stripped down theme. It has no standard html markups as a result of which the reply box doesn't move upto the place of being just below the comment to which you hit the reply button. Can anyone point me to the minimum markup required? I am trying to add classes one by one. Trying to explain it better: I click on the reply button, the page reloads and the comment form stays below all the comments list. I want it to make it work like when we click on reply button, then without any page reload, it jumps up there and can be cancelled back to the place. The default what we have in Twentyten Update: I managed to fix up the markup and now I am using comment_form() but cancel reply button doesn't appear and I am not filtering that out. Any ideas? Done So sorry to trouble everyone here. The last issue was fixed by removing the CSS <code> display:none; </code> ( Lesson - DIY Themes sucks unless its what you do! ;) )
You should really use comment_form() instead of rolling your own. Still, if you must, make sure that: The textarea has id="comment". The wrapping container around the entire comment form (probably a DIV) has id="respond".
Comment Reply javascript
wordpress
I'm using a custom post type and custom taxonomies, and using the following to display the terms of the taxonomies on the post page: <code> the_terms( $post-&gt;ID, 'taxname', 'beforetext', ', '); </code> Is there a way to loop through all the taxonomies assigned to this post and display the terms in an unordered list, rather than a separate line in functions.php for each taxonomy? I suspect that this can be done with a foreach loop, but I don't know the right syntax.
This answer was a joint effort with tnorthcutt so I made it community wiki . There are several interesting functions available: <code> the_taxonomies() </code> , which calls <code> get_the_taxonomies() </code> , which in turn calls <code> get_object_taxonomies() </code> and <code> wp_get_object_terms() </code> . <code> the_taxonomies() </code> is a documented template tag and is a light wrapper around a call to <code> get_the_taxonomies() </code> , which is undocumented. <code> get_object_taxonomies() </code> returns a list of associated taxonomies (as simple names or as objects), which could be quite useful in certain situations. It's documented, but it's easy to miss this function because nothing links to it in the Codex. I only found it by perusing <code> wp-includes/taxonomy.php </code> . There is an undocumented wrapper function around this, <code> get_post_taxonomies() </code> , which defaults to the current post. <code> wp_get_object_terms() </code> does most of the heavy lifting. It has two very interesting parameters: an array(!) of object ids and an array(!) of taxonomy names. It ends up generating a moderately evil-looking SELECT and returns an array of terms (as names, objects, or ... read the docs) for the given object(s) within the given taxonomy(ies). Should you need more complex formatting than is available via <code> the_taxonomies() </code> , knowing about these "inner" functions should prove useful.
Using a loop to display terms associated with a post
wordpress
I just configured my VPS, I am using Centos, everything works fine, but if I am setting my permalinks to Custom Structure, then accept the homepage none of the posts come, it shows me 404 page, I think this is because I haven't enabled curl, but I don't know where is my php.ini file in my centos? OK my curl is enabled, I checked it through <code> phpinfo(); </code> Here is the URL <code> http://74.117.158.182/info.php </code> But if I am setting any permalinks in my wordpress then accept home page, all are giving me 404 pages You can check it on this URL http://mbas.co.in If I am keeping the permalink as default then pages are loaded without any 404 I don't know what is the problem, more-over my post-content is not getting loaded, Only the posts title comes, but the content part is missing, MY APACHE ERROR LOG [Tue Feb 01 15:22:47 2011] [notice] suEXEC mechanism enabled (wrapper: /usr/sbin/suexec) [Tue Feb 01 15:22:47 2011] [notice] Digest: generating secret for digest authentication ... [Tue Feb 01 15:22:47 2011] [notice] Digest: done [Tue Feb 01 15:22:47 2011] [notice] Apache/2.2.3 (CentOS) configured -- resuming normal operations [Tue Feb 01 15:22:51 2011] [error] [client 95.168.183.226] File does not exist: /var/www/html/web-hosting-concerns-for-ecommerce-businesses, referer: mysite.com [Tue Feb 01 15:23:30 2011] [error] [client 38.101.148.126] File does not exist: /var/www/html/cpcu-vs-mba [Tue Feb 01 15:23:35 2011] [error] [client 66.77.240.125] File does not exist: /var/www/html/can-u-see-below-for-growing-opinions-on-write-in-vote-process-in-sa [Tue Feb 01 15:23:43 2011] [error] [client 38.101.148.126] File does not exist: /var/www/html/dc-area-financial-strategist-questions-lack-of-regulation-for-tv-financial-gurus [Tue Feb 01 15:24:15 2011] [error] [client 38.101.148.126] File does not exist: /var/www/html/is-a-political-science-degree-with-a-business-admin-minor-a-good-idea-feature-jobs-with-that-combo [Tue Feb 01 15:26:01 2011] [error] [client 66.249.71.225] File does not exist: /var/www/html/emba-ralph-irizarry-timbalista-de-ruben-blades My htaccess file <code> # BEGIN W3TC Page Cache &lt;IfModule mod_rewrite.c&gt; RewriteEngine On RewriteBase / RewriteCond %{HTTP_USER_AGENT} (2\.0\ mmp|240x320|alcatel|amoi|asus|au\-mic|audiovox|avantgo|benq|bird|blackberry|blazer|cdm|cellphone|danger|ddipocket|docomo|dopod|elaine/3\.0|ericsson|eudoraweb|fly|haier|hiptop|hp\.ipaq|htc|huawei|i\-mobile|iemobile|j\-phone|kddi|konka|kwc|kyocera/wx310k|lenovo|lg|lg/u990|lge\ vx|midp|midp\-2\.0|mmef20|mmp|mobilephone|mot\-v|motorola|netfront|newgen|newt|nintendo\ ds|nintendo\ wii|nitro|nokia|novarra|o2|openweb|opera\ mobi|opera\.mobi|palm|panasonic|pantech|pdxgw|pg|philips|phone|playstation\ portable|portalmmm|ppc|proxinet|psp|pt|qtek|sagem|samsung|sanyo|sch|sec|sendo|sgh|sharp|sharp\-tq\-gx10|small|smartphone|softbank|sonyericsson|sph|symbian|symbian\ os|symbianos|toshiba|treo|ts21i\-10|up\.browser|up\.link|uts|vertu|vodafone|wap|willcome|windows\ ce|windows\.ce|winwap|xda|zte) [NC] RewriteRule .* - [E=W3TC_UA:_low] RewriteCond %{HTTP_USER_AGENT} (acer\ s100|android|archos5|blackberry9500|blackberry9530|blackberry9550|cupcake|docomo\ ht\-03a|dream|htc\ hero|htc\ magic|htc_dream|htc_magic|incognito|ipad|iphone|ipod|lg\-gw620|liquid\ build|maemo|mot\-mb200|mot\-mb300|nexus\ one|opera\ mini|samsung\-s8000|series60.*webkit|series60/5\.0|sonyericssone10|sonyericssonu20|sonyericssonx10|t\-mobile\ mytouch\ 3g|t\-mobile\ opal|tattoo|webmate|webos) [NC] RewriteRule .* - [E=W3TC_UA:_high] RewriteCond %{HTTPS} =on RewriteRule .* - [E=W3TC_SSL:_ssl] RewriteCond %{SERVER_PORT} =443 RewriteRule .* - [E=W3TC_SSL:_ssl] RewriteCond %{HTTP:Accept-Encoding} gzip RewriteRule .* - [E=W3TC_ENC:.gzip] RewriteCond %{REQUEST_METHOD} !=POST RewriteCond %{QUERY_STRING} ="" RewriteCond %{REQUEST_URI} \/$ RewriteCond %{REQUEST_URI} !(\/wp-admin\/|\/xmlrpc.php|\/wp-(app|cron|login|register|mail)\.php|wp-.*\.php|index\.php) [NC,OR] RewriteCond %{REQUEST_URI} (wp\-comments\-popup\.php|wp\-links\-opml\.php|wp\-locations\.php) [NC] RewriteCond %{HTTP_COOKIE} !(comment_author|wp\-postpass|wordpress_\[a\-f0\-9\]\+|wordpress_logged_in) [NC] RewriteCond "/var/www/html/wp-content/w3tc/pgcache/$1/_index%{ENV:W3TC_UA}%{ENV:W3TC_SSL}.html%{ENV:W3TC_ENC}" -f RewriteRule (.*) "/wp-content/w3tc/pgcache/$1/_index%{ENV:W3TC_UA}%{ENV:W3TC_SSL}.html%{ENV:W3TC_ENC}" [L] &lt;/IfModule&gt; # END W3TC Page Cache # 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] RewriteRule ^index\.php/?(.*)$ $1 [R] &lt;/IfModule&gt; # END WordPress </code> The only solution I found was reinstalling the entire Centos, starting all from scratch, and enabling each thing respectively as per the answers, and finally it worked, my Linux was having some problems, thats why it was not working.
You need to add: Options +FollowSymLinks It's often but not always enabled in most hosting environments. We have a server that has it off by default for PCI compliance.
curl problem or permalinks
wordpress
The title pretty much explains exactly what I'm trying to do. If someone could help me out, that would be awesome. Thanks! :)
the correct way to include files for scripts you can use the hook "admin_print_scripts" and include your scripts with wp_enqueue_script() for example: <code> &lt;?php add_action('admin_print_scripts','my_scripts'); function my_scripts(){ wp_enqueue_script( 'jquery' ); } ?&gt; </code> and for styles use the hook "admin_print_styles" and include you styles with wp_enqueue_style for example: <code> &lt;?php add_action('admin_print_styles','my_styles'); function my_styles(){ wp_enqueue_style( 'myPluginStylesheet', WP_PLUGIN_URL . '/myPlugin/stylesheet.css' ); } ?&gt; </code> Hope This Helps.
Include jQuery (or anything) inside Custom Options Panel's tag
wordpress
Recently I purchased a VPS from intovps.com, And first time I configured a fully unmanaged VPS through ssh comands. My website is working into it, properly. Now I just want to know how to secure it? I started my process of configuring VPS in this way:- Installed LAMP, phpmyadmin, restored the backup(wordpress &amp; mysql), installed vsftpd for ftp access, added a user into FTP(user can navigate into any directory over the entire VPS, but change anything) Now after everything, I just want to know the security steps for my VPS. I have heard from my friends that after configuring a VPS, it also needs to be configure for security. In VPS, I have only one user added for ssh access, which is default,and I just added one ftp user. Now I want that the ftp added user should just navigate to the <code> /html </code> directory, where my website is installed, and has all writes to change everything And any suggestions or tricks or steps for making server more secure?
Have a look at this excellent question and answers on Server Fault that discusses how to secure your LAMP stack. Make sure your FTP user can only access the directories you want. Setup sudo to allow a non root user to run commands as root. Lock down your ssh so that root cannot log in set <code> PermitRootLogin = no in /etc/ssh/sshd_config </code> Enable passwordless public key login for ssh. Disable ssh password login
Secure Server after configuration
wordpress
I've been adding custom post types in the admin panel and endingup with the following results: 1. Prioritazing content: Posts (blog entries, news, events...) Pages Static Content (custom post type) -> Sections (custom taxonomy) (Tagline, Slider, Mainbar...) ... In this case, I divided the pages into sections, the problem is that the client can only know where the section is by creating a term like this: Tagline (Front-Page). 2. Prioritizing pages: Pages Front-Page (custom post type) -> Sections (custom post type) (Tagline, Slider, Mainbar...) News (custom post type) ... Events (custom post type) ... Photos (custom post type) ... About (custom post type) ... Blog (custom post type) ... Contact (custom post type) ... In this case, the client will know to which page the content will go. But if the user will see some pages he or she may never use. Which method is more efficient concerning content managment? Do you have another better alternative? * Reference Picture of case #1 (the custom post type is called Static Content and the custom taxonomy is called Sections. Posts will be preserved but used in Categories called Events, News, etc...): .
Hi @janoChen: Definitely #1. #2 will create a lot of complexity for the user. To address the problems you've identified with #1 I would recommend removing the static content post types from the admin and isntead creating a custom admin page that allows the user to add static sections via AJAX with links to their edit pages.
Using custom post types to give Wordpress a more CMS-like look. What to prioritaize? Pages or Content?
wordpress
I want to display one post from each category per page. So the first page would contain the first post of cat A, the first post of cat B and the first post of cat C. The second page would contain the second post of cat A, the second post of cat B and the second post of cat C. I currently use the following code, but it does not work, I always get the same posts. <code> $category_ids = get_all_category_ids(); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; foreach($category_ids as $kk=&gt; $cat_id) { $cat_name= query_posts( 'cat='.$cat_id.'&amp;posts_per_page=1&amp;orderby=date&amp;order=ASC&amp;paged='.$paged); foreach($cat_name as $post) : setup_postdata($post); if (have_posts ()) : while (have_posts ()) : the_post(); ?&gt; &lt;?php } else { ?&gt; &lt;?php if( get_the_category_list() ) { ?&gt;&lt;p class="alignleft"&gt;&lt;span&gt;&lt;?php the_category( ', ' ) ?&gt;&lt;/span&gt;&lt;/p&gt;&lt;?php } ?&gt; endwhile; endif; </code>
If you are only showing one post of each category then in your <code> query_posts() </code> change the <code> &amp;paged='.$paged </code> to <code> &amp;offset='.$paged </code>
Showing one post from each category, paged?
wordpress