question
stringlengths
0
34.8k
answer
stringlengths
0
28.3k
title
stringlengths
7
150
forum_tag
stringclasses
12 values
For some reason, I'm having difficulty converting a date value stored in a meta field to a unix timestamp (and back again). If I save the date as a string it all works fine, but if I convert it to a timestamp using <code> strtotime </code> it won't save the value. My working code looks like this: <code> &lt;?php add_action( 'add_meta_boxes', 'rs_add_date' ); function rs_add_date() { add_meta_box( 'rs_add_date', 'Date', 'rs_add_date_create_meta_box', 'concerts', 'normal', 'high' ); } function rs_add_date_create_meta_box( $post ) { $date = get_post_meta($post-&gt;ID, 'rs_date', true); echo 'Choose a date for the event'; wp_nonce_field( plugin_basename(__FILE__), 'rs_date_nonce'); ?&gt; &lt;p&gt;Date (dd/mm/yyyy) &lt;input type="text" name="rs-date" id="rs-date" value="&lt;?php echo $date; ?&gt;"&gt;&lt;/p&gt; &lt;?php } // Save the new meta add_action('save_post', 'rs_date_save_meta'); function rs_date_save_meta( $post_id ) { if(!wp_verify_nonce( $_POST['rs_date_nonce'], plugin_basename(__FILE__) ) ) return; if(!current_user_can('edit_posts') ) return; $date = $_POST['rs-date']; update_post_meta($post_id, 'rs_date', $date); } ?&gt; </code> But if I change it to the following it won't work: <code> &lt;?php add_action( 'add_meta_boxes', 'rs_add_date' ); function rs_add_date() { add_meta_box( 'rs_add_date', 'Date', 'rs_add_date_create_meta_box', 'concerts', 'normal', 'high' ); } function rs_add_date_create_meta_box( $post ) { $date = get_post_meta($post-&gt;ID, 'rs_date', true); $date = time("d/m/Y", $date); echo 'Choose a date for the event'; wp_nonce_field( plugin_basename(__FILE__), 'rs_date_nonce'); ?&gt; &lt;p&gt;Date (dd/mm/yyyy) &lt;input type="text" name="rs-date" id="rs-date" value="&lt;?php echo $date; ?&gt;"&gt;&lt;/p&gt; &lt;?php } // Save the new meta add_action('save_post', 'rs_date_save_meta'); function rs_date_save_meta( $post_id ) { if(!wp_verify_nonce( $_POST['rs_date_nonce'], plugin_basename(__FILE__) ) ) return; if(!current_user_can('edit_posts') ) return; $date = $_POST['rs-date']; $date = strtotime($date); update_post_meta($post_id, 'rs_date', $date); } ?&gt; </code> Scratching my head here! Cheers
Looking at http://www.php.net/manual/en/datetime.formats.date.php I dont think strtotime will convert a DD/MM/YYYY to time correctly. However it can do MM/DD/YYYY or YYYY/MM/DD. Try using the date format of YYYY/MM/DD Or if thats not to your liking then you can use the same date format but you will have to, on save, split up the date and convert it to unix datestamp a diff way. You could use: <code> $date = "dd/mm/yyyy"; $date = explode("/", $date); $date = mktime(0, 0, 0, (int)$date[1], (int)$date[0], (int)$date[2]); </code>
custom field value date convert to unix timestamp problems
wordpress
I am using <code> get_posts </code> and <code> get_comments </code> to build several loops on the page, at which I am having some issues in pagination. I have the global posts per page option (Settings > Reading) set to 10 , and this seems to vary the problem. As of now, I can easily get to Page 2 - http://dev.ashfame.com/author/ashfame/page/2/ , but Page 3 returns a 404 . If I lower the global value, I get to have more paginated pages but not all (lesser number than how many there should be). Update: I just tried setting my custom setting as 2 (and the global one too), and WordPress should paginate until page 4 (I have 7 items to show) but now it does but also page 5 &amp; 6. 7 gives 404 . Why? How do I troubleshoot this thing now? Progress: @t31os helped me figure out that its the WP default query on the page which is setting up the pagination for that page. Now I can think of one way to kill the default WP query on that page (but how?) and then how would I further paginate the author.php page? Or is there any other way of doing it? Current code: <code> &lt;?php $author_details = $wp_query-&gt;get_queried_object(); // Posts Per Page option // $ppp = get_option('posts_per_page'); $ppp = 1; //custom setting, if you want to obey the global setting here, comment this line and uncomment the above line if (!is_paged()) { $custom_offset = 0; } else { $custom_offset = $ppp*($paged-1); } echo '&lt;h1&gt;Author ID : '.$author_details-&gt;ID.', Page : '.$paged.', Custom Offset : '.$custom_offset.'&lt;/h1&gt;'; ?&gt; &lt;h2&gt;Articles&lt;/h2&gt; &lt;?php $args = array( 'numberposts' =&gt; $ppp, 'offset' =&gt; $custom_offset, 'category' =&gt; 7, 'author' =&gt; $author_details-&gt;ID ); $posts_data = get_posts( $args ); // print_r($posts_data); if ( count( $posts_data ) &gt; 0 ) { echo '&lt;ul&gt;'; foreach ( $posts_data as $post ) { echo '&lt;li&gt;&lt;a href="'.get_permalink( $post-&gt;ID ).'"&gt;'.$post-&gt;post_title.'&lt;/a&gt;&lt;/li&gt;'; } echo '&lt;/ul&gt;'; } else { echo '&lt;p&gt;No articles by this user&lt;/p&gt;'; } ?&gt; &lt;h2&gt;Journals&lt;/h2&gt; &lt;?php $args = array( 'numberposts' =&gt; $ppp, 'offset' =&gt; $custom_offset, 'category' =&gt; 6, 'author' =&gt; $author_details-&gt;ID ); $posts_data = get_posts( $args ); // print_r($posts_data); if ( count( $posts_data ) &gt; 0 ) { echo '&lt;ul&gt;'; foreach ( $posts_data as $post ) { echo '&lt;li&gt;&lt;a href="'.get_permalink( $post-&gt;ID ).'"&gt;'.$post-&gt;post_title.'&lt;/a&gt;&lt;/li&gt;'; } echo '&lt;/ul&gt;'; } else { echo '&lt;p&gt;No journals by this user&lt;/p&gt;'; } ?&gt; &lt;h2&gt;Questions&lt;/h2&gt; &lt;?php $args = array( 'numberposts' =&gt; $ppp, 'offset' =&gt; $custom_offset, 'category' =&gt; 3, // parent category ID is enough 'author' =&gt; $author_details-&gt;ID ); $posts_data = get_posts( $args ); // print_r($posts_data); if ( count( $posts_data ) &gt; 0 ) { echo '&lt;ul&gt;'; foreach ( $posts_data as $post ) { $category_array = get_the_category( $post-&gt;ID ); $category_name = $category_array[0]-&gt;name; $category_permalink = get_category_link( $category_array[0]-&gt;term_id ); echo '&lt;li&gt;&lt;a href="'.get_permalink( $post-&gt;ID ).'"&gt;'.$post-&gt;post_title.'&lt;/a&gt; &lt;br /&gt;In: &lt;a href="'.$category_permalink.'"&gt;'.$category_name.'&lt;/a&gt;&lt;br /&gt;'.get_comments_number( $post-&gt;ID ).' Answers&lt;/li&gt;'; } echo '&lt;/ul&gt;'; } else { echo '&lt;p&gt;No questions by this user&lt;/p&gt;'; } ?&gt; &lt;h2&gt;Answers&lt;/h2&gt; &lt;?php $args = array( 'user_id' =&gt; $author_details-&gt;ID, 'number' =&gt; $ppp, 'offset' =&gt; $custom_offset, 'status' =&gt; 'approve' ); $answers_list = get_comments( $args ); // print_r($answers_list); if ( count( $answers_list ) &gt; 0 ) { $date_format = get_option( 'date_format' ); echo '&lt;ul&gt;'; foreach ( $answers_list as $answer ) { echo '&lt;li&gt;Answer: '.substr( $answer-&gt;comment_content, 0, 20 ).'..&lt;br /&gt;'.date( $date_format, strtotime( $answer-&gt;comment_date ) ).'&lt;br /&gt;Question: &lt;a href="'.get_permalink( $answer-&gt;comment_post_ID ).'"&gt;'.get_the_title( $answer-&gt;comment_post_ID ).'&lt;/a&gt;&lt;/li&gt;'; } echo '&lt;/ul&gt;'; } else { echo '&lt;p&gt;No answers by this user&lt;/p&gt;'; } ?&gt; </code>
t31os says: [See edit history for previous code and comments] Using Ajax to paginate your queries I've put together some code that will fetch your posts and comments via ajax using simple prev/next navigation via ajax. 1) Replace all the code you posted in your author.php with the following.. <code> &lt;?php $cat_settings = array( 'Articles' =&gt; 7, 'Journals' =&gt; 6, 'Questions' =&gt; 3 ); ?&gt; &lt;?php do_action( 'author_ajax_catposts', $cat_settings ); ?&gt; </code> 2) Create a Javascript file in your theme's directory called <code> authorposts.js </code> and place the following code into that file. <code> jQuery(document).ready( function($) { if( 'undefined' == typeof( aacVars ) ) return; $('.aacnav').click(function() { var r = $( $(this).attr('href') ); var a = $( $(this).attr('href') + '-ap' ); var c = this.className.split(' '); if( 'undefined' == typeof( c ) || 'undefined' == typeof( r ) || 'undefined' == typeof( a ) ) return false; var d = { action: aacVars.posts_action, _ajax_nonce: aacVars.nonce, author: aacVars.author, category: $(this).attr('href') }; p = parseInt( a.text() ); c = c.pop(); switch( c ) { case 'aacnext': if( r.children('p.nomore').length ) return false; d.page = p + 1; break; case 'aacprev': if( p &lt; 2 ) return false; d.page = p - 1; break; default: return false; } $.post( aacVars.ajaxpth, d, function( res ) { if( '-1' == res ) { alert( 'auth failed' ); return false; } $( r ).html( res ); $( a ).text( d.page ); }); return false; }); $('.aacnavc').click(function() { var r = $( '#aac-comments' ); var n = $( '#aac-comments-ap' ); var l = $(this).attr('href'); if( 'undefined' == typeof( n ) || 'undefined' == typeof( r ) ) return false; var d = { action: aacVars.comments_action, _ajax_nonce: aacVars.nonce, author: aacVars.author }; p = parseInt( n.text() ); switch( l ) { case '#next': if( r.children('p.nomore').length ) return false; d.page = p + 1; break; case '#prev': if( p &lt; 2 ) return false; d.page = p - 1; break; default: return false; } $.post( aacVars.ajaxpth, d, function( res ) { if( '-1' == res ) { alert( 'auth failed' ); return false; } r.html( res ); $( n ).text( d.page ); }); }); }); </code> 3) Copy the following code into your theme's functions.php file. <code> class Author_Ajax_Cats { private $posts_per_page = 3; private $comments_per_page = 1; private $posts_action = 'aac-posts'; private $comments_action = 'aac-comments'; private $js = array(); public function __construct() { add_action( 'parse_request', array( $this, 'aac_parse_request' ) ); add_action( 'wp_ajax_nopriv_' . $this-&gt;posts_action, array( $this, 'aac_ajax_posts' ) ); add_action( 'wp_ajax_' . $this-&gt;posts_action, array( $this, 'aac_ajax_posts' ) ); add_action( 'wp_ajax_nopriv_' . $this-&gt;comments_action, array( $this, 'aac_ajax_comments' ) ); add_action( 'wp_ajax_' . $this-&gt;comments_action, array( $this, 'aac_ajax_comments' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'aac_enqueue_scripts' ) ); add_action( 'author_ajax_catposts', array( $this, 'aac_print_posts' ) ); } public function aac_parse_request( $wp ) { if( !isset( $wp-&gt;query_vars['author_name'] ) || is_admin() ) return; $wp-&gt;query_vars['paged'] = 1; } private function setup_js_vars() { global $wp_query; $this-&gt;js['author'] = $wp_query-&gt;get_queried_object_id(); $this-&gt;js['posts_action'] = $this-&gt;posts_action; $this-&gt;js['comments_action'] = $this-&gt;comments_action; $this-&gt;js['nonce'] = wp_create_nonce( 'noncekey' ); $this-&gt;js['ajaxpth'] = admin_url( 'admin-ajax.php' ); } public function aac_enqueue_scripts() { if( !is_author() ) return; $this-&gt;setup_js_vars(); wp_register_script( 'author-ajax', get_bloginfo('stylesheet_directory') . '/authorposts.js', array( 'jquery' ), time(), true ); wp_localize_script( 'author-ajax', 'aacVars', $this-&gt;js ); wp_enqueue_script( 'author-ajax' ); } public function aac_ajax_comments() { if( !isset( $_POST['page'] ) || !isset( $_POST['author'] ) ) die; check_ajax_referer( 'noncekey' ); $authID = absint( $_POST['author'] ); $paged = absint( $_POST['page'] ); $args = array( 'user_id' =&gt; $authID, 'number' =&gt; $this-&gt;comments_per_page, 'offset' =&gt; ( ( $paged - 1 ) * $this-&gt;comments_per_page ), 'status' =&gt; 'approve', 'type' =&gt; 'comment' ); $answers_list = get_comments( $args ); if( empty( $answers_list ) ) { printf( '&lt;p class="nomore"&gt;%s&lt;/p&gt;', __( 'No more answers by this user.' ) ); die; } $_comment_walk = new Walker_Comment; echo '&lt;ul&gt;'; $_comment_walk-&gt;paged_walk( $answers_list, 0, 1, $this-&gt;comments_per_page, array( 'style' =&gt; 'ul', 'avatar_size' =&gt; 15, 'max_depth' =&gt; 1, 'callback' =&gt; array( $this, 'author_comment_walker' ) ) ); echo '&lt;/ul&gt;'; die; } public function aac_ajax_posts() { if( !isset( $_POST['page'] ) || !isset( $_POST['category'] ) || !isset( $_POST['author'] ) ) die; check_ajax_referer( 'noncekey' ); $catID = absint( str_replace( '#aac-', '', $_POST['category'] ) ); $authID = absint( $_POST['author'] ); $paged = absint( $_POST['page'] ); $args = array( 'paged' =&gt; $paged, 'numberposts' =&gt; $this-&gt;posts_per_page, 'author' =&gt; $authID, 'cat' =&gt; $catID ); $posts = get_posts( $args ); if( empty( $posts ) ) die( sprintf( '&lt;p class="nomore"&gt;%s&lt;/p&gt;', __( 'No more posts.' ) ) ); $this-&gt;do_posts( $posts ); die; } public function aac_print_posts( $cats = array() ) { //get_the_term_list( $post-&gt;ID, 'category', '&lt;ul&gt;&lt;li&gt;', '&lt;/li&gt;&lt;li&gt;', '&lt;/li&gt;&lt;/ul&gt;' ) foreach( $cats as $heading =&gt; $id ) { $args = array( 'cat' =&gt; $id, 'paged' =&gt; 1, // Always the first page on load 'numberposts' =&gt; $this-&gt;posts_per_page, 'author' =&gt; $this-&gt;js['author'] ); $posts = get_posts( $args ); printf( '&lt;h2&gt;%s&lt;/h2&gt;', $heading ); if( empty( $posts ) ) { printf( '&lt;div&gt;&lt;p class="nomore"&gt;%s&lt;/p&gt;&lt;/div&gt;', __( 'No posts.' ) ); continue; } printf( '&lt;div id="aac-%d" class="aac-result"&gt;', $id ); $this-&gt;do_posts( $posts ); printf( '&lt;/div&gt;&lt;div&gt;' ); printf( '&lt;p class="alignright"&gt;Page: &lt;span id="aac-%1$d-ap"&gt;1&lt;/span&gt;&lt;/p&gt;&lt;p class="alignleft"&gt;&lt;a class="aacnav aacprev" href="#aac-%1$d"&gt;%2$s&lt;/a&gt; &lt;a class="aacnav aacnext" href="#aac-%1$d"&gt;%3$s&lt;/a&gt;&lt;/p&gt;', $id, __('Previous'), __('Next') ); printf( '&lt;br class="clear" /&gt;&lt;/div&gt;' ); } ?&gt; &lt;h2&gt;Answers&lt;/h2&gt; &lt;?php $args = array( 'user_id' =&gt; $this-&gt;js['author'], 'number' =&gt; $this-&gt;comments_per_page, 'status' =&gt; 'approve', 'type' =&gt; 'comment' ); $answers_list = get_comments( $args ); if( empty( $answers_list ) ){ printf( '&lt;p&gt;%s&lt;/p&gt;', __( 'No answers by this user' ) ); return; } $_comment_walk = new Walker_Comment; printf( '&lt;div id="aac-comments"&gt;&lt;ul&gt;' ); $_comment_walk-&gt;paged_walk( $answers_list, 0, 1, $this-&gt;comments_per_page, array( 'style' =&gt; 'ul', 'avatar_size' =&gt; 15, 'max_depth' =&gt; 1, 'callback' =&gt; array( $this, 'author_comment_walker' ) ) ); printf( '&lt;/ul&gt;&lt;/div&gt;&lt;div&gt;&lt;p class="alignright"&gt;Page: &lt;span id="aac-comments-ap"&gt;1&lt;/span&gt;&lt;/p&gt;&lt;p class="alignleft"&gt;&lt;a class="aacnavc" href="#prev"&gt;%s&lt;/a&gt; &lt;a class="aacnavc" href="#next"&gt;%s&lt;/a&gt;&lt;/p&gt;&lt;br class="clear" /&gt;&lt;/div&gt;', __('Prev'), __('Next') ); } private function do_posts( $posts, $term_id = 0 ) { echo '&lt;ul&gt;'; foreach( $posts as $post ) printf( '&lt;li&gt;&lt;a href="%s"&gt;%s&lt;/a&gt;&lt;/li&gt;', get_permalink( $post-&gt;ID ), get_the_title( $post-&gt;ID ) ); echo '&lt;/ul&gt;'; } public function author_comment_walker( $comment, $args, $depth ) { $GLOBALS['comment'] = $comment; ?&gt; &lt;li&gt; &lt;div id="comment-&lt;?php comment_ID(); ?&gt;"&gt; &lt;div&gt; &lt;?php echo get_avatar( $comment, $args['avatar_size'], $default = '&lt;path_to_url&gt;' ); ?&gt; &lt;?php echo get_comment_author_link(); ?&gt; answered &lt;a href="&lt;?php echo get_permalink( $comment-&gt;comment_post_ID ); ?&gt;"&gt;&lt;?php echo get_the_title( $comment-&gt;comment_post_ID ); ?&gt;&lt;/a&gt; on &lt;a href="&lt;?php echo htmlspecialchars( get_comment_link( $comment-&gt;comment_ID ) ) ?&gt;"&gt;&lt;?php printf( __( '%1$s at %2$s' ), get_comment_date(), get_comment_time() ); ?&gt;&lt;/a&gt; &lt;?php //edit_comment_link( __( '(Edit)' ),' ','' ); ?&gt; &lt;/div&gt; &lt;?php // comment_text() ?&gt; &lt;p&gt;&lt;?php comment_excerpt(); ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php } } $aac = new Author_Ajax_Cats; </code> 4) Fire up an author page and see how the results look and to check my code works for you. How it looks locally with test data. Click to view larger version, scaled down for the answer Live demo of the code in action:** (test site) http://t31os.onatha.com/author/t31os/ 5) Provide some feedback.. :) I hope that helps...
Stomping WP_Query in author archive to facilitate pagination with custom queries
wordpress
I have a question. How can I clear the cache when a post is submitted ? Actually, I need to clear two speficied pages which display these articles ? By default, I have noticed the <code> index.php </code> is cleared automatically when a post is submitted. But not <code> Archive page </code> or <code> Category page </code> ... Thanks in advance. EDIT : By the way, how to clear only a specific page with W3 Total Cache ? Example : Clear <code> /blog.php </code>
Hm, I am not sure but I think that whole cache should be invalidated on publishing of new post... Had you tried to enable debug info in W3TC and check why are those pages aren't refreshed? As for manual cache clear, from plugin's FAQ: How can I flush the cache without using the WP Admin interface? It's possible to empty the entire cache or simply purge the cache of a single post / page: Purge the entire page cache: <code> if (function_exists('w3tc_pgcache_flush')) { w3tc_pgcache_flush(); } </code> Purge a single post / page by passing it's ID: <code> if (function_exists('w3tc_pgcache_flush_post')) { w3tc_pgcache_flush_post($post_id); } </code>
Clear cache when a post is submitted
wordpress
I'm finding a way to redirect to a sub-domain. Sub-domains contain instances of multiple languages, say for an example -: <code> http://mysite/?p=7694 </code> This is the English site and I want it to redirect to (when user selects particular language) <code> http://chinese.mysite/?p=7694 </code> Is there a simple way of doing this want to know if there are any plugins to do so. This the requirement of my client, and they wont to do it in that way. Thanks.
You can Use qTranslate , this WordPress plugin let you have an easy to use interface for managing a fully multilingual web site. One-Click-Switching between the languages - Change the language as easy as switching Choose one of 3 Modes to make your URLs pretty and SEO-friendly. - The everywhere compatible ?lang=en, simple and beautiful /en/foo/ or nice and neat en.yoursite.com One language for each URL - Users and SEO will thank you for not mixing multilingual content For reference: http://codex.wordpress.org/Multilingual_WordPress
Wordpress | Sub-domain switching
wordpress
Is there any RSS feed to keep track of the Newest Plugins published on wordpress.org?
Update: Found it from the dashboard widget code, its http://wordpress.org/extend/plugins/rss/browse/new/ As a workaround, you can use Page2rss.com to create a feed for that page - http://page2rss.com/page?url=wordpress.org/extend/plugins/browse/new/
How to keep track of new plugins published on wordpress.org?
wordpress
So what i would like to do is order in some CSS depending on the value of a custom field. The code below just says that if there is ANY value, do X, else do nothing... <code> &lt;?php $pageNumbered=get_post_meta($post-&gt;ID, 'page-number', true); ?&gt; &lt;?php if ( $pageNumbered ) : ?&gt; &lt;div class="page-number left"&gt; &lt;?php echo get_post_meta($post-&gt;ID, "page-number", true); ?&gt; &lt;/div&gt; &lt;?php else : ?&gt; &lt;?php endif; ?&gt; </code> ...what i want to do is say if the value is X do Y, if it is Z do XY etc etc... Thanks guys!
Sorry but it's not clear what you want to do. From what I understand is you simply want to use an elseif statement: <code> &lt;?php $pageNumbered=get_post_meta($post-&gt;ID, 'page-number', true); ?&gt; &lt;?php if ( $pageNumbered ) : ?&gt; &lt;div class="page-number left"&gt; &lt;?php echo get_post_meta($post-&gt;ID, "page-number", true); ?&gt; &lt;/div&gt; &lt;?php elseif($pageNumbered == "Z") : ?&gt; &lt;div class="page-number left"&gt; &lt;?php echo get_post_meta($post-&gt;ID, "page-number", true); ?&gt; &lt;/div&gt; &lt;?php endif; ?&gt; </code> If you can edit you question to be clearer then I might be able to help more.
How to make condition, based on custom fields value?
wordpress
I have a website that needs to display state-specific versions, for a few states. Obviously, I will need to parse the IP address to gain geographic information. Before I start making that plug-in, I figured I'd shoot a question out to the collective. To further explain my situation, the website has a different "version", depending on if customers are coming to it from Texas, California, New York and Canada. The language will be English throughout, but the content for Texas is different (think: compliance) from California. I was thinking of using a splash page (cringe) with a drop-down, should all else fail.
I guess stackexchange-url ("this thread") will steal you more than a day. After reading through it and all the code it contains, you'll be more than happy... or maybe just confused ;)
What is the best practice to localize content? (Geographic not langauge)
wordpress
I have over 400 interviews on my site and my audience keeps asking me for a way to sort through them. I don't have time to tag all 400 interviews. Do you think there's a way for my audience to tag interviews themselves?
Andrew, Matt Mullenweg uses a similar feature on on his blog, Ma.tt , that lets users tag photos. He released the code as a plugin, Matts Community Tags . You will have to create a custom taxonomy for the tags and add some additional code to your templates to make it work. See the discussion on the WordPress.org forums for more information.
How can I let my audience tag my posts?
wordpress
I'd like to find an optimized, WP_Query-safe method for generating a dynamically-populated copyright statement for the bottom of my themes. That is to say, I'd like to check the date (by year) of my oldest and newest posts and then output something along the lines of <code> [blog name] &amp;copy; [oldest post year]-[newest post year] [primary blog author] </code> What's the easiest/safest way to do so?
Here's what I use: <code> function oenology_copyright() { global $wpdb; $copyright_dates = $wpdb-&gt;get_results(" SELECT YEAR(min(post_date_gmt)) AS firstdate, YEAR(max(post_date_gmt)) AS lastdate FROM $wpdb-&gt;posts WHERE post_status = 'publish' "); $output = ''; if($copyright_dates) { $copyright = "&amp;copy; " . $copyright_dates[0]-&gt;firstdate; if($copyright_dates[0]-&gt;firstdate != $copyright_dates[0]-&gt;lastdate) { $copyright .= '-' . $copyright_dates[0]-&gt;lastdate; } $output = $copyright; } return $output; } </code> Of course, if there's a cleaner, safer, or more efficient method, I'd love to hear about it, too! EDIT: And here's a more cleaned-up version, that adds the copyright dates to wp_cache: <code> function oenology_copyright() { // check for cached values for copyright dates $copyright_cache = wp_cache_get( 'copyright_dates', 'oenology' ); // query the database for first/last copyright dates, if no cache exists if ( false === $copyright_cache ) { global $wpdb; $copyright_dates = $wpdb-&gt;get_results(" SELECT YEAR(min(post_date_gmt)) AS firstdate, YEAR(max(post_date_gmt)) AS lastdate FROM $wpdb-&gt;posts WHERE post_status = 'publish' "); $copyright_cache = $copyright_dates; // add the first/last copyright dates to the cache wp_cache_set( 'copyright_dates', $copyright_cache, 'oenology', '604800' ); } // Build the copyright notice, based on cached date values $output = '&amp;copy; '; if( $copyright_cache ) { $copyright = $copyright_cache[0]-&gt;firstdate; if( $copyright_cache[0]-&gt;firstdate != $copyright_cache[0]-&gt;lastdate ) { $copyright .= '-' . $copyright_cache[0]-&gt;lastdate; } $output .= $copyright; } else { $output .= date( 'Y' ); } return $output; } </code> Would this improve performance a bit?
How do I create a dynamically-updated copyright statement?
wordpress
Anyone who has experience in building wordpress plugin using eclipse PDT? My situation is: I need to build plugin that extend another plugin (look at it as premium version from another plugin) I already created project <code> plugin core </code> (the original plugin) by importing from svn repository I created eclipse library called <code> wordpress </code> and added it to <code> plugin core </code> project. I created another project <code> plugin extender </code> which will host scripts I created. The problem is, how to easily test it to wordpress, without having to manually copy-paste those project to <code> wp-content/plugins </code> ? Is there anyway to automatically copy those files to <code> wp-content/plugins </code> ? Or, do you guys have another solutions to this problem? As a side note, I'm working on windows 7. I'm aware of windows's <code> mklink </code> . However, my htdocs in on FAT32 partition and I'm in situation where I have to use Windows in the following months.
Create WordPress as a project. I have several such projects, trunk, old versions … for the following, I just use a project named WP Latest Final . You can use the standard installation with <code> /wp-content/plugins </code> . I put my <code> wp-content </code> directory in a Dropbox and stackexchange-url ("tell WP via wp-config.php") where to search for it. Create a new PHP project for each of your plugins. Use Create project from existing source and point to the plugin directory in <code> /wp-content/plugins </code> . Click Next in the project wizard, and go to the Projects tab. Choose Add … WP Latest Final . Select Access Rules and exclude <code> wp-admin/load-scripts.php </code> and <code> wp-admin/load-styles.php </code> . Hat tip to stackexchange-url ("@hakre"). Add more projects as you need, other plugins, theme projects etc. Click Finish . Done. If you have installed Egit , you probably want to create a new Git project now to get independent from Eclipse’s history tracking.
Strategy On Building Plugin Using Eclipse
wordpress
Is it possible to clone the plugins and settings from a WordPress site to a new fresh install? I don't want any of the content from the original site I just want all the plugins used and their settings. Just ftp'ing the plugins into the new install doesn't work. It's really important that all the settings are saved from the one site to the other as this will save a huge amount of time.
Usually blog settings, sidebars and plugins option are located in wp_options table. If you copy whole table except option_name IN ( 'siteurl', 'home' ), You get whole "old" configuration.
Clone plugins (and settings) to new installation?
wordpress
I want to include a slider in the default Wordpress theme on the home page. I did manage to get the page to show using <code> &lt;?php if ( is_home() ) { include ('slider.php'); } ?&gt; </code> but it doesn't look like it's loading the jquery script it needs or the style sheet. I know there's a conflict with scripts and Wordpress, I just don't know how to get it to work. Sample page is at http://axiomwest.com/ How do you feed in a page with it's own style sheet and scripts?
UPDATE! What I did was just include the slider I was trying to use. I linked the jquery scripts that page needs via the <code> &lt;?php bloginfo('template_directory'); ?&gt; </code> method. I did notice that it takes a couple of seconds to load that portion of the page, but it works. I still think this can be improved, but with time constraints it will have to do. Thanks all for your comments and eagerness to help!
What's the correct way to include files in Wordpress TwentyTen theme with it's own jquery scripts and css?
wordpress
This question is a little different then the others floating around here. The most similar one is "stackexchange-url ("How to get the parent's taxonomy ?")". I have a music cms setup that utilizes two post types: album and album media and a few taxonomies: genre , year , and artist . In the footer of every single-album.php post I want to display the corresponding album media template and do this dynamically. There is only one album media post for every one album . Both post types are associated with the three taxonomies. How can I write a loop inside another loop that automatically/dynamically obtains the associated taxonomies of it's parent post type? For example: An album called "Dark Side of the Moon" is associated with taxonomies rock, 1973, and Pink Floyd. The album media "Dark Side of the Moon" is associated with the same taxonomies. Within the main loop in single-album.php is another loop that looks for what three taxonomies the album is associated with and constructs a loop for "album-media". The contents of this loop could also be displayed as single-albummedia.php . Can this be done? I have the feeling that I am over-thinking this :) Things this question involves: multiple taxonomy query loop within a loop custom taxonomies and post types
As per comment I also see some trouble understanding <code> album </code> and <code> album media </code> essence. You are also mixing up terminology a bit with <code> terms </code> and <code> taxonomies </code> ( <code> term </code> is item in <code> taxonomy </code> ). So I am going to focus on your summary and leave to you how to put parts together: multiple taxonomy query - taxonomy queries got much improved in WP 3.1 and now you can construct very elaborate things with taxonomy parameters . loop within a loop - easier to say secondary loop , it doesn't matter where secondary loop is. because it shouldn't influence surroundings in any case. For WP_Query </code> object or <code> get_posts() </code> function are appropriate. custom taxonomies and post types a little to generic point, there are plenty of nifty related functions. I suppose <code> wp_get_post_terms() </code> sees a lot of usage, when taxonomies are involved.
How to dynamically build a multiple taxonomy query loop within a post type's single loop?
wordpress
is it possible to add extra fields via the functions.php script for attachments in wordpress? Tried loads of examples but none seem to work. Worried an existing plugin might be affecting my attempts but its not clear if its even possible. best, dan.
Here is a tutorial that shows how to add custom fields to the attachments/media gallery/thickbox/iframe/whatever-you-call it overlay. I've successfully used it, but have not yet taken it much further by adding radio buttons/checkboxes/etc or messed with limiting the changes to particular post types, but that all looks completely doable too. Here is the code from the link above, just in case it disappears some day: 1) 'attachment_fields_to_edit' : We will attach a function to this hook which will do the job of adding a custom field to Media Gallery. <code> /* For adding custom field to gallery popup */ function rt_image_attachment_fields_to_edit($form_fields, $post) { // $form_fields is a an array of fields to include in the attachment form // $post is nothing but attachment record in the database // $post-&gt;post_type == 'attachment' // attachments are considered as posts in WordPress. So value of post_type in wp_posts table will be attachment // now add our custom field to the $form_fields array // input type="text" name/id="attachments[$attachment-&gt;ID][custom1]" $form_fields["rt-image-link"] = array( "label" =&gt; __("Custom Link"), "input" =&gt; "text", // this is default if "input" is omitted "value" =&gt; get_post_meta($post-&gt;ID, "_rt-image-link", true), "helps" =&gt; __("To be used with special slider added via [rt_carousel] shortcode."), ); return $form_fields; } </code> 2) 'attachment_fields_to_save' : This in turn will accept and save the user input. <code> // now attach our function to the hook add_filter("attachment_fields_to_edit", "rt_image_attachment_fields_to_edit", null, 2); function rt_image_attachment_fields_to_save($post, $attachment) { // $attachment part of the form $_POST ($_POST[attachments][postID]) // $post['post_type'] == 'attachment' if( isset($attachment['rt-image-link']) ){ // update_post_meta(postID, meta_key, meta_value); update_post_meta($post['ID'], '_rt-image-link', $attachment['rt-image-link']); } return $post; } // now attach our function to the hook. add_filter("attachment_fields_to_save", "rt_image_attachment_fields_to_save", null , 2); </code>
custom fields for attachments?
wordpress
I have 7 posts, like this: 1 2 3 4 - this is the current post 5 6 7 As noted, number four is the current post being displayed. I need to create a query that will allow me to display the previous 3 posts (by publication date) and also the three posts after. This can be done with two separate queries. I've been able to display the immediately previous or next post, just not the ones further down / up. Any ideas?
This can be done in a single query, though i can't speak specifically about how well this query will perform(i've not spent a great deal with Union queries - never had a need, till now).. First, a function to select two sets of results, but using union to return them as a single result set. <code> function get_post_siblings( $limit = 3, $date = '' ) { global $wpdb, $post; if( empty( $date ) ) $date = $post-&gt;post_date; //$date = '2009-06-20 12:00:00'; // test data $limit = absint( $limit ); if( !$limit ) return; $p = $wpdb-&gt;get_results( " ( SELECT p1.post_title, p1.post_date, p1.ID FROM $wpdb-&gt;posts p1 WHERE p1.post_date &lt; '$date' AND p1.post_type = 'post' AND p1.post_status = 'publish' ORDER by p1.post_date DESC LIMIT $limit ) UNION ( SELECT p2.post_title, p2.post_date, p2.ID FROM $wpdb-&gt;posts p2 WHERE p2.post_date &gt; '$date' AND p2.post_type = 'post' AND p2.post_status = 'publish' ORDER by p2.post_date ASC LIMIT $limit ) ORDER by post_date ASC " ); $i = 0; $adjacents = array(); for( $c = count($p); $i &lt; $c; $i++ ) if( $i &lt; $limit ) $adjacents['prev'][] = $p[$i]; else $adjacents['next'][] = $p[$i]; return $adjacents; } </code> There's a test date in there, you can safely ignore that or add in your own value for testing. Here's some sample code you can use in your single.php loop to list out the results, though note this is just a generic example, and the function might need to select more/different data, but based on the info you've provided i wasn't sure exactly what you wanted, so the following is for illustration and to give a sample you can use to test the results.. <code> &lt;?php $siblings = get_post_siblings( 3 ); // This is the same as doing the call below(which is just for illustration) //$siblings = get_post_siblings( 3, $post-&gt;post_date ); $prev = $siblings['prev']; foreach( $prev as $p ) echo get_the_time( 'd m Y', $p ) . ': ' . apply_filters( 'the_title', $p-&gt;post_title ) . '&lt;br /&gt;'; $next = $siblings['next']; foreach( $next as $p ) echo get_the_time( 'd m Y', $p ) . ': ' . apply_filters( 'the_title', $p-&gt;post_title ) . '&lt;br /&gt;'; ?&gt; </code> Awaiting feedback... :)
Get Next / Prev 3 Posts in Relation to Current Post
wordpress
Why doesn't wp_title() display the author's name on an author archive as it does for a category or date archive? How can I hack this functionality? header.php calls: <code> &lt;title&gt;&lt;?php wp_title ( '|', true,'right' ); ?&gt;&lt;/title&gt; </code> Here is my author.php: <code> &lt;?php get_header(); ?&gt; &lt;?php $curauth = (isset($_GET['author_name'])) ? get_user_by('slug', $author_name) : get_userdata(intval($author)); get_userdata(intval($author)); function validate_gravatar($email) { // Craft a potential url and test its headers $hash = md5($email); $uri = 'http://www.gravatar.com/avatar/' . $hash . '?d=404'; $headers = @get_headers($uri); if (!preg_match("|200|", $headers[0])) { $has_valid_avatar = FALSE; } else { $has_valid_avatar = TRUE; } return $has_valid_avatar; } $user_email = $curauth-&gt;user_email; $has_avatar = validate_gravatar($user_email); ?&gt; &lt;div class="content-title"&gt;About &lt;?php echo $curauth-&gt;display_name; ?&gt;&lt;/div&gt; &lt;div id="curauth" class="post-content"&gt; &lt;div id="avatar"&gt;&lt;?php if($has_avatar) {echo get_avatar($curauth-&gt;ID, 70);} ?&gt;&lt;/div&gt; &lt;?php if ($curauth-&gt;user_description) : ?&gt; &lt;p&gt;&lt;?php echo $curauth-&gt;user_description; ?&gt;&lt;/p&gt; &lt;?php endif; if ($curauth-&gt;user_url) : ?&gt; &lt;p&gt;&lt;a href="&lt;?php echo $curauth-&gt;user_url; ?&gt;"&gt;&lt;?php echo $curauth-&gt;user_url; ?&gt;&lt;/a&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php if (!$curauth-&gt;user_description &amp;&amp; !$curauth-&gt;user_url) : ?&gt; &lt;p&gt;A riddle wrapped in a mystery inside an enigma...&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;div class="content-title"&gt;Contact&lt;/div&gt; &lt;div id="curauth" class="post-content"&gt; &lt;?php echo do_shortcode( '[contact-form 1 "Contact Author"]' ); ?&gt; &lt;/div&gt; &lt;div class="content-title"&gt; &lt;?php $post = $posts[0]; // Hack. Set $post so that the_date() works. ?&gt; &lt;?php _e('Author Archive'); ?&gt; &lt;a href="javascript: void(0);" id="mode"&lt;?php if ($_COOKIE['mode'] == 'grid') echo ' class="flip"'; ?&gt;&gt;&lt;/a&gt; &lt;/div&gt; &lt;ul&gt; &lt;!-- The Loop --&gt; &lt;?php get_template_part('loop'); ?&gt; &lt;?php get_template_part('pagination'); ?&gt; &lt;?php get_footer(); ?&gt; </code>
I see my name in the title when viewing author pages. <code> wp_title() </code> runs this code during execution.. <code> // If there's an author if ( is_author() ) { $author = get_queried_object(); $title = $author-&gt;display_name; } </code> Perhaps your author(s) don't have a display name set? Additionally be sure to try disabling plugins that may be hooking a filter onto <code> wp_title </code> and check your theme's function file for functions that hook on to...
wp_title() handling of author page
wordpress
I have a main menu where I display pages. All the pages have associated sub-pages, however in the menu some of them are displayed by themselves without sub-pages and some are displayed with a submenu as a list of all sub-pages. The pages in the menu are sorted according to the menu order specified for them. (Please see my code below). Now, I would like to add some categories at a specific place in the menu and not sure how to better do it. Is it possible to do it using wp_list_pages? What I like about my code is that whenever a subpage is added for a parent page that programmed to display all subpages, the newly added subpage will automatically appear in the site's menu. As opposite to using Appearance-> Menu functionality where a user will need to add a newly created subpage to the menu before it will appear on the site. I might be easily over complicating it(!) and the only way to do it is via Appearance-> Menu functionality. I would really appreciate any help and tips! Here is the code that I use to display pages, some with all the sub-pages and some only at the top level. <code> //main nav: use wp_list_pages to display cirtain parent pages without any and with all child pages (a tree with parent) $parents = array(5,7,17,61,19,25); $children = array(); foreach($parents as $parent) { $child_pages = get_pages( "child_of=$parent" ); if($child_pages){ foreach($child_pages as $child_page){ $children[] = $child_page-&gt;ID; } } } //add all the pages that need to be included without children $parents = array_merge( (array)$parents, (array)array(31,23) ); //merge $parents and $children $menu_pages = array_merge( (array)$parents, (array)$children ); $menu_pages_str = implode(",", $menu_pages); ?&gt; &lt;ul class="menu wrap"&gt; &lt;?php wp_list_pages( "sort_column=menu_order&amp;title_li=&amp;include=$menu_pages_str" ); ?&gt; &lt;/ul&gt; </code>
wp_list_pages has limited functionality, and would be difficult to inject Categories into the mix without rewriting the function itself. Using the built in Menu functionality is likely the best way to go, because you can at least set individual item classes, allowing you to create Menu headers for your top level categories (having the header items use a "header" class or similar). You may also be able to just use the get_pages() function, which will return an array of the pages instead of just printing them onto the page. This will allow you add logic to the display of the data when iterating through the array.
Add a specific category at a specific place to the menu that uses wp_list_pages
wordpress
I'd like to make a grid view that can be used to list items with a thumbnail, a primary description heading, a subheading, and possibly pricing details. This will not necessarily be for eCommerce as initially there will be no shopping cart. Similar to a post, clicking on the item should take you to a full "post" for that item with more information. For an idea what I'm thinking, take a look here: http://www.powerzoneequipment.com/inventory_search.asp?category=engines So here's my questions: 1) Does something like this already exist? 2) What are the requirements to build something like this? Should it be a plugin combined with a custom theme that supports this? Or could this be done with a custom theme and a custom post type? I realize that what I'm asking might be functionality more typically found in something like Drupal. However, I'm curious how difficult it would be to get this type of display in Wordpress.
It's not that difficult at all its simply styling you category loop in to a table something like this: <code> &lt;table&gt; &lt;tr&gt; &lt;th&gt;Photo&lt;/th&gt;&lt;th&gt;Item Brand, Model&lt;/th&gt;&lt;th&gt;Description&lt;/th&gt;&lt;th&gt;PSI&lt;/th&gt;&lt;th&gt;GPM&lt;/th&gt;&lt;th&gt;RPM&lt;/th&gt;&lt;th&gt;HP&lt;/th&gt;&lt;th&gt;Stock No.&lt;/th&gt; &lt;/tr&gt; &lt;?php while (have_posts()){ the_post(); ?&gt; &lt;tr&gt; &lt;td&gt; &lt;?php if(has_post_thumbnail()) { the_post_thumbnail(); } else { echo '&lt;img src="'.get_bloginfo("template_url").'/images/img-default.png" /&gt;'; } ?&gt; &lt;/td&gt; &lt;td&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;/td&gt; &lt;td&gt; &lt;?php the_excerpt(); ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo get_post_meta($post-&gt;ID,'PSI',true); ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo get_post_meta($post-&gt;ID,'GPM',true); ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo get_post_meta($post-&gt;ID,'RPM',true); ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo get_post_meta($post-&gt;ID,'HP',true); ?&gt; &lt;/td&gt; &lt;td&gt; &lt;?php echo get_post_meta($post-&gt;ID,'Stock_No',true); ?&gt; &lt;/td&gt; &lt;/tr&gt; &lt;?php } ?&gt; &lt;/table&gt; </code> It uses the post thumbnail as image , name as title and link to the "full post", the excerpt as description and assumes that you have custom fields named : PSI, GPM, RPM, HP and Stock_No. Now after that is done you can use custom post type say you call it products and different it from you regular posts using register_post_type . <code> add_action('init', 'custom_products_post_type_init'); function custom_products_post_type_init() { $labels = array( 'name' =&gt; _x('Products', 'post type general name'), 'singular_name' =&gt; _x('Product', 'post type singular name'), 'add_new' =&gt; _x('Add New', 'Product'), 'add_new_item' =&gt; __('Add New Product'), 'edit_item' =&gt; __('Edit Product'), 'new_item' =&gt; __('New Product'), 'view_item' =&gt; __('View Product'), 'search_items' =&gt; __('Search Products'), 'not_found' =&gt; __('No Products found'), 'not_found_in_trash' =&gt; __('No Products found in Trash'), 'parent_item_colon' =&gt; '', 'menu_name' =&gt; 'Products' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; true, 'rewrite' =&gt; true, 'capability_type' =&gt; 'post', 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'taxonomies' =&gt; array('category', 'post_tag'), 'supports' =&gt; array('title','editor','author','thumbnail','excerpt','comments','custom-fields') ); register_post_type('product',$args); } </code> and if you do it this way you just need to add a simple argument to query above the loop using query_post to let it know you are using your custom post type: query_posts('post_type='product'); hope this helps
How to Make a Custom Grid View
wordpress
I recently published a podcast hosted on WordPress.com on iTunes and it says "Podcasts by Unknown". It seems like it is missing the author tag. My question is that how can I add the author tag to the RSS since I used the RSS widget to expose my RSS?
iTunes uses extra tags for author information, category classification, ... I believe you can't add these using WordPress.com . What you can do is pick up your feed using FeedBurner and submit that URL to iTunes instead. FeedBurner has support for podcasts and allows you to fill in the extra iTunes tags.
WordPress.com podcast feed missing iTunes tags?
wordpress
I'm using the following code branch to execute some theme setup options... <code> $myTheme_initialized = get_option('myTheme_initialized'); if (is_admin() &amp;&amp; !$myTheme_initialized &amp;&amp; isset($_GET['activated'] ) ) { //do setup stuff } </code> What hook can I tap into when the theme is deactivated?
http://www.krishnakantsharma.com/2011/01/activationdeactivation-hook-for-wordpress-theme/# Pretty good writeup for activation and deactivation Same thing is here on SE stackexchange-url ("Theme Activate Hook")
How to determine when my theme is deactivated?
wordpress
Basically if you see the picture below there are 5 tab items in my groups page: Now, I want to be able to remove some of them. I want to be able to remove "Members" and "Send Invites" (for instance). This is on the frontend groups page. When you select a group and go to view it. I don't want to edit core files really, is there any other way to do this? Maybe a remove_action? Thank you.
Managed to crawl through the core code and find this function: <code> bp_core_remove_subnav_item </code> So you can do something like this: <code> function remove_group_options() { global $bp; bp_core_remove_subnav_item($bp-&gt;groups-&gt;slug, 'members'); bp_core_remove_subnav_item($bp-&gt;groups-&gt;slug, 'send-invites'); } add_action( 'bp_setup_nav', 'remove_group_options' ); </code>
Remove tabs from buddypress groups and members pages
wordpress
I'm trying to add an image in my CSS with the theme folder code, <code> &lt;?php bloginfo('template_directory'); ?&gt; </code> , which works in HTML but for some reason it's not working in the CSS. Does anyone know why or a solution? Here's my code: <code> background: url("&lt;?php bloginfo('template_directory'); ?&gt;/images/bg.jpg"); </code>
That's because php code inside a CSS file is not parsed unless you configure your server to. Just use it as a relative path to the image (as per the CSS file). <code> background: url("images/bg.jpg"); </code>
I'm trying to add an image in my CSS
wordpress
I'm finding that SEOmoz is showing page titles with ASCII when indexing my customer's site http://bulldogfencespokane.com . I'm concerned that this is how search engines will index the site. I'd love to remove commas and apostrophes but it would change the sentence structure entirely. Is there a way to clear up this formatting? <code> Spokane &amp;amp; Coeur d&amp;#039;Alene&amp;#039;s top fencing installers - Bulldog Fences Inc. </code>
ASCII characters will not cause any issues with search engines and they will be displayed properly. SEOmoz does this to avoid any chance of sql injection via its form fields.
ASCII titles with Yoast SEO plugin
wordpress
Hey Guys, I'm using a meta box to store a bunch of page ID's. When I try to pass the page ID's to the post__in parameter of WP_Query it doesn't work becuase the metabox comes throug as a string, when it needs to be a comma separated integers. So, say the "relatedpages" meta box contains: 55, 33, 22 <code> $relatedpages = get_post_meta($post-&gt;ID, 'relatedpages', true); $args = array( 'post_type' =&gt; 'page', 'posts_per_page' =&gt; -1, 'order' =&gt; 'ASC', 'orderby' =&gt; 'menu_order', 'post__in' =&gt; array($relatedpages) ); $myposts = get_posts($args); echo $myposts; </code> The problem is that $related pages is now "55, 33, 22" rather than 55, 33, 22 How can I overcome this? Is there a way to store just the integers in the meta box, rather than converting them to a string? Thanks, Drew
<code> 'post__in' =&gt; explode( ',', $relatedpages ) </code>
Passing meta_box string to post__in?
wordpress
Im trying to build a Featured post slider to show any post that i <code> mark as a "featured" </code> (with a in-post option) regardless the category or tag type... Im new to wordpress and although I understand a little bit php language im not a coder :( The slider is already working. The question is, how can can i build this slider with a loop to show the last <code> 7 </code> post marked as "featured" with the corresponding featured image? I already have the in-post option set up in a metabox in the post edit page, also the image size configured in my function.php ... Im using wordpress 3.1 with the genesis framework. Here is the slider code <code> &lt;div class="slider"&gt; &lt;ul class="main-wapper"&gt; &lt;li&gt; &lt;img src="path to featured img" title="the post title" height="300" width="315"&gt; &lt;div class="main-item-desc"&gt; &lt;h2&gt;&lt;a target="_parent" title="Post Title" href="post link"&gt;POST TITLE&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;Post Description limited to 150 character&lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;img src="path to featured img" title="the post title" height="300" width="315"&gt; &lt;div class="main-item-desc"&gt; &lt;h2&gt;&lt;a target="_parent" title="Post Title" href="post link"&gt;POST TITLE&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;Post Description limited to 150 character&lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;img src="path to featured img" title="the post title" height="300" width="315"&gt; &lt;div class="main-item-desc"&gt; &lt;h2&gt;&lt;a target="_parent" title="Post Title" href="post link"&gt;POST TITLE&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;Post Description limited to 150 character&lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;img src="path to featured img" title="the post title" height="300" width="315"&gt; &lt;div class="main-item-desc"&gt; &lt;h2&gt;&lt;a target="_parent" title="Post Title" href="post link"&gt;POST TITLE&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;Post Description limited to 150 character&lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="navigator-outer"&gt; &lt;ul class="navigator"&gt; &lt;li&gt; &lt;div&gt; &lt;img src="img src" /&gt; &lt;h3&gt;Content Title H3&lt;/h3&gt; &lt;p&gt;&lt;span class="date"&gt;20.01.2010&lt;/span&gt; | &lt;span class="category"&gt;CATEGORY NAME&lt;/span&gt;&lt;/p&gt;&lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div&gt; &lt;img src="img src" /&gt; &lt;h3&gt;Content Title H3&lt;/h3&gt; &lt;p&gt;&lt;span class="date"&gt;20.01.2010&lt;/span&gt; | &lt;span class="category"&gt;CATEGORY NAME&lt;/span&gt;&lt;/p&gt;&lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div&gt; &lt;img src="img src" /&gt; &lt;h3&gt;Content Title H3&lt;/h3&gt; &lt;p&gt;&lt;span class="date"&gt;20.01.2010&lt;/span&gt; | &lt;span class="category"&gt;CATEGORY NAME&lt;/span&gt;&lt;/p&gt;&lt;/div&gt; &lt;/li&gt; &lt;li&gt; &lt;div&gt; &lt;img src="img src" /&gt; &lt;h3&gt;Content Title H3&lt;/h3&gt; &lt;p&gt;&lt;span class="date"&gt;20.01.2010&lt;/span&gt; | &lt;span class="category"&gt;CATEGORY NAME&lt;/span&gt;&lt;/p&gt;&lt;/div&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;/div&gt; </code> here is a screenshot of the slider.. UPDATE: in my functions.php files i have this.. <code> // Add new image sizes add_image_size('Slider', 315, 300, TRUE); require_once(CHILD_DIR . '/lib/admin/inpost-settings.php'); wich is the code below.. </code> inpost-settings.php <code> $prefix = 'myslider_'; $meta_box = array( 'id' =&gt; 'slider-meta-box', 'title' =&gt; 'Featured Slider Options', 'page' =&gt; 'post', 'context' =&gt; 'normal', 'priority' =&gt; 'high', 'fields' =&gt; array( array( 'name' =&gt; 'Show in featured slider', 'id' =&gt; $prefix . 'show_post_slider', 'type' =&gt; 'checkbox' ) ) ); add_action('admin_menu', 'mytheme_add_box'); // Add meta box function mytheme_add_box() { global $meta_box; add_meta_box($meta_box['id'], $meta_box['title'], 'mytheme_show_box', $meta_box['page'], $meta_box['context'], $meta_box['priority']); } // Callback function to show fields in meta box function mytheme_show_box() { global $meta_box, $post; // Use nonce for verification echo '&lt;input type="hidden" name="mytheme_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" /&gt;'; echo '&lt;table class="form-table"&gt;'; foreach ($meta_box['fields'] as $field) { // get current post meta data $meta = get_post_meta($post-&gt;ID, $field['id'], true); echo '&lt;tr&gt;', '&lt;th style="width:20%"&gt;&lt;label for="', $field['id'], '"&gt;', $field['name'], '&lt;/label&gt;&lt;/th&gt;', '&lt;td&gt;'; switch ($field['type']) { case 'checkbox': echo '&lt;input type="checkbox" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' /&gt;'; break; } echo '&lt;td&gt;', '&lt;/tr&gt;'; } echo '&lt;/table&gt;'; } add_action('save_post', 'mytheme_save_data'); // Save data from meta box function mytheme_save_data($post_id) { global $meta_box; // verify nonce if (!wp_verify_nonce($_POST['mytheme_meta_box_nonce'], basename(__FILE__))) { return $post_id; } // check autosave if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return $post_id; } // check permissions if ('page' == $_POST['post_type']) { if (!current_user_can('edit_page', $post_id)) { return $post_id; } } elseif (!current_user_can('edit_post', $post_id)) { return $post_id; } foreach ($meta_box['fields'] as $field) { $old = get_post_meta($post_id, $field['id'], true); $new = $_POST[$field['id']]; if ($new &amp;&amp; $new != $old) { update_post_meta($post_id, $field['id'], $new); } elseif ('' == $new &amp;&amp; $old) { delete_post_meta($post_id, $field['id'], $old); } } } // check autosave if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return $post_id; } </code> Thanks in advance.
All you need is a simple query and to iterate over that query a couple of times so you can build the two required lists. <code> WP_Query </code> has a convenient method for resetting the pointer in the posts array, so you can loop over it again, called <code> rewind_posts </code> though i believe inside custom loops you have to reference the method directly.. Anyway, here's the kind of thing you're looking for, simply make adjustments as necessary.. <code> &lt;?php $featured = new WP_Query; $featured-&gt;query( array( 'meta_query' =&gt; array( array( 'key' =&gt; 'myslider_show_post_slider', 'value' =&gt; array('on','1'), 'compare' =&gt; 'IN', 'type' =&gt; 'CHAR', ) ), 'post_type' =&gt; 'post', 'post_status' =&gt; 'publish', 'ignore_sticky_posts' =&gt; '1', 'posts_per_page' =&gt; '7' //The number of post in the slider. ) ); if( $featured-&gt;have_posts() ) : ?&gt; &lt;div class="slider"&gt; &lt;ul class="main-wapper"&gt; &lt;?php while( $featured-&gt;have_posts() ) : $featured-&gt;the_post(); ?&gt; &lt;li&gt; &lt;?php the_post_thumbnail(); ?&gt; &lt;div class="main-item-desc"&gt; &lt;h2&gt;&lt;a title="&lt;?php the_title_attribute(); ?&gt;" href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;Where's this description suppose to be coming from?&lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;?php endwhile; $featured-&gt;rewind_posts(); ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;div class="navigator-outer"&gt; &lt;ul class="navigator"&gt; &lt;?php while( $featured-&gt;have_posts() ) : $featured-&gt;the_post(); ?&gt; &lt;li&gt; &lt;div&gt; &lt;?php the_post_thumbnail('Slider'); ?&gt; &lt;h3&gt;&lt;?php the_title(); ?&gt;&lt;/h3&gt; &lt;p&gt;&lt;span class="date"&gt;&lt;?php the_time( 'd.m.Y' ); ?&gt;&lt;/span&gt; | &lt;span class="category"&gt;&lt;?php the_category(','); ?&gt;&lt;/span&gt;&lt;/p&gt; &lt;/div&gt; &lt;/li&gt; &lt;?php endwhile; ?&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php endif; ?&gt; </code> Firstly, there was a stray closing DIV in the HTML you posted, so i simply removed that from the code above. Secondly, the checkbox does not have a value specified, in such cases a checkbox isn't given a specific value, the browser assigns the checkbox one, i'm not sure whether there's a common value that all browsers will use, but Firefox produces the value <code> on </code> , but i accounted for the possibility that the browser may assign a value of <code> 1 </code> , ideally the checkbox should be given a implicit value to ensure consistent behaviour, eg.. <code> echo '&lt;input type="checkbox" value="1" name="', $field['id'], '" id="', $field['id'], '"', $meta ? ' checked="checked"' : '', ' /&gt;'; </code> Any questions, lemme know..
PHP loop that selects posts with a particular in-post option
wordpress
I've created a page that includes a size such as 5x10 since the given term is something people often Google for, together with some other words. Wordpress is converting 5x10 to: &amp; # 2 1 5 ; (without the spaces) Is there any way to prevent this? I suppose that there are places where this feature would be useful but in my case it's hindering my SEO efforts.
This is performed by <code> wptexturize() </code> . Unfortunately it saves replacement lists as static variables which you can't modify. So your options are: Remove <code> wptexturize </code> filter from related hook (depends on where you have that replacement done). Write and add your own filter that will replace converted symbol back.
'x' Converted to html code in example: 5x10
wordpress
Since WP 3.1, it's been possible to use Tumblr-style post formats. I want to use the 'aside' option in a theme, but I want it to have a different title in the WP admin area. So, for example, when a user is writing a post, they have the option for the post to be, say, either 'Standard' or 'Quick' -- rather than 'Standard' or 'Aside'. Is it possible to do this without modifying the core? It'd be great if it's something that could be pretty easily done via functions.php or the like. I live in hope... Thanks!
I think this is the only way for now. Put this in your functions.php in your theme folder or create a simple plugin: <code> function rename_post_formats( $safe_text ) { if ( $safe_text == 'Aside' ) return 'Quick'; return $safe_text; } add_filter( 'esc_html', 'rename_post_formats' ); //rename Aside in posts list table function live_rename_formats() { global $current_screen; if ( $current_screen-&gt;id == 'edit-post' ) { ?&gt; &lt;script type="text/javascript"&gt; jQuery('document').ready(function() { jQuery("span.post-state-format").each(function() { if ( jQuery(this).text() == "Aside" ) jQuery(this).text("Quick"); }); }); &lt;/script&gt; &lt;?php } } add_action('admin_head', 'live_rename_formats'); </code>
Is it possible to rename a post format?
wordpress
I'm using the following code to create custom write panels: <code> &lt;?php $key = "project"; $meta_boxes = array( "project_services" =&gt; array( "name" =&gt; "project_services", "title" =&gt; "Services", "description" =&gt; "List the services provided for the project."), "project_name" =&gt; array( "name" =&gt; "project_name", "title" =&gt; "Name", "description" =&gt; "Write the name of the project."), "project_overview" =&gt; array( "name" =&gt; "project_overview", "title" =&gt; "Overview", "description" =&gt; "Write an overview of the project.") ); function create_meta_box() { global $key; if( function_exists( 'add_meta_box' ) ) { add_meta_box( 'new-meta-boxes', ucfirst( $key ) . ' Description', 'display_meta_box', 'post', 'normal', 'high' ); } } function display_meta_box() { global $post, $meta_boxes, $key; ?&gt; &lt;div class="form-wrap"&gt; &lt;?php wp_nonce_field( plugin_basename( __FILE__ ), $key . '_wpnonce', false, true ); foreach($meta_boxes as $meta_box) { $data = get_post_meta($post-&gt;ID, $key, true); ?&gt; &lt;div class="form-field form-required"&gt; &lt;label for="&lt;?php echo $meta_box[ 'name' ]; ?&gt;"&gt;&lt;?php echo $meta_box[ 'title' ]; ?&gt;&lt;/label&gt; &lt;input type="text" name="&lt;?php echo $meta_box[ 'name' ]; ?&gt;" value="&lt;?php echo htmlspecialchars( $data[ $meta_box[ 'name' ] ] ); ?&gt;" /&gt; &lt;p&gt;&lt;?php echo $meta_box[ 'description' ]; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;?php } function save_meta_box( $post_id ) { global $post, $meta_boxes, $key; foreach( $meta_boxes as $meta_box ) { $data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ]; } if ( !wp_verify_nonce( $_POST[ $key . '_wpnonce' ], plugin_basename(__FILE__) ) ) return $post_id; if ( !current_user_can( 'edit_post', $post_id )) return $post_id; update_post_meta( $post_id, $key, $data ); } </code> Now, I can call that metadata in the following way: <code> &lt;?php $data = get_post_meta( $post-&gt;ID, 'project', true ); ?&gt; &lt;p&gt;&lt;?php echo $data[ 'project_services' ]; ?&gt;&lt;/p&gt; </code> But I would like to call it in this way: <code> &lt;p&gt;&lt;?php project_services(); ?&gt;&lt;/p&gt; </code> Any suggestions?
Try this? <code> &lt;?php function get_project_services() { global $post; $data = get_post_meta( $post-&gt;ID, 'project', true ); $project_services = $data['project_services']; return $project_services; } ?&gt; </code> Then in your template file: <code> &lt;p&gt;&lt;?php echo get_project_services(); ?&gt;&lt;/p&gt; </code> I think that will do what you're asking? (Edited to match your comment.)
How to display this meta data (an array) in form of a function (created with a custom write panel)?
wordpress
Is there a way of for instance, insert a post and assign a category to it, without accessing Wordpress' back-end?
Yes @janoChen, you can use wp_insert_post, take a look at this answers: stackexchange-url ("WP insert post PHP function and Custom Fields") stackexchange-url ("Fron-End Post Submission")
Is there a way of posting or inserting content directly to the database (without entering the wp-admin)?
wordpress
Pretty self-explanatory. How does one add another user to this function for functions.php, i.e., user2, who will be shown different menu items than user1? I tried adding another <code> if($current_user-&gt;user_login == 'user2') </code> condition, but no luck. User2 will have different admin rights, if that matters. But basically, I need to be able to show one set of menu items to user1 and another set to user2, so I need to figure out some if else logic. But I tried that, and I get a "can't redeclare a previously declared" error for the menu function. <code> function remove_menus() { global $menu; global $current_user; get_currentuserinfo(); if($current_user-&gt;user_login == 'user1') { $restricted = array( __('Links'), __('Comments'), __('Appearance'), __('Plugins'), __('Profile'), __('Tools'), __('Settings') ); end ($menu); while (prev($menu)){ $value = explode(' ',$menu[key($menu)][0]); if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);} } } } add_action('admin_menu', 'remove_menus'); </code>
Why not just add another if? <code> function remove_menus(){ global $menu; global $current_user; get_currentuserinfo(); //check first user if($current_user-&gt;user_login == 'user1'){ $restricted = array( __('Links'), __('Comments'), __('Appearance'), __('Plugins'), __('Profile'), __('Tools'), __('Settings') ); end ($menu); while (prev($menu)){ $value = explode(' ',$menu[key($menu)][0]); if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);} } } //check second user if($current_user-&gt;user_login == 'user2'){ $restricted = array( __('Links'), __('Comments'), __('Appearance'), __('Plugins') ); end ($menu); while (prev($menu)){ $value = explode(' ',$menu[key($menu)][0]); if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){unset($menu[key($menu)]);} } } } add_action('admin_menu', 'remove_menus'); </code> same function but two different users will get different menus.
How to add another user to this remove_menu function?
wordpress
I have post type 'product' and hierarchical taxonomy 'types' attached to it. In this taxonomy, I have terms: 'dry-clean', 'washer', etc. With several sub terms on each terms. In my situation, I need to display, eg: http://example.com/types/washer -> display all sub terms on it http://example.com/types/washer/ {subterm} -> display all posts on it My questions is: How do I get permalink URL for parent terms? I try URL above, but it result in 404. How the template files work for that kind of problem? is <code> taxonomy-types-washer.php </code> enough for case #1? or should I create <code> taxonomy-types.php </code> and create the logic there? in my mind, after scanning template hierarchy , I might need <code> taxonomy-types-{term_parent}.php </code> to list all sub terms and <code> taxonomy-types.php </code> to list all product in sub terms. ultimately, to display each product, I will have to create <code> single-product.php </code> On a slightly unrelated problem. I find that <code> archive-{posttype}.php </code> doesn't work when I don't have any post on it. Is there any solution for this? ( should I create different question, or stick with this one )? UPDATE I checked my <code> rewrite_rules </code> options and it doesn't list [types] at all. I don't know why. To test it, I change my slug into <code> product-types </code> , flush permalink and it list this: <code> [product-types/([^/]+)/feed/(feed|rdf|rss|rss2|atom)/?$] =&gt; index.php?types=$matches[1]&amp;feed=$matches[2] [product-types/([^/]+)/(feed|rdf|rss|rss2|atom)/?$] =&gt; index.php?types=$matches[1]&amp;feed=$matches[2] [product-types/([^/]+)/page/?([0-9]{1,})/?$] =&gt; index.php?types=$matches[1]&amp;paged=$matches[2] [product-types/([^/]+)/?$] =&gt; index.php?types=$matches[1] </code> So I guess it's registered now. I try to load URL <code> product-types/washer </code> it goes to 404. I try to load URL <code> index.php?types=washer </code> . It too, goes 404. Right now, I have this files: taxonomy-types-washer.php taxonomy-types.php So, I don't know what's wrong with this one :(. UPDATE #2 I find the problem. It's because I missed <code> 'rewrite'=&gt;array('hierarchical'=&gt;true) </code> Here's the new <code> rewrite_rules </code> : <code> [product-types/(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$] =&gt; index.php?types=$matches[1]&amp;feed=$matches[2] [product-types/(.+?)/(feed|rdf|rss|rss2|atom)/?$] =&gt; index.php?types=$matches[1]&amp;feed=$matches[2] [product-types/(.+?)/page/?([0-9]{1,})/?$] =&gt; index.php?types=$matches[1]&amp;paged=$matches[2] [product-types/(.+?)/?$] =&gt; index.php?types=$matches[1] </code>
These types of URLs are supported since WP 3.1: <code> register_taxonomy( 'types', 'post', array( 'hierarchical' =&gt; true, 'rewrite' =&gt; array( 'hierarchical' =&gt; true ), ... ); </code> Remember to flush the rewrite rules after making the change. The template you would use for both parent and child terms is taxonomy-types.php: <code> $current_term = get_queried_object(); if ( 0 == $current_term-&gt;parent ) { // it's a parent term; display it's child terms using wp_list_categories() etc. } else { // it's a child term; display the posts using The Loop etc. } </code>
Taxonomy, Terms, and Template Files
wordpress
When a post is split on more pages TwentyTen theme use the native function <code> wp_link_pages </code> to display a navigation page bar at the end of post. I am trying to style those elements for my theme, but unfortunately it seems that the current page number cannot be styled. I imagine that I should override the <code> wp_link_pages </code> function but I am still learning the basic of WP programming. Can you help me identifing the steps to follow to solve this problem?
Unfortunately, there is no way to do this just with native functions: WP is … request agnostic and produces always links to the current page (nav manus, list pages …). Also, you cannot use a filter, because <code> wp_link_pages() </code> has no appropriate filter. In my themes, I use an own function, based on this code . It is probably too long to post it here, so I put it as a plugin on GitHub: Logical Page Links . You may use the plugin as is or copy the code into your theme. The resulting markup will look like this: <code> &lt;p class="pager"&gt; &lt;b title='You are here.'&gt;1&lt;/b&gt; &lt;a class=number href='http://example.com/page/2/'&gt;2&lt;/a&gt; &lt;/p&gt; </code> The <code> &lt;b&gt; </code> marks the current page, you can style it via: <code> .pager b { color: #fff; background: #111; } </code> More features are listed in the readme of the plugin. Update I misunderstood the question. I thought you needed such a function for archives. Sorry. Here is a rewritten version of <code> wp_link_pages() </code> as a plugin. I guess you’ll put it into your theme. <code> &lt;?php # -*- coding: utf-8 -*- /* Plugin Name: Numbered In-Page Links Description: Replacement for wp_link_pages with numbers. Use do_action( 'numbered_in_page_links' ); Version: 1.0 Required: 3.1 Author: Thomas Scholz Author URI: http://toscho.de License: GPL v2 */ ! defined( 'ABSPATH' ) and exit; add_action( 'numbered_in_page_links', 'numbered_in_page_links', 10, 1 ); /** * Modification of wp_link_pages() with an extra element to highlight the current page. * * @param array $args * @return void */ function numbered_in_page_links( $args = array () ) { $defaults = array( 'before' =&gt; '&lt;p&gt;' . __('Pages:') , 'after' =&gt; '&lt;/p&gt;' , 'link_before' =&gt; '' , 'link_after' =&gt; '' , 'pagelink' =&gt; '%' , 'echo' =&gt; 1 // element for the current page , 'highlight' =&gt; 'b' ); $r = wp_parse_args( $args, $defaults ); $r = apply_filters( 'wp_link_pages_args', $r ); extract( $r, EXTR_SKIP ); global $page, $numpages, $multipage, $more, $pagenow; if ( ! $multipage ) { return; } $output = $before; for ( $i = 1; $i &lt; ( $numpages + 1 ); $i++ ) { $j = str_replace( '%', $i, $pagelink ); $output .= ' '; if ( $i != $page || ( ! $more &amp;&amp; 1 == $page ) ) { $output .= _wp_link_page( $i ) . "{$link_before}{$j}{$link_after}&lt;/a&gt;"; } else { // highlight the current page // not sure if we need $link_before and $link_after $output .= "&lt;$highlight&gt;{$link_before}{$j}{$link_after}&lt;/$highlight&gt;"; } } print $output . $after; } </code>
How to style current page number (wp_link_pages)?
wordpress
We're using Facebook Comments for the comment functionality on our WordPress blog. I thought it'd be nice to embed the page with Facebook Moderation tools on the WP Dashboard. That way, we can immediately see who commented on what when we log in. I've looked for the functionality to embed an html page in a dashboard widget but I haven't managed to find something. Does anybody know if this is possible?
<code> function facebook_setup_function() { add_meta_box( 'facebook_widget', 'Facebook Moderation Tools', 'facebook_widget_function', 'dashboard', 'normal', 'low' ); } function facebook_widget_function() { include ('facebook.php'); } add_action( 'wp_dashboard_setup', 'facebook_setup_function' ); </code> add the above to your functions file and replace the include url with the php file you wish to include into your dashboard. Setting it up ; Use the facebook.php and add an iframe to it, or ajax call to load the facebook tools, then simply just echo that file into your dashboard page :)
Embed a page within WordPress dashboard?
wordpress
How can I force the user to first choose a category before continuing to the editor when creating a new post? I want to stackexchange-url ("set some default content"), but this is based on the category, so I need to know that before showing the editor (unless I do some fancy Ajax stuff, but in this case I don't want to do that).
I solved this by hooking into <code> post-new.php </code> , and checking for a <code> category_id </code> request parameter. If it does not exist, I display a form with a category dropdown that submits back to this page, and then call <code> exit() </code> so the regular post form does not display. If it exists, I set up a hook for <code> wp_insert_post </code> that will add the category. This works because a new post is already created in the database via the <code> get_default_post_to_edit() </code> function , and we can add categories, tags, or other (meta) content. The form is rendered after this with the "fresh" new content. <code> add_filter( 'load-post-new.php', 'wpse14403_load_post_new' ); function wpse14403_load_post_new() { $post_type = 'post'; if ( isset( $_REQUEST['post_type'] ) ) { $post_type = $_REQUEST['post_type']; } // Only do this for posts if ( 'post' != $post_type ) { return; } if ( array_key_exists( 'category_id', $_REQUEST ) ) { add_action( 'wp_insert_post', 'wpse14403_wp_insert_post' ); return; } // Show intermediate screen extract( $GLOBALS ); $post_type_object = get_post_type_object( $post_type ); $title = $post_type_object-&gt;labels-&gt;add_new_item; include( ABSPATH . 'wp-admin/admin-header.php' ); $dropdown = wp_dropdown_categories( array( 'name' =&gt; 'category_id[]', 'hide_empty' =&gt; false, 'echo' =&gt; false, ) ); $category_label = __( 'Category:' ); $continue_label = __( 'Continue' ); echo &lt;&lt;&lt;HTML &lt;div class="wrap"&gt; &lt;h2&gt;{$title}&lt;/h2&gt; &lt;form method="get"&gt; &lt;table class="form-table"&gt; &lt;tbody&gt; &lt;tr valign="top"&gt; &lt;th scope="row"&gt;{$category_label}&lt;/th&gt; &lt;td&gt;{$dropdown}&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;&lt;/td&gt; &lt;th&gt;&lt;input name="continue" type="submit" class="button-primary" value="{$continue_label}" /&gt;&lt;/th&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;input type="hidden" name="post_type" value="{$post_type}" /&gt; &lt;/form&gt; &lt;/div&gt; HTML; include( ABSPATH . 'wp-admin/admin-footer.php' ); exit(); } // This function will only be called when creating an empty post, // via `get_default_post_to_edit()`, called in post-new.php function wpse14403_wp_insert_post( $post_id ) { wp_set_post_categories( $post_id, $_REQUEST['category_id'] ); } </code>
Force category choice before creating new post?
wordpress
I am developing a theme for my blog using Twenty Ten as starting point. Now, I am trying to understand how it manages the background image that can be set in theme options but I wasn't able to find the code. Can you help find where is that implementation?
This is native WP feature, it is set up in Twenty Ten with simple <code> add_custom_background() </code> call in <code> functions.php </code> .
Where is the code that set the background image in TwentyTen theme?
wordpress
hey guys, when posting a youtube video link in the backend (in a post or a page) wordpress is automatically creating the embed code for me. Is it possible to add a filter to that? I'd love to change the width and height of all embedded videos to 100%? e.g. <code> &lt;object width="100%" height="100%"&gt; &lt;param name="movie" value="http://www.youtube.com/v/rBa5qp9sUOY?version=3"&gt; &lt;param name="allowFullScreen" value="true"&gt; &lt;param name="allowscriptaccess" value="always"&gt; &lt;embed src="http://www.youtube.com/v/rBa5qp9sUOY?version=3" type="application/x-shockwave-flash" width="100%" height="100%" allowscriptaccess="always" allowfullscreen="true"&gt; &lt;/object&gt;` </code> Any idea how to solve this? edit: Or is it at least possible to add a classname to the object tag so I can use javascript to influence with and height of the embedded video? update: Thank you I tried the following piece of code but it doesn't work? <code> add_filter('oembed_result','oembed_result', 10, 3); function oembed_result($html, $url, $args) { // $args includes custom argument // modify $html as you need //return $html; } </code> if return $html is a comment no youtube video should appear right, however it does!
Yes, there is a filter for Oembeds. Two (or even more) in fact: <code> oembed_result </code> will be called before it is put in the cache (so only once per external embed), and <code> embed_oembed_html </code> after the cache (so every time the item is displayed). If you only need to modify it once, <code> oembed_result </code> is probably your friend. The second parameter is the <code> $url </code> , so check whether it comes from Youtube before you do something.
add_filter to youtube embeds?
wordpress
This is the code I used to create the meta boxes: <code> &lt;?php $key = "project"; $meta_boxes = array( "project_services" =&gt; array( "name" =&gt; "project_services", "title" =&gt; "Services", "description" =&gt; "List the services provided for the project."), "project_name" =&gt; array( "name" =&gt; "project_name", "title" =&gt; "Name", "description" =&gt; "Write the name of the project."), "project_overview" =&gt; array( "name" =&gt; "project_overview", "title" =&gt; "Overview", "description" =&gt; "Write an overview of the project.") ); function create_meta_box() { global $key; if( function_exists( 'add_meta_box' ) ) { add_meta_box( 'new-meta-boxes', ucfirst( $key ) . ' Description', 'display_meta_box', 'post', 'normal', 'high' ); } } function display_meta_box() { global $post, $meta_boxes, $key; ?&gt; &lt;div class="form-wrap"&gt; &lt;?php wp_nonce_field( plugin_basename( __FILE__ ), $key . '_wpnonce', false, true ); foreach($meta_boxes as $meta_box) { $data = get_post_meta($post-&gt;ID, $key, true); ?&gt; &lt;div class="form-field form-required"&gt; &lt;label for="&lt;?php echo $meta_box[ 'name' ]; ?&gt;"&gt;&lt;?php echo $meta_box[ 'title' ]; ?&gt;&lt;/label&gt; &lt;input type="text" name="&lt;?php echo $meta_box[ 'name' ]; ?&gt;" value="&lt;?php echo htmlspecialchars( $data[ $meta_box[ 'name' ] ] ); ?&gt;" /&gt; &lt;p&gt;&lt;?php echo $meta_box[ 'description' ]; ?&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;?php } function save_meta_box( $post_id ) { global $post, $meta_boxes, $key; foreach( $meta_boxes as $meta_box ) { $data[ $meta_box[ 'name' ] ] = $_POST[ $meta_box[ 'name' ] ]; } if ( !wp_verify_nonce( $_POST[ $key . '_wpnonce' ], plugin_basename(__FILE__) ) ) return $post_id; if ( !current_user_can( 'edit_post', $post_id )) return $post_id; update_post_meta( $post_id, $key, $data ); } add_action( 'admin_menu', 'create_meta_box' ); add_action( 'save_post', 'save_meta_box' ); ?&gt; </code> Then, I changed the input to a textarea: <code> &lt;textarea name="&lt;?php echo $meta_box[ 'name' ]; ?&gt;"&gt; &lt;?php echo htmlspecialchars( $data[ $meta_box[ 'name' ] ] ); ?&gt; &lt;/textarea&gt; </code> This turns all the three fields into text areas. I would like to only make the third field, <code> project_overview </code> a textarea. Any suggestions?
Modify your array definition with something like this to add a new element of the array that specify the type of the field <code> "project_overview" =&gt; array( "name" =&gt; "project_overview", "title" =&gt; "Overview", "description" =&gt; "Write an overview of the project.", "type"=&gt;"textarea") </code> Then in your code substitute <code> &lt;input type="text" name="&lt;?php echo $meta_box[ 'name' ]; ?&gt;" value="&lt;?php echo htmlspecialchars( $data[ $meta_box[ 'name' ] ] ); ?&gt;" /&gt; </code> with something like this <code> &lt;? if ( $meta_box['type'] == 'textarea') { ? &lt;textarea name="&lt;?php echo $meta_box[ 'name' ]; ?&gt;"&gt; &lt;?php echo htmlspecialchars( $data[ $meta_box[ 'name' ] ] ); ?&gt; &lt;/textarea&gt; } else { ?&gt; &lt;input type="text" name="&lt;?php echo $meta_box[ 'name' ]; ?&gt;" value="&lt;?php echo htmlspecialchars( $data[ $meta_box[ 'name' ] ] ); ?&gt;" /&gt; } ?&gt; </code> Is better that you wrap the piece of code above in a function, like <code> function print_meta_box ( $meta_box ) { switch (meta_box ['type'] ) { case 'textarea': .... your code ... break; default: } } </code>
How to add a textarea to only one of the fields of this custom metabox?
wordpress
I want to make minor css-changes based on the choice of the top (root) menu. What's the proper way to handle this in WP? //edit// It's a website (pages), no blog, and basically, the colors of some links and some images should depend of the choosen top-menu-item. Example, page-structure: * Start * Products * Prod.categ. * A product * Services * List of services * Nested * Contact * Main office * List of staff * Abroad * Another list Top level is in a topmenu, one-level, and level2&amp;3 in nested left-menu. Now minor coloured items in sidemenu changes depending on selected top-menu item. //end edit// regards, /t
My answer adds a class to the <code> &lt;body&gt; </code> element via the <code> body_class </code> filter. This is probably the easiest way to apply extra formatting to any element on the page. The added classes are <code> wpse14430_products </code> , <code> wpse14430_services </code> or <code> wpse14430_contact </code> (based on the slugs of the top pages in your example). Using <code> wp_nav_menu() </code> If you use <code> wp_nav_menu() </code> to display the menu, WordPress builds a tree of the menu items. We can use this information to get the top page of the current item. Only problem: we need it in the <code> &lt;body&gt; </code> tag, thus before the menu is rendered. The solution is to save the menu in an variable which we later echo ourselves. Taking the Twenty Ten theme as an example, I move the <code> wp_nav_menu() </code> call up to the first <code> &lt;?php </code> block: <code> $wpse14430_menu = wp_nav_menu( array( 'container_class' =&gt; 'menu-header', 'theme_location' =&gt; 'primary', 'echo' =&gt; false, ) ); </code> And where we used to call it, we now echo our saved output: <code> echo $wpse14430_menu; </code> <code> wp_nav_menu() </code> has an interesting filter, called after the menu items are ordered and have their classes. The classes already contain ancestor information. We hook into this filter and find the first item that is the current item or an ancestor of it: <code> add_filter( 'wp_nav_menu_objects', 'wpse14430_wp_nav_menu_objects' ); function wpse14430_wp_nav_menu_objects( $sorted_menu_items ) { // The items are in menu order, so the first match is the top item foreach ( $sorted_menu_items as $menu_item ) { if ( $menu_item-&gt;current || $menu_item-&gt;current_item_ancestor ) { $GLOBALS['wpse14430_top_page'] = get_post( $menu_item-&gt;object_id ); break; } } return $sorted_menu_items; } </code> Now we got the top page, and only need to add this to the body class: <code> add_filter( 'body_class', 'wpse14430_body_class_menu' ); function wpse14430_body_class_menu( $body_class ) { if ( isset( $GLOBALS['wpse14430_top_page'] ) ) { $body_class[] = 'wpse14430_' . $GLOBALS['wpse14430_top_page']-&gt;post_name; } return $body_class; } </code> Using pages as the menu structure If you don't use <code> wp_nav_menu() </code> but instead use the direct ordering of the pages, you can also check for ancestors. Remember that if don't define a menu using the new menu system but still display the page list via <code> wp_nav_menu() </code> (the fallback functionality), the above system will work for you. <code> add_filter( 'body_class', 'wpse14430_body_class_pages' ); function wpse14430_body_class_pages( $body_class ) { if ( is_page() ) { $null = null; $top_page = get_post( $null ); $ancestors = get_post_ancestors( $top_page ); if ( $ancestors ) { $top_page = get_post( array_pop( $ancestors ) ); } $body_class[] = 'wpse14430_' . $top_page-&gt;post_name; } return $body_class; } </code>
Minor css-change based on topmenu - how?
wordpress
I'm running several Wordpress installs on my desktop machine using XAMPP. I would like to move them to my laptop as well. Can I simply copy the htdocs, mysql and phpMyAdmin directories to the laptop, replacing the ones from the new install? What if I copied everything in the directory structure under XAMPP? Will this work, or will everything go gruesomely wrong? If so, what is the right way? UPDATE - Tried copying the desktop files to the laptop. A combination of lack of sleep, XP to Windows 7 and bad juju made this a case of epic fail. To get things done quickly, I resorted to doing an XML export and reinstalling my theme on the laptop in order to do the demo.
From personal experience sync between two different computers work best in one direction. For example your desktop is primary and notebook is precise mirror (yep, of whole directory tree preferably with tool that doesn't touch unchanged files). Two way sync gets messy very fast for web stack. If you need to actively work with same stack on different computers it is easier to keep portable stack on external media (like external hard drive or flash drive) and just plug it. Don't forget solid backup routine (which you should have in any case) or if external thingie dies - you lose whole stack. PS another idea is to use something like Dropbox, but I hadn't tried that in practice yet.
I have a desktop and a laptop: What's the best way to move between local installations?
wordpress
I have a site that displays the content only to registered users. Most of the content is available to all the users, but some of it is user specific (i.e. all users have that page, but each sees a it's own content which no one else can see). Any idea as to how I can restrict(and display) specific content per specific user ?
I had coded something like this a while back and i remember wanting to upload it to the plugin repository but never had the time, Basically it adds a meta box to the post or page edit screen and lets the user select specific users by name or roles and then it check using <code> the_content </code> filter, so here you go: Update: It just got approved in to WordPress plugin repository so you can download it User specific content form there or from your dashboard and i wrote a little about it here . <code> &lt;?php /* Plugin Name: User Specific Content Plugin URI: http://en.bainternet.info Description: This Plugin allows you to select specific users by user name, or by role name who can view a specific post content or page content. Version: 0.1 Author: Bainternet Author URI: http://en.bainternet.info */ /* Define the custom box */ add_action('add_meta_boxes', 'User_specific_content_box'); /* Adds a box to the main column on the custom post type edit screens */ function User_specific_content_box() { add_meta_box('User_specific_content', __( 'User specific content box'),'User_specific_content_box_inner','post'); add_meta_box('User_specific_content', __( 'User specific content box'),'User_specific_content_box_inner','post'); } /* Prints the box content */ function User_specific_content_box_inner() { global $post,$wp_roles; $savedroles = get_post_meta($post-&gt;ID, 'U_S_C_roles',true); //var_dump($savedroles); $savedusers = get_post_meta($post-&gt;ID, 'U_S_C_users',true); //var_dump($savedusers); // Use nonce for verification wp_nonce_field( plugin_basename(__FILE__), 'User_specific_content_box_inner' ); echo __('Select users to show this content to'); echo '&lt;h4&gt;'.__('By User Role:').'&lt;/h4&gt;'; if ( !isset( $wp_roles ) ) $wp_roles = new WP_Roles(); foreach ( $wp_roles-&gt;role_names as $role =&gt; $name ) { echo '&lt;input type="checkbox" name="U_S_C_roles[]" value="'.$name.'"'; if (in_array($name,$savedroles)){ echo ' checked'; } echo '&gt;'.$name.' '; } echo '&lt;h4&gt;'.__('By User Name:').'&lt;/h4&gt;'; $blogusers = get_users('blog_id=1&amp;orderby=nicename'); $usercount = 0; foreach ($blogusers as $user) { echo '&lt;input type="checkbox" name="U_S_C_users[]" value="'.$user-&gt;ID.'"'; if (in_array($user-&gt;ID,$savedusers)){ echo ' checked'; } echo '&gt;'.$user-&gt;display_name.' '; $usercount = $usercount + 1; if ($usercount &gt; 5){ echo '&lt;br/&gt;'; $usercount = 0; } } echo '&lt;h4&gt;'.__('Content Blocked message:').'&lt;/h4&gt;'; echo '&lt;textarea rows="3" cols="70" name="U_S_C_message" id="U_S_C_message"&gt;'.get_post_meta($post-&gt;ID, 'U_S_C_message',true).'&lt;/textarea&gt;&lt;br/&gt;'.__('This message will be shown to anyone who is not on the list above.'); } /* Save Meta Box */ add_action('save_post', 'User_specific_content_box_inner_save'); /* When the post is saved, saves our custom data */ function User_specific_content_box_inner_save( $post_id ) { global $post; // verify this came from the our screen and with proper authorization, // because save_post can be triggered at other times if ( !wp_verify_nonce( $_POST['User_specific_content_box_inner'], plugin_basename(__FILE__) ) ) return $post_id; // verify if this is an auto save routine. // If it is our form has not been submitted, so we dont want to do anything if ( defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE ) return $post_id; // OK, we're authenticated: we need to find and save the data $savedroles = get_post_meta($post_id, 'U_S_C_roles',true); $savedusers = get_post_meta($post_id, 'U_S_C_users',true); if (isset($_POST['U_S_C_roles']) &amp;&amp; !empty($_POST['U_S_C_roles'] )){ foreach ($_POST['U_S_C_roles'] as $role){ $new_roles[] = $role; } update_post_meta($post_id, 'U_S_C_roles', $new_roles); }else{ if (count($savedroles) &gt; 0){ delete_post_meta($post_id, 'U_S_C_roles'); } } if (isset($_POST['U_S_C_users']) &amp;&amp; !empty($_POST['U_S_C_users'])){ foreach ($_POST['U_S_C_users'] as $u){ $new_users[] = $u; } update_post_meta($post_id, 'U_S_C_users', $new_users); }else{ if (count($savedusers) &gt; 0){ delete_post_meta($post_id, 'U_S_C_users'); } } if (isset($_POST['U_S_C_message'])){ update_post_meta($post_id,'U_S_C_message', $_POST['U_S_C_message']); } } add_filter('the_content','User_specific_content_filter'); function User_specific_content_filter($content){ global $post,$current_user; $savedroles = get_post_meta($post-&gt;ID, 'U_S_C_roles',true); $run_check = 0; $savedusers = get_post_meta($post-&gt;ID, 'U_S_C_users',true); if (!count($savedusers) &gt; 0 &amp;&amp; !count($savedroles) &gt; 0 ) return $content; if (isset($savedroles) &amp;&amp; !empty($savedroles)){ foreach ($savedroles as $role){ if (current_user_can($role)) { return $content; exit; } } //failed role check $run_check = 1; } if (isset($savedusers) &amp;&amp; !empty($savedusers)){ get_currentuserinfo(); if (in_array($current_user-&gt;ID,$savedusers)){ return $content; } //failed both checks return get_post_meta($post-&gt;ID, 'U_S_C_message',true); } return $content; } ?&gt; </code>
How do I display a user specific content?
wordpress
This is kind of a stupid question... I scheduled a action to run every hour: <code> if(!wp_next_scheduled('my_hourly_events')) wp_schedule_event(time(), 'hourly', 'my_hourly_events'); add_action('my_hourly_events', 'the_function_to_run'); function the_function_to_run(){ echo 'it works!'; } </code> How can I test if this works without waiting an hour? :) I tried adding <code> wp_clear_scheduled_hook('my_hourly_events'); </code> before this code and adding <code> wp_cron() </code> after, but I don't see my function running... edit: ok, I added a <code> trigger_error() </code> inside my function, checked out the apache error log, and it's there :) So now I'm even more confused: How can the wp-cron run in the background? because apparently that's what happens if I see no output... this doesn't seem to work in a object context; why?
My favorite plugin for that is Core Control which has very nice module for display of what is going in the cron - which events are set up, when are they next firing, etc. On getting your hands dirty level see <code> _get_cron_array() </code> , which returns internal stored data for cron events (top level of keys are timestamps).
How to test wp_cron?
wordpress
How to find out if a particular plugin is enabled in a sub-blog in a multisite blog?
Hm, I am not entirely sure about mechanics here. Usual <code> is_plugin_active() </code> checks if plugin is in <code> active_plugins </code> option. By this logic you could probably retrieve <code> active_plugins </code> of specific blog with <code> get_blog_option() </code> and check it for plugin.
How to Check If A Plugin Is Enabled Through API?
wordpress
I registered custom post type by <code> register_post_type('new_post',$args); </code> So new post url looks like `http://myweb.com/new_post/post_name Can I change _ later _ the part of url from <code> new_post </code> to something else?
It would help if you listed your $args array, but, the portion you are looking for is under 'rewrite'. Here's the way I like to build an $args array for registering a post type: <code> // set up the labels $labels = array( 'name' =&gt; _x('Archived Jobs', 'post type general name'), 'singular_name' =&gt; _x('Archived Job', 'post type singular name'), 'add_new' =&gt; __('Add New'), 'add_new_item' =&gt; __('Add New Job'), 'edit_item' =&gt; __('Edit Job'), 'new_item' =&gt; __('New Job'), 'view_item' =&gt; __('View Job'), 'search_items' =&gt; __('Search Jobs'), 'not_found' =&gt; __('No Jobs found'), 'not_found_in_trash' =&gt; __('No Jobs found in Trash'), 'parent_item_colon' =&gt; '', 'menu_name' =&gt; 'Archives' ); //set up the rewrite rules $rewrite = array( 'slug' =&gt; 'archives' ); //build the arguement array $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'show_in_menu' =&gt; true, 'query_var' =&gt; 'archives', 'rewrite' =&gt; $rewrite, 'capability_type' =&gt; 'post', 'has_archive' =&gt; true, 'hierarchical' =&gt; false, 'menu_position' =&gt; null, 'supports' =&gt; array('title','editor','author','comments') ); register_post_type('archive',$args); </code> The portion of this you are looking for is the $rewrite part, change the slug to whatever you want (url friendly of course, no weird characters or spaces). You may even wish to put slashes in there. In my example, a URL reads: www.website.com/archives/post_name/
can I chage url for register_post_type
wordpress
After installing wordpress and some plugins i am getting this error when i create a sitemap. I realy have no idea what this is and how to solve. Any help would realy be appreciated! <code> Warning: file_put_contents(/home/ugywhzos/domains/mydomain.com/public_html/sitemap.xml) [function.file-put-contents]: failed to open stream: Permission denied in /home/ugywhzos/domains/ipadkopen.biz/public_html/wp-content/plugins/simple-google-sitemap/simple-google-sitemap.php on line 283 </code> And this error after editing a post: <code> Warning: file_put_contents(/home/ugywhzos/domains/mydomain.com/public_html/sitemap.xml) [function.file-put-contents]: failed to open stream: Permission denied in /home/ugywhzos/domains/mydomain.com/public_html/wp-content/plugins/simple-google-sitemap/simple-google-sitemap.php on line 283 Warning: Cannot modify header information - headers already sent by (output started at /home/ugywhzos/domains/mydomain/public_html/wp-content/plugins/simple-google-sitemap/simple-google-sitemap.php:283) in /home/ugywhzos/domains/mydomain.com/public_html/wp-includes/pluggable.php on line 897 </code>
If you already have the files <code> sitemap.xml </code> and (if you have gzip enabled in Simple Google Sitemap) <code> sitemap.xml.gz </code> in the root directory of your WordPress installation, try deleting them and create new empty files with the correct permissions for that plugin, then manually run the sitemap generator. If these files don't exist, try creating the files. Here's how I would do it: Make sure <code> sitemap.xml </code> and <code> sitemap.xml.gz </code> don't exist in the root directory of your WordPress installation. If they do, delete them with <code> rm sitemap.xml </code> and <code> rm sitemap.xml.gz </code> over SSH, or just delete them through your FTP client of choice. Create two new blank instances of these files. Over SSH: <code> touch sitemap.xml </code> and <code> touch sitemap.xml.gz </code> . If you're doing this over FTP (I'll use WinSCP in this example, it's free), navigate to your root WordPress directory, right click, select New --> File and type <code> sitemap.xml </code> and <code> sitemap.xml.gz </code> , respectively. Set the file permissions of these files. I'd try 755 to start, but there may be a recommended value somewhere in this plugin's documentation. Over SSH: <code> chmod 755 sitemap.xml </code> and <code> chmod 755 sitemap.xml.gz </code> . If you're using FTP with WinSCP, right click the files, select Properties, and set the value of Octal to 0755 for each. In the Simple Google Sitemap settings (it's listed as XML-Sitemap in the WordPress settings menu), click the link "rebuild the sitemap" and see if it can now generate the sitemaps. If I was to take a guess, I'd say both of those files don't exist right now and the Simple XML Sitemap plugin doesn't have permissions to create new files on your web server. Please let me know how it goes.
What is this error message?
wordpress
Hi I'm running a site that makes heavy use of a custom taxonomy called 'Games' and using the Simple Term Meta plugin the metadata for these terms. Using pretty much a copy of the code from wordheavy.com it's working fine except for two things: it throws an error on the 'Game' taxonomy page (Warning: Missing argument 2 for game_form_fields() in ommitted /functions.php on line 32) and when you add a 'game' the form doesn't clear. You can find a copy of my code here . I'm not quite where to start (apart from line 32!) so any direction would be appreciated.
The issue at first glance appears to be here.. <code> add_action('game_edit_form_fields', 'game_form_fields'); add_action('game_add_form_fields', 'game_form_fields'); function game_form_fields($tag,$taxonomy) { </code> Your function is expecting 2 vars to be passed from the hook, but your <code> add_action </code> calls default to 1.. Eg, this.. <code> add_action('game_edit_form_fields', 'game_form_fields'); </code> Is equal to this.. <code> add_action('game_edit_form_fields', 'game_form_fields', 10, 1 ); </code> The fourth parameters sets how many arguments your callback function can take, and the default is 1, so that's all your function ever receieves. Updating those <code> add_action </code> calls to the following should fix it.. <code> add_action('game_edit_form_fields', 'game_form_fields', 10, 2 ); </code> Hope that helps.. Follow-up #1 Maybe the hook isn't passing a second variable, instead of the previous change, try update the function line to read.. <code> function game_form_fields( $tag ) { </code> Perhaps that will fix it..
Error in Custom Taxonomy UI
wordpress
I am using the <code> &lt;?php wp_create_user( $username, $password, $email ); ?&gt; </code> function in a contact form to create a subscriber when the user enters infomation on the contact form, thus in the background adding their email address to the database and giving them an account for site access. Does this way of doing it though not mean that if a user sends 3 messages from the contact form they end up with 3 accounts with the same email address, or will it check to see if the email address or user name already exists. Any ideas?
The function <code> wp_create_user </code> calls <code> ‪wp_insert_user‬ </code> which check to see if <code> $username </code> and <code> $email </code> already exists and if so it returns a new WP_Error so you wont have duplicate users in your database and it wont send the new user email more then once, but i'm not sure if that is the best way to do that.
WP Create User - Preventing repeated information
wordpress
This is a common function that adds default text to all posts: <code> add_filter( 'default_content', 'my_editor_content' ); function my_editor_content( $content ) { $content = "default content goes here...."; return $content; } </code> How would this be changed to add the default content only to a post in one category? 4/10/11 Not an exact answer, but a few choices below in my own answer
One possibility is this question/answer here by Jan Fabry, which asks for the default content in the process of creating the new post: stackexchange-url ("Force category choice before creating new post?") I ended up using a Quicktag as a way of easily getting the content into a post, and because the default content happened to be html, it works as good as it can for now. But in the future there turns out to be a way to get default content into a post when that post is saved in that category, that will be good. Quicktags function for functions.php: <code> //Custom Quicktags Function function my_quicktags() { wp_enqueue_script('custom_quicktags', get_bloginfo('template_directory').'/custom-quicktags.js', array('quicktags')); } add_action('admin_print_scripts', 'my_quicktags'); </code> Sample Quicktags code for custom-quicktags.js, which goes in the theme folder: <code> edButtons[edButtons.length] = new edButton('newbutton1' ,'TagButtonName' ,'html, like &lt;div&gt;' ,'and more &lt;/div&gt;' ,'' ); </code>
Default content for a post in one category?
wordpress
I have a page (not a blog post) I need to embed an iframe on (it's to "integrate" an external service's product catalog). I added the iframe code in the raw HTML editor and saved the page. I viewed the page, everything worked. I went back to the editor and switched from raw HTML to the Visual editor tab, added a line of text, and then remembered I needed to add an attribute to the iframe code. So I switched back to the raw HTML tab. When I did this, the post is completely empty. Everything I'd entered in the editor in raw HTML or not was stripped out and the post is blank, like I'd just created it new. I had to roll back to a revision to recover it. So far the solution has been to disable the Visual editor, but I have a non technical partner and that isn't an ideal long term solution. Is there any way to control this behavior of WordPress? I'm using WordPress 3.1.1 Thanks
I've had this code in a custom local plugin for a while. Or you could just stick it in your theme's <code> functions.php </code> : <code> // Allow iframe in TinyMCE function tinymce_add_iframe( $arr = array() ) { $extra = 'iframe[id|class|title|style|align|frameborder|height|longdesc|marginheight|marginwidth|name|scrolling|src|width]'; if ( isset( $arr['extended_valid_elements'] ) ) { // append to existing value $arr['extended_valid_elements'] .= ',' . $extra; } else { // set the value $arr['extended_valid_elements'] = $extra; } return $arr; } add_filter('tiny_mce_before_init','tinymce_add_iframe'); </code> This tells TinyMCE (the visual editor) to allow the <code> iframe </code> tag and all of its attributes.
Switching From HTML to Visual Editor and Back Completely Strips Page Contents
wordpress
I am running Contact 7 form, and looks good for my needs. I have added it to Wordpress , for people to suggest ideas for our product. When users send an idea, they are given a message to say thanks. This message is configurable via the settings for the form in wp-admin Does anyone know how I could get Mr Burns to appear once they have successfully sent an idea? i.e. Make a picture visible, and ideally place the picture to the side of the contact form.
You can customize the "Your message was sent successfully. Thanks." message with-in the the form's edit page at the bottom so add something like this: <code> Your message was sent successfully. Thanks.&lt;/p&gt; &lt;p&gt;&lt;a href="http://pages.sbcglobal.net/bluealbino/SYP/images/mrburns-oh.gif"&gt;&lt;img width="234" height="369" alt="" src="http://pages.sbcglobal.net/bluealbino/SYP/images/mrburns-oh.gif" class="alignnone"&gt;&lt;/a&gt;&lt;/p&gt; </code> Update: Just tried and it works with this exact code.
Contact Form 7 - Show image on successful send?
wordpress
Using WP 3.1.1 as a CMS, using the Boldy theme. Home page is at http://www.dekho.com.au Advantage of using this theme, is that it comes setup with a homepage that has a gallery slider and some homeboxes at the bottom. To get to the blog, I had to dump all my posts into a category called blog. - The themes docco advises to do this] 3 . I can then link to this blog category from the top menu. This then passes me to this URL: http://www.dekho.com.au/?category_name=blog I want to know how to retain the home page provided by Boldy, but have the blog on a separate page with the following URL: dekho.com.au/blog
First, you need to change your Front Page settings: 1) Create a Static Page , called "Blog" (and a slug of "blog") 2) Create another Static Page , to serve as your site Front Page 3) Go to Dashboard -> Settings -> Reading 4) Change "Front Page Displays" from "Your latest posts" to "A static Page (select below)" 5) In the "Front Page" dropdown, select the Static Page that you created to serve as your site Front Page 6) In the "Posts Page" dropdown, select the Static Page "Blog" Next, you need to fix your permalinks: 1) Go to Dashboard -> Settings -> Permalinks 2) Select one of the default options ("Month and Name" is usually good) 3) Save settings, to write the rewrite rules to .htaccess Now dekho.com.au/blog should be displaying your blog posts index
Change URL for Blog?
wordpress
I have 2 custom post types 'bookmarks' and 'snippets' and a shared taxonomy 'tag'. I can generate a list of all terms in the taxonomy with get_terms(), but I can't figure out how to limit the list to the post type. What I'm basically looking for is something like this: <code> get_terms(array('taxonomy' =&gt; 'tag', 'post_type' =&gt; 'snippet')); </code> Is there a way to achieve this? Ideas are greatly appreciated!! Oh, I'm on WP 3.1.1
Here is another way to do something similar, with one SQL query: <code> static public function get_terms_by_post_type( $taxonomies, $post_types ) { global $wpdb; $query = $wpdb-&gt;prepare( "SELECT t.*, COUNT(*) from $wpdb-&gt;terms AS t INNER JOIN $wpdb-&gt;term_taxonomy AS tt ON t.term_id = tt.term_id INNER JOIN $wpdb-&gt;term_relationships AS r ON r.term_taxonomy_id = tt.term_taxonomy_id INNER JOIN $wpdb-&gt;posts AS p ON p.ID = r.object_id WHERE p.post_type IN('".join( "', '", $post_types )."') AND tt.taxonomy IN('".join( "', '", $taxonomies )."') GROUP BY t.term_id"); $results = $wpdb-&gt;get_results( $query ); return $results; } </code>
Get terms by taxonomy AND post_type
wordpress
I was wondering if there was a way to prevent the addition of new categories into a taxonomy, essentially 'locking' the taxonomy. I'm programatically registering a taxonomy and filling it with terms via functions.php and would like it so you cannot add anymore into it. The Vision, REALIZED... Heres how my solution ended up looking, and it works great! THANKS to everyone who helped. Upvotes all over the place up in your face! <code> // some stuff happens before this... $labels = array( 'name' =&gt; _x( 'Attendees', 'taxonomy general name' ), 'singular_name' =&gt; _x( 'Attendee', 'taxonomy singular name' ), 'search_items' =&gt; __( 'Search Attendees' ), 'all_items' =&gt; __( 'All Attendees' ), 'edit_item' =&gt; __( 'Edit Attendee' ), 'update_item' =&gt; __( 'Update Attendee' ), 'add_new_item' =&gt; __( 'Add New Attendee' ), 'new_item_name' =&gt; __( 'New Attendee Name' ), 'menu_name' =&gt; __( 'Attendees' ) ); $rewrite = array( 'slug' =&gt; 'attendee' ); $capabilities = array( 'manage_terms' =&gt; 'nobody', 'edit_terms' =&gt; 'nobody', 'delete_terms' =&gt; 'nobody', 'assign_terms' =&gt; 'nobody' ); $args = array( 'hierarchical' =&gt; true, 'labels' =&gt; $labels, 'show_ui' =&gt; true, 'query_var' =&gt; 'attendee', 'rewrite' =&gt; $rewrite, 'capabilities' =&gt; $capabilities ); register_taxonomy('attendees', 'meetings', $args); } add_action( 'init', 'todo_create_taxonomies', 1); function todo_register_attendees() { $users = get_users(); foreach ( $users as $user ) { wp_insert_term( $user-&gt;display_name, 'attendees', array('description'=&gt; $user-&gt;display_name, 'slug' =&gt; $user-&gt;user_nicename) ); $lockdown[] = $user-&gt;user_nicename; } $terms = get_terms('attendees', array('get' =&gt; 'all') ); foreach ($terms as $term) { if ( !in_array($term-&gt;slug, $lockdown) ) { wp_delete_term( $term-&gt;term_id, 'attendees' ); $message = new WP_Error('force_terms', __('Only Registered Users can be Attendees, ' . $term-&gt;name . ' has been deleted.')); if ( is_wp_error($message) ) { ?&gt; &lt;div id="aphid-error-&lt;?php echo $message-&gt;get_error_code(); ?&gt;" class="error aphid-error"&gt; &lt;p&gt;&lt;strong&gt;&lt;?php echo $message-&gt;get_error_message(); ?&gt;&lt;/strong&gt;&lt;/p&gt; &lt;/div&gt; &lt;?php } } } } add_action( 'admin_notices', 'todo_register_attendees' ); </code>
Categories, Tags & Taxonomies First i want to make this one clear: Everything is a Taxonomy . Tags is a non-hierarchical, Categories a hierarchical and both are built-in taxonomies. Same goes for eg. post formats (aside, chat, etc.). It's the same concept as with post-types (post, page, attachment, nav_menu_item, etc. are all just built in post types). Everything inside one of those Taxonomies is a Term . For eg. (inside post formats) "aside", "quote", "audio". Codex Links <code> register_taxonomy() </code> - allows you to register a taxonomy from ex. inside your <code> functions.php </code> file. <code> wp_insert_term() </code> - allows you to register a term <code> wp_delete_term() </code> - allows you to delete a term <code> get_terms() </code> - allows you to retrieve all terms from a given taxonomy The Concept The following is for your <code> functions.php </code> file. This triggers on every page request. You could improve it - using the Transients API - to trigger on given timestamps (eg. twice daily, hourly, etc.). <code> function wpse14350_cleanup_taxonomy_terms() { // Define your terms inside this array $predefined_terms = array( 'term A' ,'term B' ,'term C' ); // Name your taxonomy here $predefined_taxonomy = 'category'; $all_terms_inside_tax = get_terms( $predefined_taxonomy ,array( 'hide_empty' =&gt; false ,'taxonomy' =&gt; $predefined_taxonomy ) ); foreach ( $all_terms_inside_tax as $term ) { if ( ! in_array( $term-&gt;name, $predefined_terms ) ) wp_delete_term( $term-&gt;term_id, $predefined_taxonomy ); } } add_action( 'init', 'wpse14350_cleanup_taxonomy_terms' ); </code>
Is there a way to 'Lock' a Taxonomy?
wordpress
Just wondering if anyone had tried using any of the structure tags available to post permalinks with custom post types... I'm moving my "listings" posts on a site I manage from a category hack under Posts to their own custom post type, but I'd like to still keep some sort of numeric date reference in the permalink structure. How difficult is that to set up?
Hey goldenapples, rewriting the permalink structure does the trick. I've posted an example on my blog: http://madpress.org/display-date-in-custom-post-type-permalinks/564/ . This process, and other issues related to custom post type permalinks, are described more fully here .
Can /%year%/%monthnum%/%day%/ structure tags be added to custom post type permalinks?
wordpress
I'd like some posts to look different from others. Wordpress let's me easily switch themes for pages, but not posts. Is there a plugin that will let me do that for posts?
http://wordpress.org/extend/plugins/custom-post-template/
How can I change the theme of different posts using a plugin?
wordpress
I'm using CF7 to send some information to my email and everything's working fine, but I need to redirect the users to a different page after the email has been sent, by default the forms are sent to the same page via ajax, I was thinking about setting a hidden field with the page url but since the form submits asynchronously I don't know how to set it in my page template. If the form was submitted normaly I'd do something like: <code> if (isset($_REQUEST['hidden_field_url']) { wp_redirect($_REQUEST['hidden_field_url']); } </code> So is there any way to send the form without ajax? Or maybe do what I need in any other way? Thanks in advance!
Got it, needed to add this to the additional settings option: <code> on_sent_ok: "location = 'http://www.url.com';" </code>
Redirect to another page using contact form 7?
wordpress
I've got a CSV file of new posts which I'll be importing straight into the database. Is it safe to give a GUID of <code> http://domain/?p=[n] </code> where <code> [n] </code> is any number, as long as it's not a duplicate of an existing post?
Short answer: yes The GUID field is meant to represent a globally unique identifier for the post. In WordPress we just happen to use the URL. The GUID field should never be thought of as an actual URL, though ... just an identifier for the post. In reality, the GUID field could contain anything that's unique. But if you have two posts that share the same GUID, you might want to consider bumping one or the other. Importing the CSV of posts into an empty blog and using the WordPress Import/Export mechanism would help. Or setting <code> [n] </code> to be the ID the post will have after import.
Importing Direct to DB - GUID Question
wordpress
My question is simple, I'm using WP_Query to retrieve some custom type posts filtering by a taxonomy using tax_query. Now my problem is I would like to orderby the taxonomy, but from documentation and searching in the web I can't find a solution. The orderby in WP_Query let's you order by a bunch of fields even custom meta fields but it doesn't seem to support taxonomy. Any pointers on the right direction? Thank you all.
No, it is not possible to order by taxonomy, because from a certain type of standpoint, that doesn't actually make much sense. Taxonomies are ways to group things together. So the point of having a taxonomy on posts would really be to have terms in that taxonomy that are shared between posts. If a taxonomy had terms that were only used on one post each, then that would make the taxonomy kind of pointless. And if the terms were shared like they should be, then ordering by it wouldn't produce anything particularly useful. What you should be using in such a situation is the post meta. You can order by post meta, and it's unique to each post. Edit: That said, you can order by taxonomy by making a custom SQL query using a filter, you just can't do it from a unmodified WP_Query: http://scribu.net/wordpress/sortable-taxonomy-columns.html However, if you're having to resort to doing this sort of thing, then your data design structure is wrong in the first place. "Terms" in the taxonomy are not actual "data". The terms themselves have no inherent meaning, they're just labels for the particular grouping that they're describing. If you're treating them as meaningful data, then you have an underlying design flaw. Taxonomies group things by assigning terms to them. That grouping is the whole point of taxonomies, the terms are just pretty faces on the grouping. If you have meaningful metadata to assign to a post, then you should be using the post meta for it instead. And that you can order by, because post meta uses both keys and values to store information. With a taxonomy, you're really only storing keys, with their values being the posts grouped together by that term. Things are easier in the long run if you use the correct approach for it. While I'm not saying that you can't do something strange with taxonomy, you're just making things harder for yourself in the long run by using it wrong.
Using wp_query is it possible to orderby taxonomy?
wordpress
I have a child-theme -> parent-theme setup, where I need to have stylesheet called generated.css loaded in addition to the style.css file added by the active child-theme. The generated.css file is residing in the parent-theme and is being dynamically generated and provided by the parent-theme.. I started out the obvious way, simply adding an import rule to the beginning of the child-themes style.css: <code> /* Get Parent BASE CSS */ @import url('../parent-theme/style.css'); /* Get Parent GENERATED CSS */ @import url('../parent-theme/generated.css'); </code> But this does not work for two reasons. 1) I want to be able to add a cache-busting version number to the file: <code> &lt;link rel='stylesheet' href='http://www.com/wp-content/themes/parent-theme/generated.css?ver=2389642855'&gt; </code> 2) I want the file to be loaded last, after the child themes style.css Is it possible to hook in the loading of this generated.css stylesheet into the head so it is added after the child-theme's style.css using the functions.php of the parent theme? What hook or WP mechanism could I use?
Absolutely! Into functions.php, like you said. I'll call it cache_busting_styles because I like how it sounds. First, you set up the style via wp_enqueue_style, then call it during the action hook wp_print_styles, Also, you'll want to set up a variable and pass it in there as the version number as well: <code> function cache_busting_styles() { //however you set up your version number here $version = 'cachebustingversion'; wp_enqueue_style('cachebusting', get_bloginfo('template_url').'/parent-theme/generated.css', '', $version, 'screen'); } add_action('wp_print_styles', 'cache_busting_styles'); </code> wp_enqueue_style accepts 5 arguments, first the handle, an ID wordpress associates with the stylesheet (must be unique), second the URL of the file, third the other files it depends on (any required files that should be loaded along with this file, I left it null, you may add anything you want, it uses other enqueued stylesheets handles), fourth the version, which it adds to the end of the link URL just like what you are looking for (You may pass whatever you want into this, WordPress puts it's current version in here by default), and finally the media argument for the CSS file (screen, print, all, etc...) I hope this helps! Edit: Just wanted to make clear that using this method should always add this sheet after the default style-sheet, but to make very sure, add_action accepts a third argument which is the priority of the action. A very large number will guarantee it running last, but something like 8 or 12 should do the trick, just in case you need to force the order. <code> add_action('wp_print_styles', 'cache_busting_styles', 12); </code>
add generated stylesheet from parent theme after child-themes style.css
wordpress
I just stepped into the concept of post formats and was wondering why there are two out of 3 functions from the post format "API" offer absolutely the same functionality. Consider the following two concepts (A vs. B): <code> if ( have_posts() ) { while ( have_posts() ) { the_post(); // A) has_post_format if ( has_post_format('format') ) { the_excerpt(); // some special formating } // VERSUS: // B) if ( get_post_format( $GLOBALS['post']-&gt;ID ) == 'format' ) { the_excerpt(); // some special formating } } // endwhile; } // endif; </code> Could someone please explain me why there are those two functions instead only ex. <code> get_post_format </code> ? If you could offer me some examples of situations where the one isn't capable of something the other function can do, I'd be special happy and +1 it.
Edit <code> has_post_format() </code> requires a string, <code> $format </code> , as the first parameter; which means that it can only be used to test for explicit post-format types: <code> if ( has_post_format( $format ) { // Current post has the $format post format; // do something } </code> To determine if a post has any post format, use <code> get_post_format() </code> , which will return <code> false </code> if the current post does not have a post format assigned: <code> if ( false != get_post_format() ) { // Current post has a post format; // do something } </code> Note that "standard" isn't an actual post-format, but is rather a placeholder term for posts that do not have a post format assigned. Internally, WordPress returns <code> false </code> rather than <code> post-format-standard </code> , so, to query for the "standard" post-format type, you would just use <code> if ( false == get_post_format() ) </code> . Original <code> has_post_format() </code> returns a BOOLEAN value, which is useful for conditionals, e.g.: <code> if ( ! has_post_format() ) { // I'm a standard-format post; do something } </code> or <code> if ( has_post_format( array( 'gallery', 'image' ) ) { // I'm a gallery or image format post; do something } </code> <code> get_post_format() </code> returns the string value of the current post format type, which is useful in several ways. One of the most powerful is to call different template part files based on post format, e.g.: <code> get_template_part( 'entry', get_post_format() ) </code> Which will include, e.g. "entry-aside.php" for an aside format, or "entry.php" for a standard format.
has_post_format() vs. get_post_format()
wordpress
I want to be able to create custom login errors. For instance if a user visits a restricted area without being logged in then I am redirecting to <code> wp-login.php?ref=access </code> and I would like to output <code> Restricted area, please login to continue. </code> or something similar. Any idea how to do this. I found that there are filters for <code> login_errors </code> but I can't find anywhere else in the code this comes up, except in the login page itself. Lastly, I really don't want to have to change any of the core files to do this either. I've spent a lot of time and energy trying to make sure that the wordpress core is completely untouched so that I can upgrade it. Anyone have any ideas? Thank you Tom
From quick look at the login screen code (ouch): <code> add_action('login_head','ref_access'); function ref_access() { global $error; if( !empty($_GET['ref']) &amp;&amp; 'access' == $_GET['ref'] ) $error = 'Restricted area, please login to continue.'; } </code>
Creating custom login errors
wordpress
I have lots of posts in my website . I have used <code> default pagination </code> function for paging the post list in homepage . But I wanted to implement <code> lazy loading </code> instead of pagination just like in twitter . I don't have any idea about it's implementation in Wordpress . Please help me with this.
Take a look at Infinite Scroll plugin which Automatically append the next page of posts (via AJAX) to your page when a user scrolls to the bottom.
Implementing lazy loading in homepage posts instead of pagination
wordpress
I have added a custom user role of super_poster, basically they make 20 posts and once they hit $postlimit get auto-moved back down to contributer level, the moving down and post counting works ok, my problem is that the wp system adds the user into "none" instead of into contributer role <code> if ($count_posts &gt;= $postlimit) { $current_user-&gt;remove_role( 'super_poster' ); $current_user-&gt;add_role( 'contributer' ); } </code> contributer is set for new user default on sign-up, so the situation i have is in wp-admin user edit page i can see the newly moved (into contributer from super poster) has still got "additional capabilities of contributer" however user role dropdown says --No role for this site -- wp-admin users page shows the super_poster as in user group "none" what gives?
You might want to use <code> WP_User::set_role( 'contributor' ) </code> instead. It unsets all current roles and sets the new one (the argument) too. So the above would be <code> if ($count_posts &gt;= $postlimit) { $current_user-&gt;set_role( 'contributor' ); } </code>
User Roles Not Sticking
wordpress
I've added a custom post type, which is working great; I've also added two metaboxes, which appear to work well, but the content in them always disappears after a few minutes. If anyone could help out on this I would be eternally grateful, S. //meta box code// <code> add_action( 'admin_init', 'add_custom_metabox' ); add_action( 'save_post', 'save_custom_details' ); function add_custom_metabox() { add_meta_box( 'custom-metabox', __( 'Product Description &amp;amp; Ingredients' ), 'descr_custom_metabox', 'sorbets', 'normal', 'low' ); } function descr_custom_metabox() { global $post; $proddescr = get_post_meta( $post-&gt;ID, 'proddescr', true ); $ingredients = get_post_meta( $post-&gt;ID, 'ingredients', true ); ?&gt; &lt;p&gt;&lt;label for="proddescr"&gt;Product Description:&lt;br /&gt; &lt;textarea id="proddescr" name="proddescr" style="margin:0;height:7em;width:98%;" cols="45" rows="4"&gt;&lt;?php if( $proddescr ) { echo $proddescr; } ?&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;/p&gt; &lt;p&gt;&lt;label for="ingredients"&gt;Ingredients:&lt;br /&gt; &lt;textarea id="ingredients" name="ingredients" style="margin:0;height:7em;width:98%;" cols="45" rows="4"&gt;&lt;?php if( $ingredients ) { echo $ingredients; } ?&gt;&lt;/textarea&gt;&lt;/label&gt;&lt;/p&gt; &lt;?php } function save_custom_details( $post_ID ) { global $post; if( $_POST ) { update_post_meta( $post-&gt;ID, 'proddescr', $_POST['proddescr'] ); update_post_meta( $post-&gt;ID, 'ingredients', $_POST['ingredients'] ); } } function get_descr_ingred_box() { global $post; $proddescr = get_post_meta( $post-&gt;ID, 'proddescr', true ); $ingredients = get_post_meta( $post-&gt;ID, 'ingredients', true ); return array( $proddescr, $ingredients ); } </code>
You need to check for <code> autosave </code> and avoid that , also check if you are in the right post type as <code> save_post </code> works on all posts: <code> function save_custom_details( $post_id ) { global $post; //skip auto save if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) { return $post_id; } //check for you post type only if( $post-&gt;post_type == "sorbets" ) { if( isset($_POST['proddescr']) ) { update_post_meta( $post-&gt;ID, 'proddescr', $_POST['proddescr'] );} if( isset($_POST['ingredients']) ) { update_post_meta( $post-&gt;ID, 'ingredients', $_POST['ingredients'] );} } } </code> WOW you guys are fast :)
Custom Post Type Metabox - Not Saving
wordpress
A few weeks ago I created a new WordPress blog. I bought a new domain name for it, and I have not published/linked to the blog yet (because I wanted to get a few articles up first, I only have 2 so far). I have gotten about 10 spam comments already. I am confused how the spammers could be finding me?
What are your privacy settings? Go to Dashboard -> Settings -> Privacy If it is set to I would like my site to be visible to everyone, including search engines (like Google, Bing, Technorati) and archivers , then your site is actively being crawled/indexed by search engines, and thus visible to spammers. If it is set to I would like to block search engines, but allow normal visitors , and you're still getting spam comments, then that would be a bit more surprising. In that case, you might want to look at disabling comments, or looking at some anti-spam solutions.
How is my non-published blog getting so much spam?
wordpress
This is such a simple question, but I'm having trouble getting the answer. Is it possible to have a blog at WordPress.com and not have the WordPress.com banner (shown below)? Is it simply a matter of purchasing the "master of your domain" premium feature ? Or must I host my own WordPress.org installation (which is not a big deal)?
The ribbon is merely a way to quickly administer your site. It's actually there for self-hosted WordPress.org setups, too (though you can turn it off with a filter). But think for a few minutes about why you want it hidden. Do you want it hidden from just you because you don't need it? Do you want it hidden from you readers so they aren't reminded you're hosted by WordPress.com? Does it not fit with the aesthetic of your site? If you want to hide it from your readers, keep in mind that " The only people who can see it are those who also have WordPress.com blogs and are logged into WordPress.com when they visit your blog. " If you want it hidden from just you or if it doesn't really fit with your site, you would be best suited migrating to a self-hosted installation. You can get on a shared host for about $6/month and can get a custom domain for about $8/year depending on the host. Migrating is pretty easy, and then you'd have full control over the presentation of your site without needing to buy other premium add-ons.
Removing the WordPress.com ribbon
wordpress
can't seem to get this but how can i load info in a child's page from its parent? ie, i'm looking at an attachment and i can get the parents ID easy enough but not sure how to get the parents title, excerpt etc. <code> // attachment content above here then want to get and show some parents' content echo $parent = get_post_field('post_parent', $id); echo the_title(); // this still shows the childs title... </code> any help appreciated! Dan
You can try <code> get_post($post-&gt;post_parent) </code> or <code> get_page($post-&gt;post_parent) </code> so if you do: <code> $parent = get_post($post-&gt;post_parent); </code> You can get the title like this: <code> $parent-&gt;post_title; </code> And anything you want, you can <code> var_dump($parent) </code> to see all the post info you can use.
get parent fields title, content excerpt etc
wordpress
I could not find a thread discussing this, so starting this one. I am currently working on a rather elaborate theme for 3.1+, and by elaborate I mean that in addition to styling and regular front-end functionality, I am including plugins at the core of the theme, both for back-end and front-end. So, to keep this a little more organized, I split this into three questions: Is integrating plugins a common practice? What are the implications/complications in regards to auto-updating the theme/plugins? What would be the most optimized way of including each plugin without breaking pre-existing functionality?
1) Is integrating plugins a common practice? Not really. Normally you got a theme that offers a base functionality. You then only extend the theme with plugins for special purpose like twitter stuff, event calendars, etc. Imo it makes sense. I'm currently working on an extremly slim theme that has some plugins (OOP approach) that get delivered as plugins, but are not bundled. These plugins offer template tags for pagination, breadcrumbs, ... even the loop with post formats. I like the idea of only offering functionality if the user really wants it. For ex. the comment system is rarely needed if you use WP as a CMS for a buisness homepage, so why should the theme offer this? Another pro for this approach: You just disable the plugin and exchange the template tags with custom stuff if you don't need it. Important with this approach is: Don't place those template tags directly. Use hooks &amp; filters wrapped up in functions, so your theme doesn't crash because of undefined function calls if you disabled a plugin. 2) What are the implications/complications in regards to auto-updating the theme/plugins? This is something i'm currently questioning myself. I thought about a massive routine that checks for updates on both the theme and the plugins, but overall: It makes no sense. Imo it's even better if you just use the builtin update system (or use some custom class if you're not hosting at the official repo). Why: You only update what really needs to get updated. This saves some time and energy, so i'd even call it the "greener" way to go. 3) What would be the most optimized way of including each plugin without breaking pre-existing functionality? What exactly is in your case pre-existing functionality? Function Names WordPress got around 2.500 functions that get read on a request. So questioning <code> if ( function_exists('whatever') ) </code> is never a good idea. Better use unique names. @Jan Fabry had a good idea: He prefixes all his answer functions over here with <code> wpse </code> and the number of the Q - example: <code> wpse14277_function_name() </code> . A 4 or 5 digit number combined with alphas will likely stay unique. Imagine that you got 50 custom functions in your theme and are questioning them against 2.500 per Request (you can do the math yourself) - that's not performant. Edit: If you just want to know if a plugin is active, then use the <code> is_plugin_active() </code> conditional tag.
Integrating plugins in themes
wordpress
I can see <code> validate_user() </code> calls <code> sanitize_user() </code> with strict argument as true, which means uppercase letters are not allowed too. In source code, I found this comment <code> // If strict, reduce to ASCII for max portability. if ( $strict ) $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username ); </code> I would like to know how does this affect portability?
Uppercase characters are not blocked in usernames on single site setups. Uppercase characters ARE blocked in usernames on multisite setups. The wpmu_validate_user_signup function forces lowercase a-z and numbers 0-9 only.
Reason for Lowercase usernames
wordpress
I'm in the middle of moving to WordPress from another CMS. I definitely have to keep the links intact, which are like this: example.com (Redirects to /blog) example.com/blog (The blog, displaying all the articles) example.com/blog/article (A specific article) example.com/about (A static page) example.com/portfolio (Another static page) Right now, however, only the static pages work as expected. I cannot figure out how to create a new custom "blog" page and display the blog posts on that, and how to remove the front page alltogether, making it redirect to the blog instead. Furthermore, I'm using the zBench theme, which always displays the "Home" tab which will lead to the front page. Instead, I want my tabs like this: "Blog", "About", "Portfolio" - no "Home". A similar question has been asked before: stackexchange-url ("How to get the list of posts in a static page other than front page?") But this seems like a hack, and not really the same problem I have. I do want to display the blog on the front page, I just want to rename it in both URL and on the tab.
Setting your permalinks as <code> /blog/%postname%/ </code> will solve your structure problem. In your theme, drop in a <code> home.php </code> file which redirects the user to /blog/ and you can set the blog to appear on a page with slug blog as the blog in your Settings > Reading Regarding the menu, you would have to take a look how your theme works. If its using WP 3.0 menus, then you can easily change them in the dashboard itself else if its calling <code> wp_list_pages() </code> , then you need to use the exclude parameter of the function to exclude a particular page from showing. http://codex.wordpress.org/Function_Reference/wp_list_pages
How to display blog posts on a dedicated page?
wordpress
(First of all, sorry for bad english) If there are people here using wordpress as cms, you probably realize that you dont need comment system that much. Esspecially custom post types like products need a contact form system that saves coming input. What i am dreaming but cant coding: Changing comment system for custom post types. Let me explain on an example: Lets say we have a custom post type thats using for product list. We dont need/want customer comments on this product but we want customers send us what they are thinking on this product. So they will use this "custom comment type" system and sending us a comment but this comment is not publishing on website and in admin panel, when we reply to comment, wordpress will send that reply as e-mail. So we can see all new contact form inputs about this product in a list as archieved in wordpress comment table and we can reply them from admin panel. When product is updated or a special discount or something, we will have a list of customers that previously asked a question about it so we can contact them again about new updates. In background, as performance, product custom post type not need to load comments so this will reduce database queries. What do you think about it? Possible?
I also (ab?)use comments for "private" replies to posts, like product inquiries, suggestions, answers to contests, ... The advantage is that they are stored in the database and displayed in the interface without extra code from me (sometimes I add a filter to improve the formatting). Spam filtering and e-mail notifications are easy extras. I think it is possible to create a custom comment type framework on top of the current system, thus as a plugin without internal changes. Maybe, if I ever find the time, I'll experiment with that...
Custom comment type maybe?
wordpress
Okay, I think I'm pretty close. I have the following going on: <code> $cat_id = get_cat_id('library'); wp_dropdown_categories('hierarchical=1&amp;parent=$cat_id'); </code> However, it doesn't work with $cat_id in there. It does work when I put the category's ID number in there (which I got when I echoed $cat_id), but obviously that presents a problem when I install the site on the real server. What should I try? Thanks!
If you change your single quote marks in to double quote marks it should work : <code> $cat_id = get_cat_id('library'); wp_dropdown_categories("hierarchical=1&amp;parent=$cat_id"); </code> but if you really want to make it more flexible you can phrase your arguments as an array: <code> $args = array( 'hierarchical' =&gt; 1, 'parent' =&gt; get_cat_id('library')); wp_dropdown_categories($args); </code> and if you want to make it even more flexible to get the current category's children you can use <code> get_query_var('cat'); </code> assuming that you are in your category.php file, so: <code> $args = array( 'hierarchical' =&gt; 1, 'parent' =&gt; get_query_var('cat')); wp_dropdown_categories($args); </code>
How do I list only children of a specific category in a drop-down?
wordpress
I'm setting up a WordPress site that has Flash puzzles embedded in the pages. (My site will have pages instead of posts). Each week I'll add a new puzzle to the site's Home page. When the site loads you'll see the newest puzzle. Older puzzles would be accessed through a dropdown menu. My question is how should I design the permalink structure? Under Reading Settings, I plan to set the Front Page to static. And select the latest puzzle as the front page. The problem is that if someone bookmarks the Home page, they'll get the latest puzzle. Let's say this week's puzzle (on the Home page) is called "Astronomy". The path to the Home page would be, for example, www.mysite.com. Imagine that someone is a Carl Sagan nerd and wants to link to the Astronomy puzzle. After the week is over, a new puzzle would be on the front page. The "Astronomy" puzzle's path would now be www.mysite.com/astronomy and would be accessed through the dropdown menu. Is there a way to avoid this problem? (Other than a blurb on the Home page with a link to the puzzle)? Sorry, if this is an idiotic question. But, maybe someone has a good solution. Thank you! -Laxmidi
I am not sure why you need pages over posts here. Using posts gives you ready made index home page, slugs and pretty permalinks give you link structure you want. You can just add some blurb on home page that says "bookmark this puzzle" with direct permalink.
Front Page Settings
wordpress
Summary: How can I get the name and the permalink of the object returned by wp_get_object_terms() ? Detailled: I created a custom post type called "ge_zielgruppe" and a taxonomy called "ge_zielgruppe_taxonomy". The latter can be attached to posts and to "ge_zielgruppe" post types. On the single page of "ge_zielgruppe" I want to show the last few posts tagged with the same "ge_zielgruppe_taxonomy". I achieved this with <code> &lt;?php $theZielgruppe = wp_get_object_terms($post-&gt;ID, 'ge_zielgruppe_taxonomy'); $zielgruppe = new WP_Query(array('ge_zielgruppe_taxonomy' =&gt; $theZielgruppe-&gt;slug)); $zielgruppe-&gt;query('showposts=10'); if ($zielgruppe-&gt;have_posts()) : while ($zielgruppe-&gt;have_posts()) : $zielgruppe-&gt;the_post(); ?&gt; &lt;&lt;--archive-stuff--&gt;&gt; &lt;?php endwhile; endif; ?&gt; </code> This part works (however, I don't know if it's elegant). Now I'd like to put a link right after these 10 posts, looking like this <code> &lt;a href="&lt;&lt;--permalink to archive of 'ge_zielgruppe_taxonomy'--&gt;&gt;" rel="bookmark" title="More posts for &lt;&lt;--Name of 'ge_zielgruppe_taxonomy'--&gt;&gt;; "&gt;More posts for &lt;&lt;--Name of 'ge_zielgruppe_taxonomy'--&gt;&gt;&lt;/a&gt; </code> So how do I get <code> &lt;&lt;--permalink to archive of 'ge_zielgruppe_taxonomy'--&gt;&gt; </code> and <code> &lt;&lt;--Name of 'ge_zielgruppe_taxonomy'--&gt;&gt; </code>
To fetch the archive url for that taxonomy term, use something like this (I'm using your naming conventions above, and assuming that <code> $theZielgruppe </code> is a term object. <code> $url = get_term_link( $theZielgruppe, 'ge_zielgruppe_taxonomy' ); </code> To get the name, just use <code> $theZielgruppe-&gt;name </code> Is that what you're looking for? EDIT The link above would then look like this: <code> &lt;a href="&lt;?php echo get_term_link( $theZielgruppe, 'ge_zielgruppe_taxonomy' ); ?&gt;" rel="bookmark" title="More posts for &lt;?php echo $theZielgruppe-&gt;name; ?&gt;; "&gt;More posts for &lt;?php echo $theZielgruppe-&gt;name; ?&gt;&lt;/a&gt; </code> EDIT 2 <code> wp_get_object_terms() </code> returns an array of terms. If you changed each use of <code> $theZielgruppe </code> to <code> $theZielgruppe[0] </code> to use the first term that the current <code> ge_zielgruppe </code> relates to. A warning, though: <code> wp_get_object_terms() </code> can return as either an empty array or as a <code> WP_Error </code> . You might want to change your code to check for that: <code> &lt;?php $theZielgruppe = wp_get_object_terms($post-&gt;ID, 'ge_zielgruppe_taxonomy'); if( !empty( $theZielgruppe ) &amp;&amp; !is_wp_error( $theZielgruppe ) ): $theZielgruppe = $theZielgruppe[0]; $zielgruppe = new WP_Query(array('ge_zielgruppe_taxonomy' =&gt; $theZielgruppe-&gt;slug)); $zielgruppe-&gt;query('showposts=10'); if ($zielgruppe-&gt;have_posts()) : while ($zielgruppe-&gt;have_posts()) : $zielgruppe-&gt;the_post(); ?&gt; &lt;&lt;--archive-stuff--&gt;&gt; &lt;?php endwhile; endif; ?&gt; &lt;a href="&lt;?php echo get_term_link( $theZielgruppe, 'ge_zielgruppe_taxonomy' ); ?&gt;" rel="bookmark" title="More posts for &lt;?php echo $theZielgruppe-&gt;name; ?&gt;; "&gt;More posts for &lt;?php echo $theZielgruppe-&gt;name; ?&gt;&lt;/a&gt; &lt;?php endif; ?&gt; </code>
Proper use of wp_get_object_terms
wordpress
Why is it? I tried the same query in the console and it returned multiple rows. Here's the query: <code> $this-&gt;wpdb-&gt;get_row("SELECT * FROM ".$this-&gt;wpdb-&gt;users." WHERE status = 'active'", ARRAY_A); </code> It keeps returning the same single row when there are several active users. Am I missing something?
Indeed, use <code> get_row() </code> only when you expect to get one result, else you can use <code> get_results() </code>
$wpdb-> get_row() only returns a single row?
wordpress
I've got an <code> if ($comment-&gt;user_id) </code> block to pick an default admin comment gravatar (different than a non-user's). But I'd still like this gravatar to be used if a user comments using their registered email, even if they comment while not logged in. What is the best way to test for this? EDIT I'm already using <code> if ($comment-&gt;user_id){ //comment by registered user $avatar = '/images/bird_comments_big.png'; }else{ //comment by none registered user $avatar = '/images/bird_comments_pink.png'; } </code> with <code> &lt;div&gt;&lt;?php echo get_avatar($comment, 70, get_bloginfo('template_url').$avatar); ?&gt;&lt;/div&gt; </code> If the user is logged in a makes a comments, the if statement is indeed fulfilled. However, if the user uses their registered email (i.e. tied to their login in WP) without bring logged in, <code> user_id </code> is not present, and the icon for the unregistered user appears. <code> user_id </code> is only stored if the user is logged in. I also want to test if the email given matches a registered user, regardless if they are logged-in or not.
<code> if ($comment-&gt;user_id || email_exists($comment-&gt;comment_author_email)){ //comment by registered user $avatar = '/images/registered_user.png'; }else{ //comment by none registered user $avatar = '/images/non_registered_user.png'; } </code> with <code> &lt;div&gt;&lt;?php echo get_avatar($comment, 70, get_bloginfo('template_url').$avatar); ?&gt;&lt;/div&gt; </code> Seems about as succinct a way I can figure.
Best way to tell if a comment is from a user?
wordpress
I am setting up a site where there will be multiple users as Author, the owner doesn't want the authors to be able to view each others posts, since there are some meta fields with information he'd rather not have shared between the authors. Is there a way to remove the ability to view other authors posts? Thanks, Chuck To clarify a bit more, this is for the admin side, at the top underneath Posts, there are links for mine, all, and published. I only want Authors to see "mine".
If you want to prevent a user with the "Author" role to view other users' posts in the overview screen (they won't be able to view the details anyway), you can add an extra filter on the author: <code> add_action( 'load-edit.php', 'wpse14230_load_edit' ); function wpse14230_load_edit() { add_action( 'request', 'wpse14230_request' ); } function wpse14230_request( $query_vars ) { if ( ! current_user_can( $GLOBALS['post_type_object']-&gt;cap-&gt;edit_others_posts ) ) { $query_vars['author'] = get_current_user_id(); } return $query_vars; } </code> The little links above the post table ("Mine", "All", "Drafts") are less useful now, you can also remove them: <code> add_filter( 'views_edit-post', 'wpse14230_views_edit_post' ); function wpse14230_views_edit_post( $views ) { return array(); } </code>
Prevent Authors from viewing each others Posts
wordpress
I am trying to figure out how to add a custom field to display an image instead of a title on the stats_get_csv from Wordpress stats. <code> &lt;?php if ( function_exists('stats_get_csv') &amp;&amp; $top_posts = stats_get_csv('postviews', 'days=2&amp;limit=6') ) : ?&gt; &lt;ol&gt; &lt;?php foreach ( $top_posts as $p ) : ?&gt; &lt;li&gt;&lt;a href="&lt;?php echo $p['post_permalink']; ?&gt;"&gt;&lt;?php echo $p['post_title']; ?&gt;&lt;/a&gt;&lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ol&gt; &lt;?php endif; ?&gt; </code> Update <code> &lt;?php if ( function_exists('stats_get_csv') &amp;&amp; $top_posts = stats_get_csv('postviews', 'days=2&amp;limit=6') ) : ?&gt; &lt;?php if ( get_post_meta($post-&gt;ID, 'Image', true) ) : ?&gt; &lt;ol&gt; &lt;?php foreach ( $top_posts as $p ) : ?&gt; &lt;li&gt; &lt;img class="thumb" src="&lt;?php echo get_post_meta($post-&gt;ID, 'Image', true) ?&gt;" alt="&lt;?php the_title(); ?&gt;" height='100' width='100' /&gt; &lt;/li&gt; &lt;?php endforeach; ?&gt; &lt;/ol&gt; &lt;?php endif; ?&gt; &lt;?php endif; ?&gt; </code>
Return of that function should have post ID, right? Then it's straight <code> get_post_meta() </code> using that ID and name of your field. Update In your second code snippet <code> $post </code> is global variable, <code> $post-&gt;ID </code> is not tied in any way with return of <code> stats_get_csv() </code> function. You need something like from first example ( <code> $p['post_permalink'] </code> ), just figure out if there is a field with ID. Also you don't need wrapping <code> if ( get_post_meta($post-&gt;ID, 'Image', true) ) </code> that would make sense only for single current post, not for loop of posts.
Wordpress.com Stats stats_get_csv with custom field?
wordpress
I found a great piece of code here that returns the ID's of users by role. What I would like to do is modify it so it only returns the ID's of the users who have at least one post. I have tried to <code> INNER JOIN </code> the <code> $wpdb-&gt;posts </code> table and feel that I did that correctly but not sure. Here is what I have so far: <code> function getUsersByRole( $roles ) { global $wpdb; if ( ! is_array( $roles ) ) { $roles = explode( ",", $roles ); array_walk( $roles, 'trim' ); } $sql = ' SELECT ID, display_name FROM ' . $wpdb-&gt;users . ' INNER JOIN ' . $wpdb-&gt;usermeta . ' ON ' . $wpdb-&gt;users . '.ID=' . $wpdb-&gt;usermeta . '.user_id AND INNER JOIN '. $wpdb-&gt;posts .' ON ' .$wpdb-&gt;users . '.ID=' . $wpdb-&gt;posts . '.post_author WHERE ' . $wpdb-&gt;usermeta . '.meta_key = '' . $wpdb-&gt;prefix . 'capabilities' AND ( '; $i = 1; foreach ( $roles as $role ) { $sql .= ' ' . $wpdb-&gt;usermeta . '.meta_value LIKE '%"' . $role . '"%' '; if ( $i &lt; count( $roles ) ) $sql .= ' OR '; $i++; } $sql .= ' ) '; $sql .= ' ORDER BY display_name '; $userIDs = $wpdb-&gt;get_col( $sql ); return $userIDs; } </code> Which the SQL query outputs SELECT ID, display_name FROM wp_users INNER JOIN wp_usermeta ON wp_users.ID=ba_usermeta.user_id AND INNER JOIN wp_posts ON wp_users.ID=ba_posts.post_author WHERE wp_usermeta.meta_key = 'wp_capabilities' AND ( wp_usermeta.meta_value LIKE '%"author"%' OR wp_usermeta.meta_value LIKE '%"editor"%' ) ORDER BY display_name I've never used <code> INNER JOIN </code> (or <code> JOIN </code> ) so I could doing it wrong. I also think I need to do a count or something to make sure I get a result. Any help would be awesome EDIT: Here is the full working function as PHP for anyone who finds this later <code> function getUsersByRole( $roles ) { global $wpdb; if ( ! is_array( $roles ) ) { $roles = explode( ",", $roles ); array_walk( $roles, 'trim' ); } $sql = 'SELECT ID, display_name FROM '. $wpdb-&gt;users .' JOIN '. $wpdb-&gt;usermeta.' ON ('.$wpdb-&gt;users.'.ID = '.$wpdb-&gt;usermeta.'.user_id AND '.$wpdb-&gt;usermeta.'.meta_key = ''.$wpdb-&gt;prefix.'capabilities') WHERE ID IN (SELECT post_author FROM ' .$wpdb-&gt;posts.') AND('; $i = 1; foreach ( $roles as $role ) { $sql .= ' ' . $wpdb-&gt;usermeta . '.meta_value LIKE '%"' . $role . '"%' '; if ( $i &lt; count( $roles ) ) $sql .= ' OR '; $i++; } $sql .= ' ) '; $sql .= ' ORDER BY display_name '; $userIDs = $wpdb-&gt;get_col( $sql ); return $userIDs; } </code>
Instead of a <code> JOIN </code> , you can use a <code> IN </code> with a subquery, to prevent duplicate results because of the join: <code> SELECT ID, display_name FROM wp_users WHERE ID IN (SELECT post_author FROM wp_posts) </code> This will not look at capabilities. If you also want that you can add them like a join, but move the <code> meta_key </code> clause in the join, also to prevent duplicate results: <code> SELECT ID, display_name FROM wp_users JOIN wp_usermeta ON (wp_users.ID = wp_usermeta.user_id AND wp_usermeta.meta_key = 'wp_capabilities') WHERE ID IN (SELECT post_author FROM wp_posts) AND (wp_usermeta.meta_value LIKE '%"author"%' OR wp_usermeta.meta_value LIKE '%"editor"%' ) </code> Up to you to convert this back to PHP! Sidenote: Is the <code> wp_ </code> in <code> wp_capabilities </code> dependent on the database prefix, or is it always <code> wp_ </code> , even if your table names start with another prefix?
Return ID of authors who have at least one post
wordpress
I have run into an issue trying to use the sidebar args (before_widget,after widget,after_widget,before_widget) as theme style friendly parameters for the function wp_list_bookmarks, that is that the wp_list_bookmarks output will look just as the one inside WP_Widget_Links. I almost copied verbatim the code of the links widget but when trying to reuse the only one sidebar args (via the global $wp_registered_sidebars) I get some css classes for the widget container that dont show up using the WP_Widget_Links. For example the following dump of a sidebar args: <code> 'name' =&gt; 'Sidebar 1' 'id' =&gt; 'sidebar-1' 'before_widget' =&gt; '&lt;li id="%1$s" class="widget %2$s"&gt;' 'after_widget' =&gt; '&lt;/li&gt;' 'before_title' =&gt; '&lt;h2 class="widgettitle"&gt;' 'after_title' =&gt; '&lt;/h2&gt;' </code> By reading the wp code I assumed that is safe to change %1$s, %2$s for %id, %class resp, and then once the wp_list_bookmarks gets executed I should end with before_widget looking like <code> &lt;li id="linkcat-" class="widget linkcat"&gt; </code> . But after comparing to the output of the links widget the widget css classname is missing, and the output of my code looks a bit odd in the page. This is the code where I use the function, which gets called as a filter to sidebars_widgets: <code> function my_sidebars_widgets($sidebar_widgets) { global $wpdb, $wp_registered_sidebars; static $hits; if(++$hits == 2) { $sidebar = array_values($wp_registered_sidebars); $before_title = $sidebar[0]['before_title']; $after_title = $sidebar[0]['after_title']; $before_widget = $sidebar[0]['before_widget']; $after_widget = $sidebar[0]['after_widget']; $before_widget = str_replace('%2$s','%class',$before_widget); $before_widget = str_replace('%1$s','%id',$before_widget); wp_list_bookmarks(apply_filters('widget_links_args',array( 'title_before' =&gt; $before_title, 'title_after' =&gt; $after_title, 'category_before' =&gt; $before_widget, 'category_after' =&gt; $after_widget, 'hide_invisible' =&gt; true,'title_li' =&gt; 'Links', 'categorize' =&gt; 0,'inquiry' =&gt; true ))); } return $sidebar_widgets; } </code> Did you have any clue of what Im missing here? I keep trying to get clear how WP feed widgets args but no explanation so far while reading the code. thanks in advance for any on your considerations.
After a few <code> var_dumps </code> I know this: 1) When wp_list_bookmarks is called whithin WP_Widget_Links-> widget The <code> 'class' </code> parameter is ignored because the <code> 'category_before' </code> parameter doesn't have the <code> %class </code> wildcard. Instead <code> 'category_before' </code> will look as if 'class' where <code> 'widget_links' </code> . This is how the function dynamic_sidebar set the $before_widget parameters for the widget once it gets called. Of course this can be altered by filters like <code> 'widget_links_args' </code> or <code> 'dynamic_sidebar_params' </code> . 2) On many themes in order to present default widgets the wp_list_bookmarks is called but with zero parameters then the default values are used as defined in bookmark-template.php: <code> ('class' =&gt; 'linkcat','category_before' =&gt; '&lt;li id="%id" class="%class"&gt;') </code> and this happen even when the sidebar is registered using: <code> ('before_widget' =&gt; '&lt;li id="%1$s" class="widget %2$s"&gt;') </code> which can let to a little inconsistence because WP_Widget_Links <code> 'category_before' </code> parameter is initially borrow from sidebar <code> 'before_widget' </code> parameter.
Problems with the sidebar args and wp_list_bookmarks
wordpress
my situation: I have a frontpage which filters 12 thumbnails out of 24 (each thumbnail represents a post's featured image), and displays them. The user has the ability to hide whichever post he wants from the frontpage. Let's say the user chooses to hide thumb #4, that means we now have thumb 1,2,3,5,6,7,8,9,10,11,12. That is, we have 11 thumbnails. So we are missing the last 'thumbnail space', which should be filled with the upcoming post; in this case, thumb #13. In short, the frontpage should query the posts so that when one or more thumbnails are hidden - resulting in one or more blank spaces - it automatically 'refills' the blank spaces by pushing in the upcoming thumbnails. My front-page has this query: <code> &lt;?php global $wp_query; // First row of images if(!empty($options['home_thumbs'])) { $page_items = $options['home_thumbs']; } else { $page_items = 18; } $portCat = get_category_id($options['portfoliocat']); // get the desired sort order of portfolio items if($options['homepage_sort'] == 'DESC') { $order = 'DESC'; } else { $order = 'ASC'; } $hideFromHome = get_post_meta($wp_query-&gt;post-&gt;ID, 'pr_hidehome', true); query_posts('posts_per_page=' . $page_items . '&amp;orderby=title&amp;order=' . $order . '&amp;cat=' . $portCat . '&amp;meta_key=' . $hideFromHome .'&amp;meta_value=' . true); // arrays to detect first and last columns $firsts = array(6,12,18,24,30,36); $lasts = array(5,11,17,23,29,35); if (have_posts()) : $count = 0; echo '&lt;ul class="imageRows rowOne"&gt;'; while (have_posts()) : the_post(); $custom_meta = get_post_custom($post-&gt;ID); if (has_post_thumbnail() &amp;&amp; $custom_meta['pr_hidehome'][0] != true) { ?&gt; &lt;li class="&lt;?php if (in_array($count, $firsts) ) { echo ' columnFirst'; } if (in_array($count, $lasts) ) { echo ' columnLast'; } ?&gt;"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title_attribute(); ?&gt;"&gt; &lt;?php $atts = array( 'class' =&gt; "attachment-$size imageBlock", 'alt' =&gt; get_the_title(), ); the_post_thumbnail('portfolioSmall', $atts); ?&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php $count++; } endwhile; echo '&lt;/ul&gt; &lt;!-- First row --&gt;'; else : echo '&lt;h3&gt;Oops, something went wrong.&lt;/h3&gt;'; endif; ?&gt; </code> pr_hidehome is the option that, when enabled, hides the respective post (but leaves that empty space I'd need to be filled in with one or more of the upcoming thumbnails). You can also see how I am trying to query the posts. However, stackexchange-url ("on this article"), I read that the best way to query posts by custom fields is using an array with 'meta_query' in it. So here's what I tried it: <code> &lt;?php global $wp_query; // First row of images if(!empty($options['home_thumbs'])) { $page_items = $options['home_thumbs']; } else { $page_items = 18; } $portCat = get_category_id($options['portfoliocat']); // get the desired sort order of portfolio items if($options['homepage_sort'] == 'DESC') { $order = 'DESC'; } else { $order = 'ASC'; } $args = array( 'posts_per_page' =&gt; $page_items, 'orderby' =&gt; 'title', 'order' =&gt; $order, 'cat' =&gt; $portCat, 'meta_query' =&gt; array( array( 'key' =&gt; 'pr_hidehome', 'value' =&gt; 'the_value_you_want', 'compare' =&gt; 'LIKE' ) ) ); query_posts($args); // arrays to detect first and last columns $firsts = array(6,12,18,24,30,36); $lasts = array(5,11,17,23,29,35); if (have_posts()) : $count = 0; echo '&lt;ul class="imageRows rowOne"&gt;'; while (have_posts()) : the_post(); $custom_meta = get_post_custom($post-&gt;ID); if (has_post_thumbnail() &amp;&amp; $custom_meta['pr_hidehome'][0] != true) { ?&gt; &lt;li class="&lt;?php if (in_array($count, $firsts) ) { echo ' columnFirst'; } if (in_array($count, $lasts) ) { echo ' columnLast'; } ?&gt;"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title_attribute(); ?&gt;"&gt; &lt;?php $atts = array( 'class' =&gt; "attachment-$size imageBlock", 'alt' =&gt; get_the_title(), ); the_post_thumbnail('portfolioSmall', $atts); ?&gt; &lt;/a&gt; &lt;/li&gt; &lt;?php $count++; } endwhile; echo '&lt;/ul&gt; &lt;!-- First row --&gt;'; else : echo '&lt;h3&gt;Oops, something went wrong.&lt;/h3&gt;'; endif; ?&gt; </code> Sadly this gave me the fallback error 'Oops, something went wrong'. That's it. I hope I explained myself well enough. If not, I'll try and rephrase everything so that you can help me out! Thank you very much. All help is greatly appreciated ;)
Will do. It's just a bit more complicated, but here it goes: <code> &lt;?php /** * WP Practica * Home Page Template */ get_header(); ?&gt; &lt;?php $options = get_option( 'practica_theme_settings' ); ?&gt; &lt;div id="main"&gt; &lt;!-- start div#main --&gt; &lt;!-- Optional 3D style --&gt;&lt;div class="dimWrap_content"&gt;&lt;/div&gt; &lt;div id="content" &gt; &lt;!-- start div#content --&gt; &lt;?php global $wp_query; // First row of images if(!empty($options['home_thumbs'])) { $page_items = $options['home_thumbs']; } else { $page_items = 18; } $portCat = get_category_id($options['portfoliocat']); // get the desired sort order of portfolio items if($options['homepage_sort'] == 'DESC') { $order = 'DESC'; } else { $order = 'ASC'; } $hideFromHome = get_post_meta($wp_query-&gt;post-&gt;ID, 'pr_hidehome', true); query_posts('posts_per_page=-1&amp;orderby=title&amp;order=' . $order . '&amp;cat=' . $portCat . '&amp;meta_key=' . $hideFromHome .'&amp;meta_value=' . true); // arrays to detect first and last columns $firsts = array(6,12,18,24,30,36); $lasts = array(5,11,17,23,29,35); if ( $options['nothumb_content'] == true ) { ?&gt; &lt;div id="page-content"&gt; &lt;?php the_content(); ?&gt; &lt;/div&gt; &lt;?php } else { if (have_posts()) : $count = 0; echo '&lt;ul class="imageRows rowOne"&gt;'; while (have_posts()) : the_post(); $custom_meta = get_post_custom($post-&gt;ID); if (has_post_thumbnail() &amp;&amp; $custom_meta['pr_hidehome'][0] != true) { ?&gt; &lt;li class="&lt;?php if (in_array($count, $firsts) ) { echo ' columnFirst'; } if (in_array($count, $lasts) ) { echo ' columnLast'; } ?&gt;"&gt; &lt;?php if ($custom_meta['pr_openpretty_home'][0] != true) { ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title_attribute(); ?&gt;"&gt; &lt;?php $atts = array( 'class' =&gt; "attachment-$size imageBlock", 'alt' =&gt; get_the_title(), ); the_post_thumbnail('portfolioSmall', $atts); ?&gt; &lt;/a&gt; &lt;?php } else { if ($custom_meta['pr_openpretty_video'][0] == 'Your URL' || $custom_meta['pr_openpretty_video'][0] == '') { ?&gt; &lt;a href="&lt;?php $image_id = get_post_thumbnail_id(); $image_url = wp_get_attachment_image_src($image_id,’large’, true); echo $image_url[0]; ?&gt;" title="&lt;?php the_title_attribute(); ?&gt;" rel="prettyPhoto&lt;?php if(!empty($custom_meta['pr_openpretty_slideshow'][0])) { echo '['; echo $custom_meta['pr_openpretty_slideshow'][0]; echo ']'; } ?&gt;"&gt; &lt;?php $atts = array( 'class' =&gt; "attachment-$size imageBlock", 'alt' =&gt; get_the_title(), ); the_post_thumbnail('portfolioSmall', $atts); ?&gt; &lt;/a&gt; &lt;?php } else { ?&gt; &lt;a class="videoBlock" href="&lt;?php echo $custom_meta['pr_openpretty_video'][0]; ?&gt;?width=100%&amp;height=100%" title="&lt;?php the_title_attribute(); ?&gt;" rel="prettyPhoto&lt;?php if(!empty($custom_meta['pr_openpretty_slideshow'][0])) { echo '['; echo $custom_meta['pr_openpretty_slideshow'][0]; echo ']'; } ?&gt;"&gt; &lt;?php $atts = array( 'class' =&gt; "attachment-$size imageBlock", 'alt' =&gt; get_the_title(), ); the_post_thumbnail('portfolioSmall', $atts); ?&gt; &lt;/a&gt; &lt;?php } ?&gt; &lt;?php } ?&gt; &lt;/li&gt; &lt;?php $count++; if($count == $page_items) { break; } } endwhile; echo '&lt;/ul&gt; &lt;!-- First row --&gt;'; else : echo '&lt;h3&gt;Oops, something went wrong.&lt;/h3&gt;'; endif; } ?&gt; &lt;/div&gt; &lt;!-- end div#content --&gt; &lt;?php get_footer(); ?&gt; </code>
Query Posts (post meta)
wordpress
Right now, I'm able to dynamically generate js and css, based on my theme options To do that i set up a query var, that if present redirects to a php file, which then loads itself as a javascript file. Afterwhich it then takes the jqpostID, and and grabs any options i need to generate my js. I basically have to include a script link that references a location portion of my html http://mywordpress.com/?dynamic=js&amp;jqpostid=130 I'd like to make it more readable, and less apparent that it is being dynamically generated. maybe like this... http://mywordpress.com/dynamic/js/123 i suppose this would even be better... http://mywordpress.com/dynamic/js/123.js I figure i have to hook into the rewrite engine of wordpress somehow. And add a new rule. Any help, or references to other articles would be great, or some sample code would be awesome.
adding these functions should do the trick. First things first, add this line to functions.php while you are working on this: <code> add_action('init', 'flush_rewrite_rules'); </code> What that code will do is constantly flush the rewrite rules, it makes this easier to test while you are working on it, instead of having to go in and manually reset them after every little change you make to the rewrite rules. MAKE SURE you remove this when you are done and satisfied that everything is working. Next, this function will create the rewrite rules you want. <code> function custom_add_rewrite_rules( $wp_rewrite ) { $new_rules = array( 'dynamic/js/(\d+).js' =&gt; 'index.php?dynamic=js&amp;jqpostid=' . $wp_rewrite-&gt;preg_index(1), 'dynamic/css/(\d+).css' =&gt; 'index.php?dynamic=css&amp;csspostid=' . $wp_rewrite-&gt;preg_index(1) ); $wp_rewrite-&gt;rules = $new_rules + $wp_rewrite-&gt;rules; } add_action('generate_rewrite_rules', 'custom_add_rewrite_rules'); </code> I took a stab at what maybe the CSS rule would look like as well, you may have to adjust it for your needs, I just figured it would be formatted in a way similar to what you described for the javascript. These may cause some strange behavior when it tries to rewrite the URL into a file extension, and it may not work at all. In that case, just remove the .js and .css from the end of the first part of the associative array entries. <code> function custom_add_rewrite_rules( $wp_rewrite ) { $new_rules = array( 'dynamic/js/(\d+)' =&gt; 'index.php?dynamic=js&amp;jqpostid=' . $wp_rewrite-&gt;preg_index(1), 'dynamic/css/(\d+)' =&gt; 'index.php?dynamic=css&amp;csspostid=' . $wp_rewrite-&gt;preg_index(1) ); $wp_rewrite-&gt;rules = $new_rules + $wp_rewrite-&gt;rules; } add_action('generate_rewrite_rules', 'custom_add_rewrite_rules'); </code> Basically all this does is sets up the URL to look for and the string it runs in its place. The first part of the array entry has a regular expression that looks for numbers only, the portion in parenthesis. (this can be adjusted to look for a specific number of digits, if needed) The match of which is passed into the second part of the array entry as what will be returned in the string. I hope this helps you, feel free to contact me if you have any problems.
How Do I add a redirect rule to Wordpress?
wordpress
I see the following pattern over and over, stackexchange-url ("on this site") and on other places: <code> add_action( 'save_post', 'wpse14169_save_post' ); function wpse14169_save_post( $post_id ) { if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) { return $post_id; } // Other code... } </code> Why should I return <code> $post_id </code> ? <code> save_post </code> is an action, and the return value of an action handler is ignored. The WordPress core itself doesn't do it either. The Codex example does return the <code> $post_id </code> , but it would not be the first incorrect (or outdated) line in the Codex. Am I missing something? Do I need to return <code> $post_id </code> ? Was there a there a time when this was needed?
The <code> 'save_post' </code> action was added to core in 2.0 , and has always been an action. Looking through the current autosave procedures, it doesn't appear to call the <code> 'save_post' </code> action directly at any time. So the short answer is, no. There is no reason, and has never been any reason, to return any value on this action. Of course, it doesn't hurt at all to do return the post id.
Return $post_id when DOING_AUTOSAVE?
wordpress
Each post has a lat/lng value attached to it via postmeta. I'm trying to grab all posts within a bounding lat/lng value. Here's the <code> get_posts </code> query: <code> $posts = get_posts(array( 'posts_per_page' =&gt; 100, 'post_type' =&gt; 'place', 'post_status' =&gt; 'publish', 'meta_query' =&gt; array( array( 'key' =&gt; 'places_lat', 'value' =&gt; array($lat_min, $lat_max), 'compare' =&gt; 'BETWEEN', //'type' =&gt; 'DECIMAL', ), array( 'key' =&gt; 'places_lng', 'value' =&gt; array($lng_min, $lng_max), 'compare' =&gt; 'BETWEEN', //'type' =&gt; 'DECIMAL', ), ), )); </code> Since postmeta values are stored as strings, I figured I should be casting to <code> DECIMAL </code> , but it just seems to trim the decimal value from the string due to the lack of <code> DECIMAL </code> arguments/precision parameters. I did notice the query treats the floats within the <code> value </code> array as strings, which could also be another point of failure. Running the compiled query without the quotes around each floating value works as expected. I'll be using <code> get_permalink() </code> on each post. I can run a custom query outside of <code> get_posts </code> (via <code> $wpdb-&gt;get_results() </code> ) to properly grab the posts within the bounding box, then loop through the posts and <code> get_permalink </code> , but it ends up firing an additional database query per post to build the permalink - not an ideal solution! Any ideas?
You can filter generated SQL and add precision parameters that you need. Enable filters for <code> get_posts() </code> by adding following to query: <code> 'suppress_filters' =&gt; false, </code> And: <code> add_filter('posts_where','cast_decimal_precision'); function cast_decimal_precision( $where ) { return str_replace('DECIMAL','DECIMAL(10,3)',$where); } </code> Update With Jan's suggestion: <code> add_filter('get_meta_sql','cast_decimal_precision'); function cast_decimal_precision( $array ) { $array['where'] = str_replace('DECIMAL','DECIMAL(10,3)',$array['where']); return $array; } </code>
meta_query: using BETWEEN with floats and/or casting to DECIMAL
wordpress
Bought some hosting with BlueHost, and when I signed up, I carelessly choose 'DekhoForum' as my domain name. I proceeded to setup a website with Wordpress 3.1 at the root folder of that address. Realised that my company had already reserved some domain names with a different provider, that were more suitable. So we got those domains forwarded to the BlueHost nameservers. So. I now have a parked domain for dekho.com.au as shown in my cPanel: If I hit the parked domain, it does take me to my Wordpress install. However, when I click on subsequent links, it will take me to URLs like: dekhoforum.com/page=1 I would prefer it to retain: dekho.com.au/page=1 How do I fix this? Seeing as I am still in the early stages of my development, I would like to iron this issue out from the beginning to avoid any headaches further down the track. I am not sure if this is something I should be changing under the Wordpress settings or something from within my BlueHost cPanel?
Changing the Site URL
How do I switch my Wordpress to point to Parked Domain?
wordpress
I would like to use WordPress to not only run my site, but also to manage users, handle authentication, and read/write content via a client application, but I would like to avoid writing everything from scratch on the PHP-side, as I don't know PHP that well. Is there a "Services" plugin similar to that in Drupal , or something else that can give me easy access to using WordPress as a data-store for a client application? Thanks much in advance for all of your assistance!
WordPress uses an XML-RPC interface in which you can define your own custom methods to it . And if server side coding is not your thing , then there are a few plugins that do most of the job for you: WordPress Web Service Extended API WP RESTful
WordPress as a data-store?
wordpress
I am using the code below to include jQuery in my Wordpress installation. I was previous calling the jQuery file using the standard HTML script but this was causing problems with a Wordpress plugin in IE9. When I use the wp_enqueue_script function, it solves the problem but then it breaks my custom Javascript file which I include after wp_head(). What am I doing wrong? <code> &lt;?php wp_enqueue_script("/wp-content/themes/mytheme/js/jquery-1.5.1.min.js"); ?&gt; &lt;?php wp_head(); ?&gt; &lt;script type="text/javascript" src="/wp-content/themes/mytheme/js/custom.js"&gt;&lt;/script&gt; </code>
1) Only include scripts via wp_head(). For your custom script, register and enqueue it as such: <code> function mytheme_custom_scripts() { if ( ! is_admin() ) { $scriptsrc = get_stylesheet_directory_uri() . '/js/'; wp_register_script( 'mytheme_custom', $scriptsrc . 'custom.js' ); wp_enqueue_script( 'mytheme_custom' ); } } add_action( 'after_setup_theme', 'mytheme_custom_scripts' ); </code> 2) You need to deregister core jQuery, and then register and enqueue your minified version, like such: <code> function mytheme_minified_jquery() { if ( ! is_admin() ) { wp_deregister_script( 'jquery' ); wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js' ); wp_enqueue_script( 'jquery' ); } } add_action( 'init', 'mytheme_minified_jquery', 1000 ); </code> Note that both include a <code> if ( ! is_admin() ) </code> conditional. You don't want to mess with the scripts that load in the Admin UI. Also, my example uses Google for the minified jQuery version. If you want to use your own bundled version, add the SRC to <code> wp_register_script() </code> instead.
Including jQuery in Wordpress
wordpress
Hi to all I need to run this twice a day: <code> UPDATE wp_posts SET post_content = REPLACE ( post_content, '[img]', '&lt;img src="' ); UPDATE wp_posts SET post_content = REPLACE ( post_content, '[IMG]', '&lt;img src="' ); UPDATE wp_posts SET post_content = REPLACE ( post_content, '[/img]', '" /&gt;' ); UPDATE wp_posts SET post_content = REPLACE ( post_content, '[/IMG]', '" /&gt;' ); UPDATE wp_posts SET post_content = REPLACE ( post_content, '[b]', '&lt;strong&gt;' ); UPDATE wp_posts SET post_content = REPLACE ( post_content, '[B]', '&lt;strong&gt;' ); UPDATE wp_posts SET post_content = REPLACE ( post_content, '[/b]', '&lt;/strong&gt;' ); UPDATE wp_posts SET post_content = REPLACE ( post_content, '[/B]', '&lt;/strong&gt;' ); </code> How can do it? I don't want to run it manually and I can't do it each time a post is published because I'm running a MU website and my authors are too lazy to modify their code from bbCode to HTML. I'm using cPanel so I can add a CronJob easily if you teach me how to do it. Thanks to all!
Creating your own schedules is a little messy (because they need to be persistent and stored in database), but it is quite easy to hop on one of the native schedules that run twice a day. <code> add_action( 'wp_version_check', 'my_function' ); function my_function() { //stuff } </code> As for running actual queries you should use <code> $wpdb </code> for that.
Use Cron to modify posts via sql
wordpress
I have a rating system where the user can enter a custom field of either "Stars" or "Hearts", but whichever one they choose they have to enter a value of 1 thru 5. Using wp_query, I can successfully sort by one of these custom fields, but I'm not sure how to sort by both. Here is the code I'm using to sort by one of the custom fields "Stars": <code> $args=array( 'posts_per_page' =&gt; $con_review_num, 'post_type' =&gt; 'con_product_reviews', 'paged' =&gt; $paged, 'orderby' =&gt; 'meta_value', 'order' =&gt; 'DESC', 'meta_key' =&gt; 'Stars' ); </code> Here is what I wish this function would do (notice the last line): <code> $args=array( 'posts_per_page' =&gt; $con_review_num, 'post_type' =&gt; 'con_product_reviews', 'paged' =&gt; $paged, 'orderby' =&gt; 'meta_value', 'order' =&gt; 'DESC', 'meta_key' =&gt; 'Stars Hearts' ); </code> Is there another way to do that?
I had the same problem and could not find a way to make this work with wp_query alone. Instead, I caught the posts_clauses filter and stuck my order_by there. This also meant doing a few joins. Basically, you set a function to catch the posts_clauses (or one of the more restrictive query filters; but let's just use this for now), and then within that JOIN to the post_meta table for the fields you need, then order by them. The important thing is to set up something to then remove the query filter. You could do it at the end of the function that catches it, but I have it separate in my plugin, so I'm going to stick with that. The 'wp' event works fine here. <code> add_filter('posts_clauses', 'filterMarkets') add_filter('wp', 'removeQueryFilter'); public static function removeQueryFilter() { remove_filter('posts_clauses', 'filterMarkets'); } public static function filterMarkets($clauses, $wp_query) { global $wpdb; $clauses['join'] .=&lt;&lt;&lt;SQL JOIN {$wpdb-&gt;postmeta} AS title_meta ON title_meta.post_id = {$wpdb-&gt;posts}.ID AND title_meta.meta_key = 'fest_sortby' JOIN {$wpdb-&gt;postmeta} AS start_date_meta ON start_date_meta.post_id = {$wpdb-&gt;posts}.ID AND start_date_meta.meta_key = 'fest_market_start_date' SQL; $clauses['orderby'] .= " title_meta.meta_value ASC"; $clauses['orderby'] .= " start_date_meta.meta_value ASC"; } return $clauses; </code> }
How do I order by multiple custom fields using wp_query?
wordpress
Hi to all I would like to add a "premium" section to my wordpress blog and I would like to force users to click on a banner before being allowed to register to my blog, any step 2 step idea on how to solve this problem? The banner will be html or js. Thanks a lot to all!
This is a WAY open-ended question. I feel that if you did some research you'd find LOTS of answers. Here's how I would go about it. Install or modify your code to use a members only plugin. Lock all the Non-Member pages. I'm confused on what you men by check a banner, but if the banner is just going to a registration page then block that page unless a query string something like <code> example.net/register?banner=true </code> has been set. If they go to <code> example.net/register </code> it would return false. I'm not sure I answer your question like I said it's super open-ended. That's how I would do it. (if I understand the question) EDIT: You'll need to use a PHP $_SESSION or even a $_COOKIE to see if the user clicked the banner. I would do something like this. Make a category "premium" and assign all preminum page to that category. Add this to your functions.php in your theme <code> add_action( 'template_redirect', 'premium_redirect' ); function premium_redirect(){ //see if post is in category of premium if(in_category('premium')){ //see if the banner variable is set $banner_check =$_GET['banner']; //set the session (or cookie) if($banner_check == 'true'){$_SESSION['banner'] = 'true';} ///see if the $banner and the $_SESSION is set if not take them to the banner page if($_SESSION['banner'] != 'true'){ wp_redirect('http://example.net/bannerpage'); } return; } //end cat check return; } </code> then have your banner link to <code> example.net/premiumpage?banner=true </code> I haven't tested this but I us similar approaches all the time. You may also need to use a custom post type for pages instead of <code> in_category </code> see http://codex.wordpress.org/Conditional_Tags#A_Post_Type
Click on banner to register to the blog
wordpress
I am unable to access the new lightbox-style link popup window. When I try to open it, I get an "error on page" message, and the popup doesn't appear. I've tried on ffx, ie &amp; chrome, on a pc and a mac. I go to work and all is well, on all those same browsers, pc &amp; mac. I can't find any pattern. I've logged out &amp; back in again, cleaned cache, refresh, yada, yada. Does anyone have any idea what could be causing this and how i might fix it?
The problem turned out to be that I added some custom javascript further down the page hat was somehow ruining the tinymce popup js. I wasn't able to figure out exactly what was causing the problem, I needed to comment it out and it works okay now.
tinymce "Link" popup throwing error, not working
wordpress
Im using wordpress 3.1.1, in frontpage i need to display only the media uploads, now im using this acction: <code> add_action( 'parse_query', 'custom_query' ); function custom_query( &amp;$query ) { $query-&gt;set( 'post_type', array('attachment') ); } </code> add_filter( 'pre_get_posts', 'my_get_posts' ); function my_get_posts( &amp;$query ) { <code> if ( is_home() || is_frontpage() ) { $query-&gt;set( 'post_status', 'inherit' ); $query-&gt;set( 'post_type', 'attachment' ); } return $query; } </code> But doesnt work. Any help is working.
You almost have it right, it should be <code> attachment </code> instead of <code> media </code> since all media uploads are "called" attachments" in WordPress, so: <code> $query-&gt;set( 'post_type', 'attachment' ); </code>
How to change default post type / post to media or attachments
wordpress
have a website (www.americanbankingnews.com) that gets 40,000-50,000 page views today. It's currently sitting on a dedicated quad-core Xeon server with 8GB of ram. The site is powered by WordPress and MySQL (sitting on the same server) and I'm currently using W3 Total Cache for page and MySQL query Caching. Unfortunately, that doesn't seem to be enough. During peak traffic times, my servers are getting a few HTTP 500 errors and pages that aren't cached load slowly. I'm currently not using Xcache or any other PHP cache/acceleration tools. Are there additional steps that I should take to try to optimize MySQL and PHP performance? Or should I fork over for an additional server. Specifically, I'd be interested in additional suggestions to improve MySQL performance and whether or not tools like xcache might help in this situation
Hi Matthew Paulson, I see your using W3 Total Cache but your database and object cache is set to disk. Caching objects and your database to disk can actually have a negative performance effect especially if your getting that much traffic. You can read more about the effects on caching database and objects to disk in an article I wrote on how to set up W3 Total Cache The plugin author agreed with the instructions in my settings. To really see the benefit of database and object caching you need to be using a PHP opcode cache like APC. You can follow the copy and paste instructions in the plugin FAQ to compile and set up APC. If your on Ubuntu or Debian you can simply run the command: apt-get apc-php5 to install. Like others have also mentioned you will get a huge performance boost and enable your site to scale much larger by setting up a reverse proxy with Nginx. I give detailed instructions on how to configure and set it up in my WordPress Performance Stack. article. You should also read some of the other questions and answers on here. A lot of good performance and scaling advice has been given. Good luck on your quest. Managing your own server can be very stressful sometimes. Edit Just to show the performance you can gain by installing Nginx as a reverse proxy I'm posting an Apache Benchmark test I just ran on my server: <code> x-wing ~: ab -n 1000 -c 80 http://wp-performance.com/ This is ApacheBench, Version 2.3 &lt;$Revision: 655654 $&gt; Copyright 1996 Adam Twiss, Zeus Technology Ltd, http://www.zeustech.net/ Licensed to The Apache Software Foundation, http://www.apache.org/ Benchmarking wp-performance.com (be patient) Completed 100 requests Completed 200 requests Completed 300 requests Completed 400 requests Completed 500 requests Completed 600 requests Completed 700 requests Completed 800 requests Completed 900 requests Completed 1000 requests Finished 1000 requests Server Software: nginx/0.8.54 Server Hostname: wp-performance.com Server Port: 80 Document Path: / Document Length: 3132 bytes Concurrency Level: 80 Time taken for tests: 0.066 seconds Complete requests: 1000 Failed requests: 0 Write errors: 0 Total transferred: 3605000 bytes HTML transferred: 3132000 bytes Requests per second: 15164.15 [#/sec] (mean) Time per request: 5.276 [ms] (mean) Time per request: 0.066 [ms] (mean, across all concurrent requests) Transfer rate: 53385.52 [Kbytes/sec] received Connection Times (ms) min mean[+/-sd] median max Connect: 0 2 0.6 1 3 Processing: 1 4 0.8 4 5 Waiting: 1 3 0.8 3 5 Total: 3 5 0.6 5 7 Percentage of the requests served within a certain time (ms) 50% 5 66% 5 75% 6 80% 6 90% 6 95% 6 98% 6 99% 6 100% 7 (longest request) </code> Theoretically it's able to handle over 15,000 requests per second. (Same Network)
WordPress MySQL & PHP Performance
wordpress
I'm getting a puzzling error when I var_dump on $menu_id in the code below... First, the test code to create a custom menu on the fly and assign it to a registered menu location called "header-menu" (creates the menu but fails in assigning it to the theme's menu location)... <code> $menu_id = wp_create_nav_menu('my_test_menu_abc_123'); //var_dump($menu_id);die; wp_update_nav_menu_item($menu_id, 0, array( 'menu-item-title' =&gt; 'First Menu Item', 'menu-item-url' =&gt; 'http://mysite.com', 'menu-item-status' =&gt; 'publish')); $theme = get_current_theme(); $mods = get_option("mods_$theme"); $mods['nav_menu_locations']['header-menu'] = $menu_id; update_option("mods_$theme", $mods); </code> When I var_dump on $menu_id below, its returning... object(WP_Error)#110 (2) { ["errors"]=> array(1) { ["menu_exists"]=> array(1) { [0]=> string(102) "The menu name my_test_menu_abc_123 conflicts with another menu name. Please try another." } } ["error_data"]=> array(0) { } } It does not matter what I name the menu, I'm always getting this error. Which leads me to believe I have a flaw in the logic of my code below. Although, it still creates the menu fine, and inserts the menu item into it. It just fails to assign the menu to the theme's header-menu location. Any ideas? Background : Thanks to the help of stackexchange-url ("@Bainternet"), I've managed to come pretty close to a solution. What I'm trying to do is to programmatically create a new custom menu on the fly [solved] , then assign that menu to one of my theme's registered "Menu Locations" [ still not solved - and no one else appears to be able to do this ], all via script inside a plugin. However, eve though the code above will create the my_test_menu_test perfectly, its not assigning it to the "header-menu" location of the theme. My first clue to a problem, is the fact that the echo statement appears to be in conflict with the code I'm using to create the menu. Here is an external reference I've been using... http://wordpress.org/support/topic/how-to-assign-a-wordpress-3-menu-to-primary-location-programmatically However, its unclear whether the author's solution actually works for anyone else (according to my experience and that of the other responders on the post)... Interestingly, as some have noted, the assignment of a custom nav menu to a theme's custom menu locations does not appear to be included in the Custom Menu API...
I got that same error when i put the code you posted in my functions file so i wrapped it up in an if to run only once and i get the menu id using get_term_by and i assign the menu location using set_theme_mod() so here is your very own function to assign a menu to a location: <code> function scotts_set_nav_menu($menu_id,$location){ $locations = get_theme_mod('nav_menu_locations'); $locations[$location] = $menu_id; set_theme_mod( 'nav_menu_locations', $locations ); } </code> and you can try it with this code: <code> $run_once = get_option('menu_check'); if (!$run_once){ $name = 'test'; $menu_id = wp_create_nav_menu($name); $menu = get_term_by( 'name', $name, 'nav_menu' ); wp_update_nav_menu_item($menu-&gt;term_id, 0, array( 'menu-item-title' =&gt; 'First Menu Item', 'menu-item-url' =&gt; 'http://mysite.com', 'menu-item-status' =&gt; 'publish')); scotts_set_nav_menu($menu-&gt;term_id,'header-menu'); update_option('menu_check', true); } </code> just tried it and it works.
WP custom menus error > menu name already exists?
wordpress
I have one "branch" of my main site's navigation tree that should only be accessible to a set of registered, logged-in users. I understand how to query a user's role and capabilities. This question is specifically about what is the best way to leverage the build-in nav menu, but just hide an item conditionally. Do I need to overload the built-in default navigation and write a custom query and build the navigation structure manually? I'd love to avoid this if possible. I don't need full code samples, just your ideas and general framework / approach. Appreciate the advice! T
Use your stackexchange-url ("own walker") and check the capability before you create an item.
Display navigation menu item conditionally based on user capabilities
wordpress
When you paste an image with a <code> class </code> attribute in the Wysiwyg editor, the pasted image no longer has this <code> class </code> attribute. This makes it harder to copy and paste images that are aligned with the <code> alignleft </code> or <code> alignright </code> classes. This used to work in WordPress 2.7, but it no longer works in WordPress 2.8 and up. It also works in the "base" version of TinyMCE (tested with 3.2.7 and 3.3.9.3), so it is probably something that is added by WordPress. I tested this in Safari, Firefox 3.6 and Chrome on Mac OS X. This has been mentioned in a Trac ticket but the main item was dismissed as a browser issue - but I think the <code> class </code> issue is not. Has anyone else found a way to make this work?
Instead of pasting into the Visual editor, switch to the html editor for pasting any kind of html, or using shortcodes. I'd recommend checking the "disable the visual editor" checkbox in your user profile. Then install Mark Jaquith's Markdown on Save plugin for more readable formatting without the wysiwyg pitfalls.
Pasting images removes class attribute
wordpress
I'm using esc_url to sanitize my url. The only problem is that "my link" becomes "mylink". I wouldreally like it to become "my-link". Is there a way to change this?
<code> $url = esc_url ( str_replace(' ' , '-', $url ) ); </code> Replace the spaces to - chars before activating esc_url function, and your problem is solved.
esc_url removes white space. Can I change that to using '-'?
wordpress
http://blog.sanspace.in/ My blog home page is messed up. None of the plugins or sidebar widgets are working. Only the latest post is showed that too partially. However, other pages and posts (accessing through their URL) seems fine. http://blog.sanspace.in/contact/ [page] http://blog.sanspace.in/hello-world/ [post] I am not sure what exactly the problem is. Could anyone help me with this? Is there anything wrong with the wordpress settings? Else, something needs to be done with my server settings? update : I have hosted it with hostso in a shared hosting plan. I did not modify any WP files. My home page is a default WP home which shows the latest post. update _ closed _ : The problem was with the json_last_error() method I used in the latest post. Somehow the method is no longer supported by my server it seems. It caused all the problems.
I believe the page is truncated due to a fatal error. Look for an error log file in the wp directory or add the following line to wp-config.php to hopefully see the error text: <code> define( 'WP_DEBUG', true ); </code>
Wordpress home page doesn't work, but other pages do. How to rectify?
wordpress
how can I delete a background for #main only on my posts. I know that I have to create a conditional <code> if </code> statement in my functions.php file with <code> if (is_post()) </code> but I'm just not sure how to write it.
Take a look at the classes offered by your body_class() function to your <code> &lt;body&gt; </code> element. Then overwrite your div with the ID <code> #main </code> on your posts page with a higher specifity and set this div to <code> display: none; </code> .
Delete backgound for ID with conditional if statement
wordpress
I had a user recently who reported an issue with my plugin's options page not loading. They would click on the "settings" link but only got a blank page. There was also an issue with the rich text editor showing up on the category edit screen. I could not figure out why, on almost every other site but their's, the plugins loaded fine. We disabled all plugins except mine and still could not get the plugins to load properly. Some time passed and I got an email from the user that he had resolved the issue (WP 3.1 site) by editing the file wp-admin/includes/misc.php changing... <code> $got_rewrite = apache_mod_loaded('mod_rewrite', true); </code> To... <code> $got_rewrite = true; </code> Anyone have any insights into why the unedited file might cause issues with plugins?
I think it has to do with http://core.trac.wordpress.org/ticket/15044 The problem appears to be localized around the use of ob_get_clean in the definition of apache_mod_loaded in the branch that has to parse phpinfo.
apache_mod_loaded setting can fubar plugins?
wordpress
I've made a custom widget which shows thumbs of my latest videos. These thumbs are set to be 300px wide, which is the same width of my sidebar. My problem is that i also want to be able to use it in my footer where the width of widgets are only 220px wide. So basically what i want to do is: if the widget is shown in the sidebar use <code> &lt;?php the_post_thumbnail('media-thumb-sidebar'); ?&gt; </code> and if the widget is used in the footer use <code> &lt;?php the_post_thumbnail('media-thumb-footer'); ?&gt; </code> Anyone know how i could do this? Thanks :)
you can always get the thumbnail, but size it with CSS as Xavier mentioned.
Show widget differently depending on if it's in the sidebar or footer
wordpress