question
stringlengths
0
34.8k
answer
stringlengths
0
28.3k
title
stringlengths
7
150
forum_tag
stringclasses
12 values
I was unable to find a custom html widget with Joomla style assignment. Like you create a module (widget), define some HTML and assign it to certain menu items (or set it to show everywhere except the selected etc). Given WordPress doesn't have the same menu system, the widget has to be able to assign itself to certain pages, post categories and tags. Hardcoding conditional tags into the template won't work... Thanks for your help. edited: I have come across this plugin. The problem is I need something easy to use for untechy guys. Like a set of checkboxes containing names of pages and categories.
This plugin might help you : Widget logic EDIT There are also many variants of this kind of plugin listed in this article . Maybe you'll find one that suits your needs there.
Custom html widget with a Joomla-style assigment
wordpress
I have a load of images - up to 16 per post plus a thumbnail and a logo. I want to figure out what the best way to handle them is. Since I'll be adding new entries quite regularly the number of images in the default uploads directory will get quite large. Is this something I should be concerned about? As far as load times etc. I was going to create a co-gallery post type and attach the gallery images to this post type. Then set the gallery id on the Company edit page ( different post type ) to which the gallery belongs. A little code and I have an image gallery. Or should I consider ( ad figure out how to ) uploading the images to a completely separate location/directory? Would doing this be worth the effort and is it really beneficial? Hope that makes sense. Thanx for your help.
Reduce image size using Photoshop, smush.it, or any other decent compressor. A decent rule is .jpg for photos with lots of colors and/or details and .gif for text and under 256 colors with less details. Use exact image sizes, if you use php to resize the images make sure they are cached versions of the re-size. Use a CDN or a non shared fast host. Make the user cache the image in his browser by using; <code> ExpiresByType image/jpeg "access plus 1 month" </code> or <code> &lt;FilesMatch "\.(gif|jpg|png|js|css)$"&gt; Expires 2592000 </code> if your on apache ( insert your own numerical values). By far the most important thing to do is proper compression an sizing.
How to handle large number of images in a post?
wordpress
I'm using the code below to create pagination for my post results, it works fine but is it possible to add a "view all posts on one page" button to the pagination? This would presumably override the pagination code and just display everything all posts on one page. <code> function numeric_pagination ($pageCount = 9, $query = null) { if ($query == null) { global $wp_query; $query = $wp_query; } if ($query-&gt;max_num_pages &lt;= 1) { return; } $pageStart = 1; $paged = $query-&gt;query_vars['paged']; // set current page if on the first page if ($paged == null) { $paged = 1; } // work out if page start is halfway through the current visible pages and if so move it accordingly if ($paged &gt; floor($pageCount / 2)) { $pageStart = $paged - floor($pageCount / 2); } if ($pageStart &lt; 1) { $pageStart = 1; } // make sure page start is if ($pageStart + $pageCount &gt; $query-&gt;max_num_pages) { $pageCount = $query-&gt;max_num_pages - $pageStart; } ?&gt; &lt;div id="pagination"&gt; &lt;?php if ($paged != 1) { ?&gt; &lt;a href="&lt;?php echo get_pagenum_link(1); ?&gt;" class="numbered page-number-first"&gt; &lt;span&gt;&amp;lsaquo; &lt;?php _e('Newest', 'rhinoplasty'); ?&gt;&lt;/span&gt;&lt;/a&gt; &lt;?php } // first page is not visible... if ($pageStart &gt; 1) { //echo 'previous'; } for ($p = $pageStart; $p &lt;= $pageStart + $pageCount; $p ++) { if ($p == $paged) { ?&gt; &lt;span class="numbered page-number-&lt;?php echo $p; ?&gt; current-numeric-page"&gt;&lt;? php echo $p; ?&gt;&lt;/span&gt; &lt;?php } else { ?&gt; &lt;a href="&lt;?php echo get_pagenum_link($p); ?&gt;" class="numbered page-number-&lt;? php echo $p; ?&gt;"&gt;&lt;span&gt;&lt;?php echo $p; ?&gt;&lt;/span&gt;&lt;/a&gt; &lt;?php } } // last page is not visible if ($pageStart + $pageCount &lt; $query-&gt;max_num_pages) { //echo "last"; } if ($paged != $query-&gt;max_num_pages) { ?&gt; &lt;a href="&lt;?php echo get_pagenum_link($query-&gt;max_num_pages); ?&gt;" class="numbered page-number-last"&gt;&lt;span&gt;&lt;?php _e('Oldest', 'rhinoplasty'); ?&gt; &amp;rsaquo;&lt;/span&gt;&lt;/a&gt; &lt;?php } ?&gt; &lt;/div&gt; &lt;?php } </code> I'm not really sure how to go about doing this, any suggestions would be greatly appreciated. Changing to different pagination code is also fine if that will work better. Just to clarify my question, I want to add a 'view all posts on one page' functionality, basically over-riding the pagination code - this would be done by clicking a "view all" link to the right of the pagination menu ( 4 5 ... last Next > > View All> ). Update - almost there I think: I've added this: <code> &lt;?php $Path=$_SERVER['REQUEST_URI']; $URI='http://sitename.com'.$Path; $nopage = add_query_arg( 'paged', 'no', $Path ); ?&gt; &lt;a href="&lt;?php echo $nopage; ?&gt;"&gt;View All&lt;/a&gt; </code> Which reloads my page with sitename.com?paged=no, but it still shows pagination - I'm not sure how to override the pagination. UPDATE: Here is how I ended up solving it in case this helps anyone else. After the above code and before the final I added: <code> if (isset($_GET['viewall'])) { function view_allposts( $query ) { $query-&gt;set( 'posts_per_page', -1 ); } add_action( 'pre_get_posts', 'view_allposts' ); } if(!$_GET['viewall']){ ?&gt; &lt;a class="numbered" href="&lt;?php echo add_query_arg( array( 'viewall' =&gt; "true" ), get_pagenum_link(1) ); ?&gt;"&gt;Show All &gt;&gt;&lt;/a&gt; &lt;?php } ?&gt; </code> Works perfectly! Thanks for your help on this Kaiser, although I used a different solution I learned a lot from the links you provided.
You could use <code> add_query_arg() </code> and change <code> $paged </code> for the old query. EDIT: <code> // This should output 'http://example.com/?paged=no' add_query_arg( 'paged', 'no', bloginfo('url') ); </code> Then use <code> get_query_var() </code> to modify the output.
Pagination that includes "view all on one page"
wordpress
hello to all I am newbie to wordpress. I want to remove the title tags from every page.Is there any way to remove that part?Thanks in advance..
You can open your theme files and remove the code that adds this to the page. The typical files to look in are: index.php, page.php, post.php, single.php. Look for this: <code> &lt;h2&gt;&lt;a href=”&lt;?php the_permalink(); ?&gt;”&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; </code> or it might look like this: <code> &lt;?php the_title(); ?&gt; </code> You might want to comment the part of code out so you can easily add it if you want to in the future. To use this method you would surround the part the_title(); with this /** the_title(); */ It would then look like this: <code> &lt;?php /** the_title(); */?&gt; </code>
Removing title tags from each page
wordpress
I have a custom post type called "cpt_docs": add_action( 'init', 'create_post_type' ); <code> function create_post_type() { register_post_type( 'cpt_docs', array( 'labels' =&gt; array( 'name' =&gt; __( 'Docs' ), 'singular_name' =&gt; __( 'Doc' ) ), 'public' =&gt; true, 'has_archive' =&gt; true, ) ); } </code> I have tabs with months and i want to show the "docs" for that month. I need to show the custom post types in the home page, bu i dont how can i do that. Should i use a hard coded sql query or there is another way? thk all.
Well, it works if i use a filter like this: <code> add_filter('getarchives_where','docs_filter'); function docs_filter($where_clause) { return "WHERE post_type = 'cpt_docs' AND post_status = 'publish'"; } </code> Thk all.
show custom post types for a month
wordpress
I am experiencing problems with custom post types, taxonomies, permalinks and rewrites. I created a custom "recipes" post type and taxonomy using this code: <code> add_action('init', 'recipes_register'); function recipes_register() { $labels = array( 'name' =&gt; __('Recipes', 'framework'), 'singular_name' =&gt; __('Recipe', 'framework'), 'add_new' =&gt; __('Add Recipe', 'framework'), 'add_new_item' =&gt; __('Add New Recipe', 'framework'), 'edit_item' =&gt; __('Edit Recipe', 'framework'), 'new_item' =&gt; __('New Recipe', 'framework'), 'view_item' =&gt; __('View Recipe', 'framework'), 'search_items' =&gt; __('Search Recipe', 'framework'), 'not_found' =&gt; __('Nothing found', 'framework'), 'not_found_in_trash' =&gt; __('Nothing found in Trash', 'framework'), 'parent_item_colon' =&gt; '' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'publicly_queryable' =&gt; true, 'show_ui' =&gt; true, 'query_var' =&gt; true, 'menu_icon' =&gt; get_stylesheet_directory_uri() . '/img/admin-recipes.png', 'rewrite' =&gt; true, 'capability_type' =&gt; 'post', 'hierarchical' =&gt; true, 'menu_position' =&gt; null, 'supports' =&gt; array('title','editor','thumbnail','comments'), ); register_post_type( 'recipes' , $args ); } register_taxonomy('recipe_type', array('recipes'), array('hierarchical' =&gt; true, 'label' =&gt; __('Recipe Type', 'framework'), 'rewrite' =&gt; array('hierarchical' =&gt; true, 'slug'=&gt;'recipes'))); </code> The problem occurs when I want to access to custom type post with this type of URL, it throws a 404 error : <code> http://my-website/recipes/name-of-the-recipe/ </code> I think the problem is caused because I want to use the same slug for the taxonomy "recipe_type" and the "recipe" custom post type. I am a bit stuck on this and I would be grateful if you could help me with this. Thanks
your custom post type will likely work if you visit your permalinks page and save, which forces a flush of the rewrite rules. however, you probably won't be able to get the taxonomy to work using the same slug, custom post types seem to supersede taxonomies if they share a slug. anyway, it would probably be a big performance hit even if it did work, WP would have to generate a rewrite rule for every term or post you create, or look in two different places for every request. also- your <code> register_taxonomy </code> should be wrapped in a function that gets called on init, like your <code> recipes_register </code> function.
Problem with custom post types, taxonomy and permalinks
wordpress
Imagine this: I have a custom post type called 'Animals' and I have registered a taxonomy for this post type called 'Types of Animal'. 'Types of Animal' would be 'dog', 'cat' and 'mouse' and so on. So that's straightforward. But say I want to introduce child taxonomies based on the value of the Types of Animal taxonomy. I can use the fact that the taxonomy is hierarchical but if Types of Animal contained 100 terms with 50 possible sub-terms, that makes for a big mess when I'm editing. So what I'd like to do is display a child taxonomy, say 'Breeds', when the editor selects 'dog' in the 'Types of Animal' taxonomy. I could use tags but I'm afraid of the margin of error inputting tags. I would rather that editors had to check a box. Is it possible to display a child/secondary taxonomy dynamically in this way?
Have a look at this tutorial for a possible solution: How To Show/Hide WordPress Meta Boxes By Selecting Categories . Basically, all of the taxonomies would be hidden via javascript, and a function attached to the click event of the Animals taxonomy, which inspects the selected item's ID to show a corresponding child taxonomy. You'd also have to have a bit of logic on page load to show the taxonomies with terms that are already selected. There are potential problems though - what happens if someone deselects "dog", but not any child terms?
Displaying child taxonomies
wordpress
Firstly please allow me to apologise - my fourth question in the week that I've been here! You've all been very helpful though, which is why I keep coming back.. I'm trying to put together a custom post type which doesn't utilise the 'editor'. There is a lot of input fields on the page and most of them will need a custom TinyMCE editor. I have meta boxes with textareas. I've tried the following code: <code> &lt;script type="text/javascript"&gt; jQuery(document).ready(function() { jQuery("#etymology").addClass("mceEditor"); if ( typeof( tinyMCE ) == "object" &amp;&amp; typeof( tinyMCE.execCommand ) == "function" ) { tinyMCE.execCommand("mceAddControl", false, "etymology"); } }); &lt;/script&gt; </code> with... <code> if (function_exists('wp_tiny_mce')) { add_filter('teeny_mce_before_init', create_function('$a', ' $a["theme"] = "advanced"; $a["skin"] = "wp_theme"; $a["height"] = "75"; $a["theme_advanced_buttons1"] = "bold, italic, pastetext, pasteword, bullist, numlist, link, unlink, outdent, indent, charmap, removeformat, spellchecker, fullscreen"; return $a;')); wp_tiny_mce(true); } </code> They don't seem to work together. The TinyMCE editor appears on the right element but it's just the default WP editor, not the settings I've tried to implement. So, my three questions are... Question 1 When using meta boxes for custom post types, what's the best (by best I probably mean most flexible and integrated and least "hacky") way to add a custom TinyMCE editor to multiple elements? Question 2 A follow on from Question 1... How do I go about adding custom buttons to such a setup? Question 3 Is it possible to change the minimum height of the TinyMCE editor? It seems to be force-capped at 100px. My research and attempts at making this work appear to indicate that WordPress' built in TinyMCE functions won't do the job. Might it be best for me to make this completely bespoke, i.e. deregister the existing tinyMCE scripts and register my own? If so, is it possible to only do this on my custom post type pages? Thanks in advance, apologies for the essay! MAJOR EDIT - QUESTIONS 1 &amp; 2 RESOLVED OK, courtesy of Martin's post (and Mike's code!) I've managed to set up multiple textareas with custom buttons: <code> function meta_genus_species() { global $post; $genus = get_post_custom_values( 'genus', $post-&gt;ID ); $species = get_post_custom_values( 'species', $post-&gt;ID ); $etymology = get_post_custom_values( 'etymology', $post-&gt;ID ); $family = get_post_custom_values( 'family', $post-&gt;ID ); $common_names = get_post_custom_values( 'common_names', $post-&gt;ID ); if (!isset($id)) { $id = "etymology"; } if (!isset($temp_min)) { $temp_min = plugins_url('images/temp_max.png' , __FILE__); } if (!isset($temp_max)) { $temp_max = plugins_url('images/temp_min.png' , __FILE__); } if (!isset($pH_min)) { $pH_min = plugins_url('images/pH_max.png' , __FILE__); } if (!isset($pH_max)) { $pH_max = plugins_url('images/pH_max.png' , __FILE__); } $tinyMCE = &lt;&lt;&lt;EOT &lt;script type="text/javascript"&gt; jQuery(document).ready(function($) { $("#{$id}").addClass("mceEditor"); if ( typeof( tinyMCE ) == "object" &amp;&amp; typeof( tinyMCE.execCommand ) == "function" ) { tinyMCE.settings = { theme : "advanced", mode : "none", language : "en", height:"75", width:"100%", theme_advanced_layout_manager : "SimpleLayout", theme_advanced_toolbar_location : "top", theme_advanced_toolbar_align : "left", theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,|,temp_min,temp_max,pH_min,pH_max", theme_advanced_buttons2 : "", theme_advanced_buttons3 : "", setup : function(ed) { ed.addButton('temp_min', { title : 'Temperature: Minimum', image : '{$temp_min}', onclick : function() { ed.focus(); ed.selection.setContent('[temp_min]'); } }), ed.addShortcut("ctrl+1", "temp_min", "temp_min"), ed.addButton('temp_max', { title : 'Temperature: Maximum', image : '{$temp_max}', onclick : function() { ed.focus(); ed.selection.setContent('[temp_max]'); } }), ed.addButton('pH_min', { title : 'pH: Minimum', image : '{$pH_min}', onclick : function() { ed.focus(); ed.selection.setContent('[pH_min]'); } }), ed.addButton('pH_max', { title : 'pH: Maximum', image : '{$pH_max}', onclick : function() { ed.focus(); ed.selection.setContent('[pH_max]'); } }); } }; tinyMCE.execCommand("mceAddControl", true, "{$id}"); } }); &lt;/script&gt; EOT; echo $tinyMCE; ?&gt; &lt;div class="meta_control normal"&gt; &lt;p&gt;Description of taxonomy.&lt;/p&gt; &lt;div class="box"&gt; &lt;label&gt;Genus&lt;/label&gt; &lt;p&gt; &lt;input name="genus" class="text" value="&lt;?php if(isset($genus[0])) { echo esc_attr( $genus[0] ); } ?&gt;" /&gt; &lt;span&gt;Testing...&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;div class="box"&gt; &lt;label&gt;Species&lt;/label&gt; &lt;p&gt; &lt;input name="species" class="text" value="&lt;?php if(isset($species[0])) { echo esc_attr( $species[0] ); } ?&gt;" /&gt; &lt;span&gt;Testing...&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;p&gt; &lt;label&gt;Etymology&lt;/label&gt; &lt;textarea cols="50" rows="5" name="etymology" id="etymology"&gt;&lt;?php if(isset($etymology[0])) { echo esc_attr( $etymology[0] ); } ?&gt;&lt;/textarea&gt; &lt;span&gt;Description&lt;/span&gt; &lt;/p&gt; &lt;p&gt; &lt;label&gt;Family&lt;/label&gt; &lt;input name="family" class="text" value="&lt;?php if(isset($family[0])) { echo esc_attr( $family[0] ); } ?&gt;" /&gt; &lt;span&gt;Description&lt;/span&gt; &lt;/p&gt; &lt;p&gt; &lt;label&gt;Common Names&lt;/label&gt; &lt;input name="common_names" class="text" value="&lt;?php if(isset($common_names[0])) { echo esc_attr( $common_names[0] ); } ?&gt;" /&gt; &lt;span&gt;Description&lt;/span&gt; &lt;/p&gt; &lt;/div&gt; &lt;?php } function meta_authored() { global $post; $species_author = get_post_custom_values( 'species_author', $post-&gt;ID ); $year_described = get_post_custom_values( 'year_described', $post-&gt;ID ); ?&gt; &lt;div class="meta_control side"&gt; &lt;label&gt;Species Author&lt;/label&gt; &lt;p&gt; &lt;input name="species_author" class="text" value="&lt;?php if(isset($species_author[0])) { echo esc_attr( $species_author[0] ); } ?&gt;" /&gt; &lt;/p&gt; &lt;label&gt;Year Described&lt;/label&gt; &lt;p&gt; &lt;input name="year_described" class="text" value="&lt;?php if(isset($year_described[0])) { echo esc_attr( $year_described[0] ); } ?&gt;" /&gt; &lt;/p&gt; &lt;/div&gt; &lt;?php } </code> I am absolutely over the moon! I've been working SO hard to find that information. Thank you ever so much Martin :) Just Question 3 to answer now!
would this be heading in the right direction?.. stackexchange-url ("See Mikes Code")
TinyMCE with custom buttons on a meta box
wordpress
I'm working on trying to get my homepage template to display post-format 'gallery' a little different than the other formats but having no luck so far. Here is a snippet 'inside the loop' that shows what I am trying to accomplish. Basically saying if post-format = 'aside' do x, elseif post-format is gallery, then I want to show a thumbnail, else just content. <code> &lt;div class="entry"&gt; &lt;?php if ( has_post_format( 'aside' , $post_id )) { the_excerpt(__('Continue Reading &amp;rarr;', 'wptumble-fluid')); } elseif ( has_post_format( 'gallery' , $post_id )) { if ( has_post_thumbnail() ) { // use the thumbnail ("featured image") $thumb_id = get_post_thumbnail_id(); the_post_thumbnail( 'thumbnail' ); } else { $attachments = get_children( array( 'post_parent' =&gt; get_the_ID(), 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'order' =&gt; 'ASC', 'orderby' =&gt; 'menu_order ID', 'numberposts' =&gt; 1) ); foreach ( $attachments as $thumb_id =&gt; $attachment ) echo wp_get_attachment_image($thumb_id, 'thumbnail' ); } } else { if ( $fluidtheme_options['fluid_post_content'] == "content" ) the_content(__('Continue Reading &amp;rarr;', 'wptumble-fluid')); else the_excerpt(); } wp_link_pages( $page_link_args ); ?&gt; &lt;/div&gt;&lt;!-- /.entry --&gt; </code> The aside part works, as does the final option which checks the theme options page. The only thing not working is my elseif statement where I want it to grab the post attachment. Probably just doing my php wrong, but this is the closest I can seem to come up with. Still in the learning process. thanks
This one's an easy fix! The first argument in <code> has_post_format() </code> is a string in the format <code> post-format-{type} </code> , e.g. <code> post-format-aside </code> , or <code> post-format-gallery </code> , etc. So, e.g., change this: <code> has_post_format( 'aside' , $post_id ) </code> To this: <code> has_post_format( 'post-format-aside' , $post_id ) </code> Wash, rinse, and repeat for all uses of <code> has_post_format() </code> . EDIT Given your example code, I would even suggest another potential option, combining <code> get_template_part() </code> and <code> get_post_format() </code> . If you create template part files <code> entry-aside.php </code> and <code> entry-gallery.php </code> , along with a default, <code> entry.php </code> , then: 1) Move this code to <code> entry-aside.php </code> (and remove unsupported parameters): <code> the_excerpt(); </code> 2) Move this code to <code> entry-gallery.php </code> : <code> if ( has_post_thumbnail() ) { // use the thumbnail ("featured image") $thumb_id = get_post_thumbnail_id(); the_post_thumbnail( 'thumbnail' ); } else { $attachments = get_children( array( 'post_parent' =&gt; get_the_ID(), 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'order' =&gt; 'ASC', 'orderby' =&gt; 'menu_order ID', 'numberposts' =&gt; 1) ); foreach ( $attachments as $thumb_id =&gt; $attachment ) echo wp_get_attachment_image($thumb_id, 'thumbnail' ); } </code> 3) Move this code to <code> entry.php </code> <code> if ( $fluidtheme_options['fluid_post_content'] == "content" ) the_content(__('Continue Reading &amp;rarr;', 'wptumble-fluid')); else the_excerpt(); </code> 4) Replace that entire if/else conditional block with this: <code> get_template_part( 'entry', get_post_format() ); </code> Now, it might be overkill for your current use case - but the advantage is that, if in the future you decide to support other post format types, you simply have to add <code> entry-{type}.php </code> , and your template will already be set up to support it! For example, if you add support for quotes, simply add <code> entry-quote.php </code> , with whatever appropriate code, and you don't have to change any existing code.
If post-format == 'gallery' conditional
wordpress
I have a Custom Field on a page named <code> banner_id_list </code> . I have a Custom Post Type called <code> top_banner </code> . I add a few banners, note the IDs and then go back to the page and add a comma delimited list of IDs in the <code> banner_id_list </code> custom field. In my template, the plan is to check the current posts meta using get_post_meta() . That should produce a list of IDs that I can then take and use in get_posts() with <code> post__in = array() </code> (see post__in ). Now on to the code, I'm missing something here but I'm a bit of a newb at this. <code> // get the banner_id_list based on the meta custom field for this page $banner_id_list = get_post_meta($post-&gt;ID, 'banner_id_list', true); </code> If I dump that I see the expected data, a list of IDs I entered into the custom field. Now for my query: <code> $args = array( 'post_type' =&gt; 'top_banner', 'post_status' =&gt; 'publish', 'numberposts' =&gt; -1, 'order' =&gt; ASC, 'orderby' =&gt; menu_order, 'post__in' =&gt; array($banner_id_list) ); $banners = get_posts($args); </code> But there's something funky about using <code> $banner_id_list </code> here. It's only getting a single record. But if I manually enter values in place of that variable, it works properly. I think it's something simple/fundamental I'm missing, hope someone can help!
If <code> $banner_id_list </code> holds comma-delimited list then to convert it to array instead of <code> array($banner_id_list) </code> you need to do <code> explode(',', $banner_id_list) </code>
post__in not taking my list of IDs
wordpress
I am looking for plugin to sort posts by alphabetic orders. <code> Sort: A-Z Z-A Newest Oldest </code> and option to view per page like in stake exchange websites <code> Per Page: 20 40 60 All </code> if not exists, can i do this in query post (How ?) Please suggest me ! Thanks
Don't know about a plugin but you can do that easily with query_posts() paste this two functions in your theme's functions.php file <code> function display_sort_links(){ ?&gt; &lt;div class="sort_links"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="?P_O=az"&gt;A - Z&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="?P_O=za"&gt;Z - A&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php } function display_posts_numbers(){ ?&gt; &lt;div class="number_links"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="?P_P=20"&gt;20&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="?P_P=40"&gt;40&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="?P_P=60"&gt;60&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="?P_P=-1"&gt;All&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; &lt;?php } </code> then paste this in the archive file just above you loop ( <code> if have_posts() </code> ) <code> global $query_string; parse_str( $query_string, $args ); //check for posts number per page if (isset($_GET['P_P'])){ $args['posts_per_page'] = (int)$_GET['P_P']; } //check for posts order a-z or z-a if (isset($_GET['P_O'])){ switch ($_GET['P_O'])){ case "az": $args['orderby'] = 'title'; $args['order'] = 'ASC'; break; case "za": $args['orderby'] = 'title'; $args['order'] = 'DESC' ; break; } } query_posts( $args ); </code> and where ever you want the links to show just call the functions from before : <code> //for a-z z-a sort use: &lt;?php display_sort_links(); ?&gt; //and for numbers use: &lt;?php display_posts_numbers(); ?&gt; </code>
sort posts by alphabetic plugin suggestion
wordpress
I can't get the user variable from the main class loading a "child class" example: <code> //PLUGIN FILE class father{ var $user; function __construct() { add_action('plugins_loaded', array(&amp;$this, 'loaded')); } function plugins_loaded(){ global $wp_get_current_user; $this-&gt;user = wp_get_current_user(); } } $plugin = new parent(); </code> That was the plugin file. <code> //EXTEND CLASS class child extends father{ function __construct(){ parent::__construct(); } function user_id(){ echo $this-&gt;user-&gt;ID; } } </code> That was the extend class. <code> //CONFIG FILE (DISPLAYED IN ADMIN PANEL) $child = new child(); $user_id = $child-&gt;user-&gt;id; $child-&gt;user_id(); </code> And that was the config page. I can't get the user id in the extended class, but yes in the father class. Why and how i can solve it?
This works for me: <code> class father { var $user; function __construct() { add_action( 'init', array( &amp;$this, 'set_user' ) ); } function set_user() { $this-&gt;user = wp_get_current_user(); } } class child extends father { function __construct() { parent::__construct(); } function user_id(){ return $this-&gt;user-&gt;ID; } } $father = new father(); $child = new child(); add_action( 'admin_notices', 'test_stuff' ); function test_stuff() { global $child; print '&lt;pre&gt;Child: ' . print_r( $child-&gt;user_id(), true ) . '&lt;/pre&gt;'; } </code>
Extend a class plugin
wordpress
I created a stripped-down page template to use for my landing pages. But I must have cut too much out of it, because I've lost the WordPress 3.1+ Admin Bar. What functions do I need to call to get the Admin Bar to appear at the top of the page again?
Not sure exactly, but adding the following two functions should get it to work and save you other headaches as well: Right before the closing head tag add: <code> &lt;?php wp_head(); ?&gt; </code> And right before the closing body tag add: <code> &lt;?php wp_footer(); ?&gt; </code>
Adding the Admin Bar to a page with a custom template
wordpress
Were drop-in plugins - when you copy a plugin directly inside a theme - a product of design. Or did the practice arise "organically".
It really depends on the developer and how they've been trained to use WordPress. In general, I've seen two schools of thought: Organic Some developers find a feature in a plugin that they think is really cool. Unfortunately, they aren't quite sure how to implement it on their own but really want to include the functionality in their theme. Rather than reinvent the wheel, they'll include a drop-in plugin in their theme and go with it. In the majority of cases (not all, but most that I've seen), this is a direct consequence of inexperience in a developer's background. Either they don't know enough PHP to build a new system on their own, or they're too lazy to attempt it. Product of Design Other developers will try to cater to clients who don't know any better. Their theme is built around, say, a large, Flash-based rotating banner plugin. The plugin is fairly well-known, but they have no idea if/when the original author will update the system with code their theme won't understand. Changing DB schema, changing parameters, new hooks ... all of these can break a theme that doesn't update accordingly. Rather than risk the client clicking on "update" without knowing what it will do (or risk binding themselves to an infinite string of updates for a client once the theme is done), they'll take a snapshot of the current working version and hard-code it into the theme. That way they'll know for sure that it will always work with their theme. Kind of like hard-coding an external reference in Svn and then disabling version control so you can't update it :-) Why it doesn't matter Whether the practice arose organically or intentionally, it is still a very bad idea!!! Whether the theme updates or not, whether the plugin updates or not ... WordPress will eventually update. Limiting your client to a single version is, frankly, insulting and bad business. Instead of hard-coding a drop-in plugin, just make your theme play nice with provided hooks and encourage users to install the other system. If you're using WordPress hooks (actions and filters) rather than direct function calls, you aren't risking much in terms of stability. If a hook changes, the feature is just disabled as if the plugin weren't installed.
Are drop-in plugins a product of design
wordpress
Images keep uploading to /uploads/2010/07 instead of /uploads/2011/06. Permissions are set to 777 just to find out if 755 is an issue, and it's not. I don't have anything in Media to define a new path. It just keeps uploading to the oldest folder. This was an XML dump from another WP to the new WP, so I'm not sure if that had anything to do with it, or not. I can see the image files fine and they post in the post editor, they're just going to the oldest folder and it's not autocreating a new one. I'm running the latest wp 3.1.3. I do have a bunch of plug-ins, the image thumbnail regenerator is one, and I've got a bunch of plugins for sidebar widgets, but nothing out of the ordinary.
Tony, are you creating a new post or editing an older post from 2010/07? I've found that the folder relates to when the post/page was created initially.
Images uploading to wrong folder
wordpress
I want to get the original image with the same width and height as uploaded. My original image is 630*370. Using the following function call I get a thumbnail sized at 630*198. <code> wp_get_attachment_image_src($PriImgId,array('630','370')); </code> How can I get it at 630*370
Try this : <code> wp_get_attachment_image_src( $PriImgId, 'full' ); </code> Also, for more options see the Codex .
how to get original image using wp_get_attachment_image_src
wordpress
I have a custom post type named "performance". I have a custom post query that orders posts by a custom field value (order-date). Now I want to exclude posts that have order-dates that are in the past. I would think I could use the same "order-date" value to compare against todays date to determine if a post should be shown, but I can't find an example that works with the ordering. Everything I've tried breaks the ordering. This seems to work! <code> &lt;?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; $today = date('Y-m-d'); query_posts(array( 'post_type' =&gt; 'performance', 'posts_per_page' =&gt; 5, 'caller_get_posts' =&gt; 5, 'paged' =&gt; $paged, 'meta_key' =&gt; 'order-date', 'orderby' =&gt; 'meta_value', 'order' =&gt; 'ASC', 'meta_query' =&gt; array( array( 'key' =&gt; 'order-date', 'meta-value' =&gt; $value, 'value' =&gt; $today, 'compare' =&gt; '&gt;=', 'type' =&gt; 'CHAR' ) ) )); if (have_posts()) : while (have_posts()) : the_post(); ?&gt; </code> Note that I defined "$today" and added it to the meta_array for comparison with the meta-value. The past-dated performance items disappeared from the list and everything looks like it should. Thanks to Brady for putting me on the right track.
You need to make use of <code> meta_query </code> http://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters <code> &lt;?php $paged = ( get_query_var('paged') ) ? get_query_var('paged') : 1; query_posts(array( 'post_type' =&gt; 'performance', 'posts_per_page' =&gt; 5, 'caller_get_posts' =&gt; 5, 'paged' =&gt; $paged, 'meta_key' =&gt; 'order-date', 'orderby' =&gt; 'meta_value', 'order' =&gt; 'ASC', 'meta_query' =&gt; array( array( 'key' =&gt; 'order-date', 'value' =&gt; $value, 'compare' =&gt; '&gt;=', 'type' =&gt; 'CHAR' ) ) )); if (have_posts()) : while (have_posts()) : the_post(); ?&gt; </code>
Trying to exclude custom posts based on date, while sorting by custom field
wordpress
I have some trouble. <code> /* Catalog */ function my_post_type_catalog() { register_post_type( 'catalog', array( 'label' =&gt; __('Catalog'), 'public' =&gt; true, 'show_ui' =&gt; true, 'show_in_nav_menus' =&gt; true, 'rewrite' =&gt; true, 'hierarchical' =&gt; true, 'menu_position' =&gt; 5, 'supports' =&gt; array( 'title', 'editor', 'thumbnail', 'excerpt') ) ); register_taxonomy('catalog_cat', 'catalog', array('hierarchical' =&gt; true, 'label' =&gt; 'Catalog category', 'singular_name' =&gt; 'catalog_category')); } add_action('init', 'my_post_type_catalog'); add_action("admin_init", "admin_init"); function admin_init(){ add_meta_box("catalogdetails_meta", "Price:", "catalog_meta", "catalog", "normal", "low"); } function catalog_meta() { global $post; $custom = get_post_custom($post-&gt;ID); $price = $custom["price"][0]; ?&gt; &lt;div id='peoplemanager_form_container'&gt; &lt;div id='shortanswers'&gt; &lt;p&gt;&lt;input name="price" size="35" value="&lt;?php echo $price; ?&gt;"&gt;&lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;?php } add_action('save_post', 'save_details'); function save_details(){ global $post; update_post_meta($post-&gt;ID, "price", $_POST["price"]); } // Register the column function price_column_register( $columns ) { $columns['price'] = __( 'Price' ); return $columns; } add_filter( 'manage_edit-catalog_columns', 'price_column_register' ); // Display the column content function price_column_display( $column_name, $post_id ) { if ( 'price' != $column_name ) return; $price = get_post_meta($post_id, 'price', true); if ( !$price ) $price = '&lt;em&gt;' . __( 'undefined' ) . '&lt;/em&gt;'; echo $price; } add_action( 'manage_catalog_post_custom_column', 'price_column_display', 10, 2 ); // Register the column as sortable function price_column_register_sortable( $columns ) { $columns['price'] = 'price'; return $columns; } add_filter( 'manage_edit-catalog_sortable_columns', 'price_column_register_sortable' ); function price_column_orderby( $vars ) { if ( isset( $vars['orderby'] ) &amp;&amp; 'price' == $vars['orderby'] ) { $vars = array_merge( $vars, array( 'meta_key' =&gt; 'price', 'orderby' =&gt; 'meta_value_num' ) ); } return $vars; } add_filter( 'request', 'price_column_orderby' ); </code> The price values not shows. What do I wrong ? ... Thanks for @Brady need replace this code: <code> // Display the column content function price_column_display( $column_name, $post_id ) { if ( 'price' != $column_name ) return; $price = get_post_meta($post_id, 'price', true); if ( !$price ) $price = '&lt;em&gt;' . __( 'undefined' ) . '&lt;/em&gt;'; echo $price; } add_action( 'manage_catalog_post_custom_column', 'price_column_display', 10, 2 ); </code> to: <code> // Display the column content add_action('manage_catalog_posts_custom_column', 'sc_stores_manage_columns', 10, 2); function sc_stores_manage_columns($column_name, $id) { $custom = get_post_custom($id); switch ($column_name) { case 'price': if ($custom["price"][0]==""){echo "none";} echo $custom["price"][0]; break; } } </code>
<code> add_action( 'manage_post_custom_column', 'price_column_display', 10, 2 ); </code> This line is wrong. I think it should be: <code> add_action( 'manage_catalog_post_custom_column', 'price_column_display', 10, 2 ); </code> The hook format is as follows: <code> manage_{$post_type}_posts_custom_column </code> EDIT: try your custom column code like the following code. I know in this format it works: <code> add_action('manage_stores_posts_custom_column', 'sc_stores_manage_columns', 10, 2); function sc_stores_manage_columns($column_name, $id) { $custom = get_post_custom($id); switch ($column_name) { case 'town': echo $custom["sc_stores_town"][0]; break; case 'road': echo $custom["sc_stores_road"][0]; break; } } </code>
Why values dont shows in custom post column?
wordpress
Right, I'm banging my head against a wall here. I'm sure it's something incredibly simple but I keep getting undefined index errors on all of these variables. <code> function meta_genus_species() { global $post; if (isset($post)) { $custom = get_post_custom($post-&gt;ID); } if (isset($custom)) { $genus = $custom["genus"][0]; $species = $custom["species"][0]; $etymology = $custom["etymology"][0]; $family = $custom["family"][0]; $common_names = $custom["common_names"][0]; } ?&gt; &lt;label&gt;Genus:&lt;/label&gt; &lt;input name="genus" value="&lt;?php if(isset($genus)) { echo $genus; } ?&gt;" /&gt; &lt;label&gt;Species:&lt;/label&gt; &lt;input name="species" value="&lt;?php if(isset($species)) { echo $species; } ?&gt;" /&gt; &lt;p&gt;&lt;label&gt;Etymology:&lt;/label&gt;&lt;br /&gt; &lt;textarea cols="50" rows="5" name="etymology"&gt;&lt;?php if(isset($etymology)) { echo $etymology; } ?&gt;&lt;/textarea&gt;&lt;/p&gt; &lt;label&gt;Family:&lt;/label&gt; &lt;input name="family" value="&lt;?php if(isset($family)) { echo $family; } ?&gt;" /&gt; &lt;label&gt;Common Names:&lt;/label&gt; &lt;input name="common_names" value="&lt;?php if(isset($common_names)) { echo $common_names; } ?&gt;" /&gt; &lt;?php } </code> I get this for every variable: Notice: Undefined index: genus in [...]sf-species-profiles.php on line 207 Any ideas?
It's a common PHP error, usually when you try to access an array member with a non-existent key; <code> $array = array( 'hello' =&gt; 'world' ); echo $array['foobar']; // undefined index </code> You should check for the key first with <code> isset( $array['foobar'] ); </code> UPDATE: In this case, I would chuck in a loop that sets-up the variables for you, checking for the index in the process. <code> foreach ( array( 'genus', 'species', 'etymology', 'family', 'common_names' ) as $var ) $$var = isset( $custom[ $var ][0] ) ? $custom[ $var ][0] : ''; echo $genus; // prints value of $custom['genus'][0] if set, otherwise empty </code>
Why on Earth am I getting "undefined_index" errors?
wordpress
I created custom post-types in my site but these posts are not shown in the RSS. Only the regular posts appear there. What could be preventing them from showing up there
They don't normally show there That is how they are supposed to work. Each CPT has a feed of it's own by default Everything in WP has a feed it seems! But if you want them in your main feed this can go in your functions.php <code> // ADDS POST TYPES TO RSS FEED function myfeed_request($qv) { if (isset($qv['feed']) &amp;&amp; !isset($qv['post_type'])) $qv['post_type'] = array('ve_products', 'post'); return $qv; } add_filter('request', 'myfeed_request'); </code> You see this line: <code> $qv['post_type'] = array('ve_products', 'post'); </code> That includes normal posts and my CPT of ve_products in my main feed You would swap out that for your CPT, if you have more CPTs, add them into that array
custom post types don't appear in RSS
wordpress
The user starts at a page showing posts of custom post type, "agent". Each post displayed shows a region/custom taxonomy it belongs to and links to a page that shows all posts in the region the user clicked. This is how these posts are currently displayed, <code> &lt;?php while ( have_posts() ) : the_post(); ?&gt; </code> Ideally I'd like to to sort these alphabetically by meta_key lname rather than by post date which appears to be the wordpress default. Thanks for any input Edit: Script I use to get all custom post type Agents. Puts one specified post as last post. <code> &lt;?php $loop = new WP_Query( array( 'post_type' =&gt; 'agents', 'orderby' =&gt; 'meta_value', 'meta_key' =&gt; 'lname', 'order'=&gt;'ASC', 'meta_query' =&gt; array(array( 'key' =&gt; 'lname' )), 'post__not_in' =&gt; array( '93' ), 'posts_per_page' =&gt; -1 ) ); $loop2 = new WP_Query( array( 'post_type' =&gt; 'agents', 'post__in' =&gt; array( '93' ) ) ); ?&gt; &lt;?php if($loop-&gt;have_posts() || $loop2-&gt;have_posts()) { if($loop-&gt;have_posts()) { while($loop-&gt;have_posts()) { $loop-&gt;the_post(); ?&gt; </code>
This is what ended up working. <code> global $wp_query; query_posts(array_merge(array('orderby' =&gt; 'meta_value', 'meta_key' =&gt; 'rw_lname' ),$wp_query-&gt;query)); &lt;?php while ( have_posts() ) : the_post(); ?&gt; </code>
Sort taxonomy page alphabetically by meta rather than default post date
wordpress
I am creating a contact form page. Perhaps I am doing it wrong? I have something like <code> &lt;?php // even when I remove this validation block it fails if (isset($_POST['name'])) { // do validation ... } get_header(); ?&gt; ... &lt;form id="frmContact" action="&lt;?php the_permalink() ?&gt;" method="post"&gt; ... &lt;/form&gt; ... </code> I used the same logic in another page and it works ... the URL is correct and if I refresh the page, it works. It just gives 404 on post back
Maybe try clearing out the action attribute: action=""
Why after a form post back, I get 404?
wordpress
What I'm trying to do is use less css with Wordpress. You're supposed to link to your .less files with the rel attribute set to 'stylesheet/less'. But I can't figure out how to alter the code that enqueue_style outputs. Is there a way to apply a filter and affect the output? EDIT: If anyone is curious as to how I ended up getting this to work, here is the code snippet: <code> function enqueue_less_styles($tag, $handle) { global $wp_styles; $match_pattern = '/\.less$/U'; if ( preg_match( $match_pattern, $wp_styles-&gt;registered[$handle]-&gt;src ) ) { $handle = $wp_styles-&gt;registered[$handle]-&gt;handle; $media = $wp_styles-&gt;registered[$handle]-&gt;args; $href = $wp_styles-&gt;registered[$handle]-&gt;src . '?ver=' . $wp_styles-&gt;registered[$handle]-&gt;ver; $rel = isset($wp_styles-&gt;registered[$handle]-&gt;extra['alt']) &amp;&amp; $wp_styles-&gt;registered[$handle]-&gt;extra['alt'] ? 'alternate stylesheet' : 'stylesheet'; $title = isset($wp_styles-&gt;registered[$handle]-&gt;extra['title']) ? "title='" . esc_attr( $wp_styles-&gt;registered[$handle]-&gt;extra['title'] ) . "'" : ''; $tag = "&lt;link rel='stylesheet' id='$handle' $title href='$href' type='text/less' media='$media' /&gt;"; } return $tag; } add_filter( 'style_loader_tag', 'enqueue_less_styles', 5, 2); </code>
Yep, final style link output is passed through <code> style_loader_tag </code> filter.
LESS CSS enqueue_style with add_filter to change rel attribute
wordpress
This is the code im using in my functions file: <code> add_action('init', 'sort_out_jquery_pngfix_frontend'); function sort_out_jquery_pngfix_frontend() { global $wp_scripts; if(!is_admin()) { wp_deregister_script('jquery'); wp_register_script('jquery', 'https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js', array(), NULL, true); wp_register_script('dd_belatedpng', get_stylesheet_directory_uri() . '/js/dd_belatedpng.js', array(), NULL, true); $wp_scripts-&gt;add_data('dd_belatedpng', 'conditional', 'lt IE 7'); } } add_action('wp_print_scripts', 'register_theme_scripts'); function register_theme_scripts() { if(!is_admin()) { wp_enqueue_script('modernizr', get_stylesheet_directory_uri() . '/js/modernizr-1.7.min.js', array(), NULL, false); wp_enqueue_script('googlemaps', 'http://maps.google.com/maps/api/js?sensor=false', array(), NULL, true); wp_enqueue_script('jquery'); wp_enqueue_script('dd_belatedpng'); wp_enqueue_script('sc_wc_js', get_stylesheet_directory_uri() . '/js/function.js', array('jquery', 'dd_belatedpng'), '1.0', true); } } </code> I'm using <code> $wp_scripts-&gt;add_data('dd_belatedpng', 'conditional', 'lt IE 7'); </code> to add a conditional statement to this script as per the documentation I can find on-line but its not working. The conditional code is not shown but the js file is. Why is this not working?
From quick look at code this conditional only seems to be processed for styles and not scripts.
wp_enqueue_script adding conditional statement not working
wordpress
I have multiple values I need to be able to punch into a meta-box on the post edit screen. EX: I am working with set-list information for concerts. Song 1 Song 2 Song 3 etc... I am always looking for efficiency in my code, here's the point: Do I just create a brand new id (i.e. song_1, song_2) for every song. Or is there a more condensed way to go about this. Here's a sample of how I would do it as of right now... which would seem like a lot of unncessary code, but then again I am not certain. <code> &lt;?php include('preset-library.php'); $meta_box['post'] = array( // default values, will change to more descriptive values later 'id' =&gt; 'post-format-meta', 'title' =&gt; 'Additional Post Format Meta', 'context' =&gt; 'normal', 'priority' =&gt; 'high', 'fields' =&gt; array( array( 'name' =&gt; 'Song 1', 'desc' =&gt; 'Setlist Song 1', 'id' =&gt; 'song_1', 'type' =&gt; 'text', 'default' =&gt; '' ), array( 'name' =&gt; 'Song 2', 'desc' =&gt; 'Setlist Song 2', 'id' =&gt; 'song_2', 'type' =&gt; 'text', 'default' =&gt; '' // then additional songs ) ) ); add_action('admin_menu', 'plib_add_box'); ?&gt; </code>
I believe that your best option would be to create a single field and save all values in an array, something like this: Create more Meta Boxes as needed .
Working with multiple values and metaboxes
wordpress
Can anyone tell me what the " <code> $handle </code> " ( first parameter ) of <code> wp_localize_script </code> is normally used for. Thanks. P.s.: I have no idea why but stackexchange is telling me this question dosen't meet quality standards. Edit: When i put in my ps it accepted it so i suppose it's the length of the quesion.... if you feel like this is an unacceptable question then apologies
It's basically a unique id of the script you registered or enqueued before. Let's say we enqueued a two scripts with wp_enqueue_script() : <code> wp_enqueue_script( 'my_script_1','/js/some_script.js' ); wp_enqueue_script( 'my_script_2','/js/some_other_script.js' ); </code> Now you want to pass your <code> $data </code> to the script #2 with wp_localize_script() : <code> wp_localize_script( 'my_script_2', 'my_script_2_local', $data ); </code> After this - when WordPress prints out your <code> my_script_2 </code> it will print out your <code> $data </code> variables along with it so you can use them in your script. As you can see <code> my_script_2 </code> is our handle here - it makes the link between our script functions.
wp_localize_script $handle
wordpress
I currently have the following custom wp_query which displays posts from 2 custom WP roles, "custom_role_one" and "custom_role_two". It displays the posts from my custom post type of "listing". It works great but how can I modify this so that the posts are ordered by each role? For example, I would like all posts from "custom_role_one" to be displayed first and then all posts from "custom_role_two" to be listed second. As you can see, they are currently ordered by date. <code> &lt;?php $custom_roles = get_users( array( 'role' =&gt; 'custom_role_one, custom_role_two' ) ); $custom_ids = array(); foreach( $custom_roles as $custom_role ) $custom_ids[] = $custom_role-&gt;ID; $custom_role_query = new WP_Query( array( 'author' =&gt; implode( ',', $custom_ids ), 'post_type' =&gt; 'listing', 'posts_per_page' =&gt; 10, 'orderby' =&gt; 'date', 'order' =&gt; 'DESC', 'paged' =&gt; get_query_var('paged') ) ); ?&gt; &lt;?php if ( $custom_role_query -&gt;have_posts() ) : while ( $custom_role_query -&gt;have_posts() ) : $custom_role_query -&gt;the_post(); ?&gt; &lt;div id="post-&lt;?php the_ID(); ?&gt;"&gt; &lt;h2&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h2&gt; &lt;/div&gt; &lt;?php endwhile; endif; ?&gt; &lt;?php wp_reset_postdata(); ?&gt; </code>
you can add a custom field to each listing post with the user's role and then in your query you can order by that field, for example say you have a custom field named `u_role' then your query should look like this: <code> $custom_role_query = new WP_Query( array( 'author' =&gt; implode( ',', $custom_ids ), 'post_type' =&gt; 'listing', 'posts_per_page' =&gt; 10, 'paged' =&gt; get_query_var('paged'), 'meta_key' =&gt; 'u_role', 'orderby' =&gt; 'meta_value', 'order' =&gt; 'DESC', ) ); </code>
How to order posts by custom WP role?
wordpress
I released a plugin that creates a shortcode and requires a JavaScript file and a CSS file to load on any page that contains that shortcode. I could just make the script/style load on all pages, but that's not the best practice. I only want to load the files on pages that call the shortcode. I've found two methods of doing this, but both have problems. Method 1 sets a flag to true inside the shortcode handler function, and then checks that value inside a <code> wp_footer </code> callback. If it's true, it uses <code> wp_print_scripts() </code> to load the JavaScript. The problem with this is that it only works for JavaScript and not CSS, because CSS should be declared inside <code> &lt;head&gt; </code> , which you can only do during an early hook like <code> init </code> or <code> wp_head </code> . Method 2 fires early and "peeks ahead" to see if the shortcode exists in the current page content. I like this method much better than the first, but the problem with it it won't detect if the template calls <code> do_shortcode() </code> . So, I'm leaning towards using the second method and then trying to detect if a template is assigned, and if so, parse it for the shortcode. Before I do that, though, I wanted to check if anyone knows of a better method. Update: I've integrated the solution into my plugin. If anyone is curious to see it fleshed out in a live environment you can download it or browse it. Update 2: As of WordPress 3.3, it's now possible to call <code> wp_enqueue_script() </code> directly inside a shortcode callback , and the JavaScript file will be called within the document's footer. That's technically possible for CSS files as well, but should be considered a bad practice because outputting CSS outside the <code> &lt;head&gt; </code> tag violates W3C specs, can case FOUC, and may force the browser to re-render the page.
Based on my own experience, I've used a combination of method 1 &amp; 2 - the architecture and footer scripts of 1, and the 'look-ahead' technique of 2. For the look-ahead though, I use regex in place of <code> stripos </code> ; personal preference, faster, and can check for 'malformed' shortcode; <code> preg_match( '#\[ *shortcode([^\]])*\]#i', $content ); </code> If you're concerned about authors using <code> do_shortcode </code> manually, I would opt to instruct them to use an action call enqueue your pre-registered style manually. UPDATE : For the lazy author who never RTFM, output a message to highlight the error of their ways ;) <code> function my_shortcode() { static $enqueued; if ( ! isset( $enqueued ) ) $enqueued = wp_style_is( 'my_style', 'done' ); // cache it so we don't repeat if called over and over // do shortcode $output = ''; if ( ! $enqueued ) // you can output the message on first occurence only by wrapping it in the previous if $output .= &lt;&lt;&lt;HTML &lt;p&gt;Attention! You must enqueue the shortcode stylesheet yourself if calling &lt;code&gt;do_shortcode()&lt;/code&gt; directly!&lt;/p&gt; &lt;p&gt;Use &lt;code&gt;wp_enqueue_style( 'my_style' );&lt;/code&gt; before your &lt;code&gt;get_header()&lt;/code&gt; call inside your template.&lt;/p&gt; HTML; return $output; } </code>
Conditionally Loading JavaScript/CSS for Shortcodes
wordpress
I need to hide the branding section of my blog, but only when someone is viewing it from the iPad. I am not sure how to attack this. EDIT: the function <code> remove_access </code> currently works in my template, but I need to add the iPad function. So would this look correct for trying to hide the area: <code> &lt;?php function remove_access() { if(is_page(array(63, 386, 391, 405, 'forums'))) { remove_action('thematic_header','thematic_blogtitle',3); remove_action('thematic_header', 'thematic_blogdescription',5); remove_action('thematic_header', 'thematic_brandingclosing',7); remove_action('thematic_header','thematic_access',9); remove_action('thematic_footer','thematic_siteinfoopen',20); remove_action('thematic_footer','thematic_siteinfo',30); } } if( preg_match('/ipad/i',$_SERVER['HTTP_USER_AGENT']) ){ add_action('template_redirect', 'remove_access'); } </code> EDIT-3: the complete function changed the condition to: if (it's an iPad AND page is blog) OR (if it's one of the pages in array), then remove items. <code> &lt;?php function remove_access() { if( preg_match('/ipad/i',$_SERVER['HTTP_USER_AGENT']) &amp;&amp; is_page('blog') || is_page(array(63, 386, 391, 405, 'forums')) ){ remove_action('thematic_header','thematic_blogtitle',3); remove_action('thematic_header', 'thematic_blogdescription',5); remove_action('thematic_header', 'thematic_brandingclosing',7); remove_action('thematic_header','thematic_access',9); remove_action('thematic_footer','thematic_siteinfoopen',20); remove_action('thematic_footer','thematic_siteinfo',30); } } add_action('template_redirect', 'remove_access'); </code> EDIT-4: Add a function to remove from child pages as well. I tried this, but it doesn't seem to work: <code> function remove_access() { if( preg_match('/ipad/i',$_SERVER['HTTP_USER_AGENT']) &amp;&amp; is_page('blog') &amp;&amp; ($post-&gt;post_parent == 'blog') || is_page(array(63, 386, 391, 405, 'forums')) &amp;&amp; ($post-&gt;post_parent == (63, 386, 391, 405, 'forums')) ){ remove_action('thematic_header','thematic_blogtitle',3); remove_action('thematic_header', 'thematic_blogdescription',5); remove_action('thematic_header', 'thematic_brandingclosing',7); remove_action('thematic_header','thematic_access',9); remove_action('thematic_footer','thematic_siteinfoopen',20); remove_action('thematic_footer','thematic_siteinfo',30); } } add_action('template_redirect', 'remove_access'); </code>
there's no foolproof method for doing this, but a quick and simple solution is to look at http user agent: <code> &lt;?php if( preg_match('/ipad/i',$_SERVER['HTTP_USER_AGENT']) ): echo "is iPad"; endif; </code>
Conditonal statement for iPad
wordpress
Sony's recent security "holes" showed how unsafe it can be to store data unencrypted. As some of you may know, I 'm working on re-releasing the free CRM theme Driftwood. What is the most secure way to store sensitive (ie non-public information) post meta in the database?
Use bcrypt. http://codahale.com/how-to-safely-store-a-password/
What is the most secure way to store post meta data in WP?
wordpress
While working with metaboxes / custom fields I've seemed to indirectly create many of these _encloseme meta_keys all over my wp_postmeta. Seen here: So far no problems have arisen from this and the custom fields work fine but I've only fidgeted with 2 or so posts on my local test site and I don't want to implement it to my live site if its going to cause issues later on down the road. Anyone know what to do about these, are they normal? Here's the code for my metaboxes. <code> &lt;?php //Add meta boxes to post types function plib_add_box() { global $meta_box; foreach($meta_box as $post_type =&gt; $value) { add_meta_box($value['id'], $value['title'], 'plib_format_box', $post_type, $value['context'], $value['priority']); } } //Formatting function plib_format_box() { global $meta_box, $post; // verification echo '&lt;input type="hidden" name="plib_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" /&gt;'; echo '&lt;table class="form-table"&gt;'; foreach ($meta_box[$post-&gt;post_type]['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 'text': echo '&lt;input type="text" name="'. $field['id']. '" id="'. $field['id'] .'" value="'. ($meta ? $meta : $field['default']) . '" size="30" style="width:97%" /&gt;'. '&lt;br /&gt;'. $field['desc']; break; case 'textarea': echo '&lt;textarea name="'. $field['id']. '" id="'. $field['id']. '" cols="60" rows="4" style="width:97%"&gt;'. ($meta ? $meta : $field['default']) . '&lt;/textarea&gt;'. '&lt;br /&gt;'. $field['desc']; break; case 'select': echo '&lt;select name="'. $field['id'] . '" id="'. $field['id'] . '"&gt;'; foreach ($field['options'] as $option) { echo '&lt;option '. ( $meta == $option ? ' selected="selected"' : '' ) . '&gt;'. $option . '&lt;/option&gt;'; } echo '&lt;/select&gt;'; break; case 'radio': foreach ($field['options'] as $option) { echo '&lt;input type="radio" name="' . $field['id'] . '" value="' . $option['value'] . '"' . ( $meta == $option['value'] ? ' checked="checked"' : '' ) . ' /&gt;' . $option['name']; } break; 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;'; } // Save data from meta box function plib_save_data($post_id) { global $meta_box, $post; //Verify if (!wp_verify_nonce($_POST['plib_meta_box_nonce'], basename(__FILE__))) { return $post_id; } //Check &gt; autosave if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return $post_id; } //Check &gt; 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[$post-&gt;post_type]['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); } } } add_action('save_post', 'plib_save_data'); //We create an array called $meta_box and set the array key to the relevant post type // If custom post type, change the 'post' variable $meta_box['post'] = array( //This is the id applied to the meta box 'id' =&gt; 'venue_location', //This is the title that appears on the meta box container 'title' =&gt; 'Venue/Location', //This defines the part of the page where the edit screen section should be shown 'context' =&gt; 'normal', //This sets the priority within the context where the boxes should show 'priority' =&gt; 'high', //Here we define all the fields we want in the meta box 'fields' =&gt; array( array( 'name' =&gt; 'Venue', 'desc' =&gt; 'Venue Name', 'id' =&gt; 'venue_info', 'type' =&gt; 'text', 'default' =&gt; '' ), array( 'name' =&gt; 'Location', 'desc' =&gt; 'Location of the Venue', 'id' =&gt; 'location_info', 'type' =&gt; 'text', 'default' =&gt; '' ) ) ); add_action('admin_menu', 'plib_add_box'); ?&gt; </code> (Just incase, here's a pastbin link to the above code: http://pastebin.com/0QsqxtZW )
Short version: _encloseme is added to a post when it's published. The wp-cron process should get scheduled shortly thereafter to process the post to look for enclosures. In other words, it cleans them up normally later. Nothing to worry about. Full explanation: "Enclosures" are links in a post to something like an audio or video file. WordPress finds these based on the MIME type of the files being linked to, then saves extra metadata about them. This metadata is used in the RSS feeds, to create special tags to connect these files to the post. This is how podcasts work, for example. If you put a link to an MP3 in a post, then an enclosure will be created for that link, and the feed will have the enclosure, and podcast readers like iTunes can then use that to be able to download the MP3 directly from the RSS feed. _encloseme is just special metadata saying that the post hasn't been processed by the enclosure process yet. When you create or update a published post, that gets auto-added so that the post will be processed by the enclosure creator.
The "_encloseme" Meta-Key Conundrum
wordpress
I'm using Contact Form 7 . I have used it once in my wordpress website as a simple contact form. Now I have to add another contact form for registration process if someone would like to apply for a job. Now, do I have to install again the plugin? Or can I use it again? I would like also to add some function on the registration form for the applicants.
Just copy the shortcode of contact form7 and use it Any where you want and 'N' of times in a single website &amp; If you want same page itself you can do it.Just Paste the Shortcode where you need.That's it.No Need to Install again..
Can I use one wordpress plugin twice in a website?
wordpress
In Settings-Reading I have selected a static page from my "Front page displays". My Front page is "Home" and my Posts page is "News". I have also added a Custom Post Type called "Project" without an archive or a slug and I have added a page "Projects" which uses the template <code> projects.php </code> . So far so good, all is working, except one thing. When I visit a single Project (CPT), in my top navigation "News" becomes selected. In the body-tag it gets the class <code> single single-project postid-114 single-format-standard logged-in </code> And in the nav-menu News has a class of <code> page_item page-item-6 current_page_parent </code> . I don't understand why this (News getting the <code> current_page_parent </code> -class) would be happening, as I expected that none of the page_items would become selected. Two questions: How can I get rid of this? And ideally, how can I make it so that "Projects" becomes selected? Below a screenshot to (hopefully) clarify things.
Might be worth looking at the Codex for registering a post type, the rewrite rule should help: http://codex.wordpress.org/Function_Reference/register_post_type rewrite (boolean or array) (optional) Rewrite permalinks with this format. False to prevent rewrite. Default: true and use post type as slug $args array 'slug' - prepend posts with this slug - defaults to post type's name - use array('slug'=> $slug) to customize permastruct 'with_front' - allowing permalinks to be prepended with front base (example: if your permalink structure is /blog/, then your links will be: false-> /news/, true-> /blog/news/) - defaults to true 'feeds' - default to has_archive value 'pages' - defaults to true You probably want to set with_front to false.
Why is Posts page selected when showing single Custom Post Type?
wordpress
I am Using Wordpress. I installed Contact form7.Now I Want To Add Captcha with Contact form7.I Don't like "Really Simple Captcha" because it shows very simple images.Any other Captcha Plugin Support Contact form7? I Need Like the output of " SI CAPTCHA Anti-Spam" or "Fast Secure Contact Form",Here Unfortunately I can't Remove Contact form7 Plugin.So I Want to Add Captcha Plugin with my Contact form7.Please Help Me.
You can use reCAPTCHA with contact form 7. http://wordpress.org/extend/plugins/contact-form-7-recaptcha-extension/
contact form 7 captcha support anyother captcha plugin?
wordpress
I need to install wordpress plugin for placing source codes to my blogs. See, the following snapshot describes that I have already uploaded plugin to proper place. I didn't make even a single change to that directory &amp; It is uploaded without any intact. What should be the next step for activating this plugin ? ( I am using my own domain ) I have followed steps 1 &amp; 2 from here . I am confused what to do for further steps. Thanks in advance for sharing your knowledge. Sugar.
Ok from here you have two options available: 1) Dont know if you have done this already but you will need to go to wp-admin > > plugins (its at the left of the wp-admin dashboard beneath "appearance") from here if all is well with your manual upload you should see your plugin title in the main area, just click activate plugin. 2) If its not there, then remove the files you have uploaded and go back to wp-admin plugins, at the top you see an area where it says "Plugins" and a button that says "Add New", click "add new" button and the page will re-load. Use the Search for the plugin from the wp repository (search for its title) and grab it from there, just follow the onscreen instructions.. very easy..
Installing a Plugin ( Which is already manually uploaded )
wordpress
I am entering valid details, though wordpress keep prompting same as follows. What would be the wrong thing ? Edit : Even after modifying the permissions as follows, I am getting same errors.
It's almost certainly a permissions problem - your <code> wp-content </code> folder must be writable by your webserver user. Typically setting permissions to <code> 755 </code> will sort this.
Wordpress - connection information
wordpress
I added <code> 'supports' =&gt; 'page-attributes' </code> to my custom post type, and now i have the meta box for page ordering. When i use the argument <code> 'sort_column' =&gt; 'menu_order' </code> with <code> get_pages() </code> on my custom post type, everything orders properly. So why do the custom pages not order properly when i query the posts using <code> query_posts(array('orderby' =&gt; 'menu_order')) </code> And what can i do to get them to order by the menu order? Here is the query im using incase anyone wants to see it. <code> &lt;?php $current_term = ($wp_query-&gt;query_vars['section'] &lt;&gt; '') ? $wp_query-&gt;query_vars['section'] : $menu_arr[0]; query_posts(array( 'post_type' =&gt; 'module', 'orderby' =&gt; 'menu_order', 'tax_query' =&gt; array(array( 'taxonomy' =&gt; 'section', 'field' =&gt; 'slug', 'terms' =&gt; $current_term )), 'post_parent' =&gt; 0 )); ?&gt; </code>
I've just had to do the same thing as you, here is what I did to get this working: <code> 'supports' =&gt; array('title', 'editor', 'thumbnail', 'page-attributes') </code> Register the post type with supports of page attributes. This adds the menu order meta box to the edit screen. From there you can place the order. Then run my custom query: <code> $args = array( 'numberposts' =&gt; -1, 'orderby' =&gt; 'menu_order', 'order' =&gt; 'ASC', 'post_type' =&gt; 'staff' ); $staff = get_posts($args); </code> set <code> orderby </code> to menu_order and <code> order </code> to ASC. Remember if you do not set a value in menu order it sets it to 0. So any posts without an order set will appear first.
Query menu_order custom post types
wordpress
This is the oddest thing I've ever seen on wordpress. Here's my problem: I have a whole ton of text. But the last few lines I have this: &lt; blockquote> [Laughs] I'm doing the exact same thing I'm doin' live. Plug in, turn it up, turn on the machine and play. I don't overdub anything. I ain't going back and redoing solos. I ain't going back and redoing vocals. It's all live. If you listen, you can hear the guitar pick clicking on the strings while I'm singing! So I'm playing it live just as if I was in front of an audience. And that's the way it feels in the studio when everybody's playing together and you're not going back and fixing anything. Because you know I'm really kind of a stickler for that. IF I add this line next (without the quotes)... "I try to keep anybody from having to go back and fix anything so it makes them have to play it now, you know?" The entire body of the post disappears. Only the title shows up. If I remove that line, the text comes back. If I add "asdf", the body stays. If I add a random line, the body disappears. I thought maybe it was a phantom html tag hidden in there or something, so I copied and pasted into notepad to clear any potential underlying formatting and it's still doing it. I've never seen anything like it. I've been poking at this thing for hours. I even tried moving the entire contents to a new post. No dice. I erased and rewrote the entire offending section and then some... nothing. We've got several hundred posts and this has never happened. There's a good 20 blockquotes in this post and everything works fine. We don't really have any plugins that scan text or anything that would be screwing with this thing. For the life of me, I can NOT figure out what in the world is going on........ Does ANYBODY have ANY ideas?!
Maybe the blockquote or it's containing elements are floated with CSS and by adding one more line, the size of it grows too large to fit in the theme / page layout, and the whole post body gets shifted down or out somewhere where it's not visible anymore. You can try the Firebug extension for Firefox, which is an excellent tool for debugging issues like that. But you'll need to know HTML + CSS to take advantage of it.
Content DISAPPEARS when simply adding normal text for ONE POST ONLY
wordpress
I'm about to upgrade my Wordpress MU installation to wordpress 3 Before I update, I want to find out which blogs use which plugins. I don't see a way to do that in the UI, is there? What about a query of the mysql database? Thanks
take a look at Plugin Commander which is a plugin management plugin for multi-site mode, which allows further control on network-activated plugins.
How can I get a list of plugins and which blogs are using them?
wordpress
I'm not sure if this is the right place to ask for this kind of help since is not an actual question but hopefully I can learn a thing or two. I'm developing a plugin (my first one) inspired in the Infinite Scroll Plugin, but instead of showing older posts when scrolling down, I'm showing them when you click a "Show more" link. My intention is to make it public but I know there are a lot of things on it that I can improve before doing so, I tested it a bit in a couple themes and it worked fine but I'm not sure how it'll behave in the real world. Here's a link to it on github: https://github.com/javiervd/Click-and-Load-Pagination Some concerns at the top of my head are: - How to handle users including and external jQuery library instead of the WP one? I'm currently queuing WP's jQuery but I'm not sure how good is this. - Simplicity? As I said this plugin is based on the Infinite Scroll Plugin so I used a similar but much simpler approach to set the options, hopefully this can be optimized as well. - Best practices? This is my first "real" plugin I'm sure I'm not following the best practices out there :( I hope some of you guys can help me, I'll make sure to mention everyone who does when I release it, feel free to fork/request pulls if you wish. Thanks in advance!
Ok, here are some pointers: never run any meaningful code right from plugin body (especially don't start queuing jQuery everywhere like you do - that's asking for trouble), always do it at appropriate hooks; learn how to use <code> $default </code> argument in <code> get_option() </code> will save you a lot of typing there; learn how to use <code> plugins_url() </code> for reliable URL building to files; learn <code> submit_button() </code> , not critical but nifty; consider storing options in single array; if you use options you should implement uninstall to delete them.
Help making my pagination plugin better
wordpress
I don't know how to make a plugin so I can't do what's suggested here stackexchange-url ("How can I make it so the Add New Post page has Visibility set to Private by default?") so what's alternative ?
Found this on WordPress forums : You can just add this to functions.php. I've tested once and seemed to work fine. <code> function default_post_visibility(){ global $post; if ( 'publish' == $post-&gt;post_status ) { $visibility = 'public'; $visibility_trans = __('Public'); } elseif ( !empty( $post-&gt;post_password ) ) { $visibility = 'password'; $visibility_trans = __('Password protected'); } elseif ( $post_type == 'post' &amp;&amp; is_sticky( $post-&gt;ID ) ) { $visibility = 'public'; $visibility_trans = __('Public, Sticky'); } else { $post-&gt;post_password = ''; $visibility = 'private'; $visibility_trans = __('Private'); } ?&gt; &lt;script type="text/javascript"&gt; (function($){ try { $('#post-visibility-display').text('&lt;?php echo $visibility_trans; ?&gt;'); $('#hidden-post-visibility').val('&lt;?php echo $visibility; ?&gt;'); $('#visibility-radio-&lt;?php echo $visibility; ?&gt;').attr('checked', true); } catch(err){} }) (jQuery); &lt;/script&gt; &lt;?php } add_action( 'post_submitbox_misc_actions' , 'default_post_visibility' ); </code>
Easiest way to make post private by default
wordpress
I was looking at the section where you click on the author name on the homepage posts. and it says the Archive posts from xxxx authors so I thought of that while ago I found that some website has it and they including the twitter of that author and their bio with the pic this is one of the example I would say http://www.redmondpie.com/author/oliver.haslam/ I'm trying to look for this kind of plugin or maybe I can edit this to have it myself but needed to ask if this been done from some plugin because I couldn't find one all I see is the widget on the sidebar Thanks For more information I have looked from the plugin page and the tags from wordpress official site about author plugin.... none of them are similar to what I want on the above example link. Thanks!
http://wordpress.org/extend/plugins/tags/author http://wordpress.org/extend/plugins/author-info-widget/ http://wordpress.org/extend/plugins/author-bio/ http://wordpress.org/extend/plugins/author-exposed/ Or you can use your own custom solution
Add author section on Author archive posts
wordpress
I've tried a number of solutions available on the internet, but none seem to work in WP 3.1.1. Thanks!
<code> remove_action('wp_head', 'feed_links', 2); add_action('wp_head', 'my_feed_links'); function my_feed_links() { if ( !current_theme_supports('automatic-feed-links') ) return; // post feed ?&gt; &lt;link rel="alternate" type="&lt;?php echo feed_content_type(); ?&gt;" title="&lt;?php printf(__('%1$s %2$s Feed'), get_bloginfo('name'), ' &amp;raquo; '); ?&gt;" href="&lt;?php echo get_feed_link(); ?&gt; " /&gt; &lt;?php } </code>
How to remove the comments feed from WP 3.1.1?
wordpress
I need to display both a portfolio and a blog on a website, and as a relative newcomer to WordPress, I was wondering what the most effective way is to do this: install a plugin, or create a multisite? Essentially for the portfolio page I just need to display a thumbnail, category, and title, but when each entry is clicked, I need a full, blog-style post. Is there a plugin that will do this, or would a multisite (ie, running the Portfolio as a separate blog) be easier?
Set your blog as Blog category and your portfolio as Portfolio category. You might be also interested in Custom Post types (which I think is the right way to do it): Run your Blog as a usual via Posts and set the Portfolio as Custom post type with its own categories, tags or what ever taxonomy you need. Read more here: http://codex.wordpress.org/Post_Types Multisite is a completely different concept.
Portfolio + Blog: multisite or plugin?
wordpress
What is the best method to count the number of posts in a post type that have a particular term? I don't believe <code> get_posts </code> accepts a term query and I have had no luck with <code> new WP_Query </code> , though I might be doing something wrong. Usage example: <code> $posts = get_posts( array( 'post_type' =&gt; 'inventory', array( 'taxonomy' =&gt; 'status', 'terms' =&gt; 'in-stock', 'field' =&gt; 'slug' ), ) ); $count = count( $posts ); echo $count; </code>
<code> $items = get_posts( array( 'post_type' =&gt; 'inventory', 'numberposts' =&gt; -1, 'taxonomy' =&gt; 'status', 'term' =&gt; 'in-stock' ) ); $count = count( $items ); echo $count; </code>
How to count post type that has a particular term?
wordpress
Quick and dirty, I have meta boxes pertaining to concert information. (i.e. venue and location) and am trying to figure out how to properly display them in my post. At the moment to display the meta-box data I have <code> &lt;?php $venue_info = get_post_custom_values("venue_info"); if (isset($venue_info[0])) { }; ?&gt; &lt;?php if( $venue_info[0] ) : ?&gt; &lt;?php echo $venue_info[0] ?&gt; &lt;?php endif; ?&gt; </code> I realize this is a very jerry-rig way to go about displaying the data. Which is why I'm hoping to learn the proper format. Thank you for your time. This is what my function.php looks like incase you need it <code> &lt;?php include('preset-library.php'); //I create an array called $meta_box and set the array key to the relevant post type // If custom post type, change the 'post' variable, which I don't $meta_box['post'] = array( //This is the id applied to the meta box 'id' =&gt; 'post-format-meta', //This is the title that appears on the meta box container 'title' =&gt; 'Additional Post Format Meta', //This defines the part of the page where the edit screen section should be shown 'context' =&gt; 'normal', //This sets the priority within the context where the boxes should show 'priority' =&gt; 'high', //Here we define all the fields we want in the meta box 'fields' =&gt; array( array( 'name' =&gt; 'Venue', 'desc' =&gt; 'venue information', 'id' =&gt; 'venue_info', 'type' =&gt; 'text', 'default' =&gt; '' ), array( 'name' =&gt; 'Location', 'desc' =&gt; 'Location of the Venue', 'id' =&gt; 'location_info', 'type' =&gt; 'text', 'default' =&gt; '' ) ) ); add_action('admin_menu', 'plib_add_box'); ?&gt; </code> and my include is here <code> //Add meta boxes to post types function plib_add_box() { global $meta_box; foreach($meta_box as $post_type =&gt; $value) { add_meta_box($value['id'], $value['title'], 'plib_format_box', $post_type, $value['context'], $value['priority']); } } //Formatting function plib_format_box() { global $meta_box, $post; // verification echo '&lt;input type="hidden" name="plib_meta_box_nonce" value="', wp_create_nonce(basename(__FILE__)), '" /&gt;'; echo '&lt;table class="form-table"&gt;'; foreach ($meta_box[$post-&gt;post_type]['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 'text': echo '&lt;input type="text" name="'. $field['id']. '" id="'. $field['id'] .'" value="'. ($meta ? $meta : $field['default']) . '" size="30" style="width:97%" /&gt;'. '&lt;br /&gt;'. $field['desc']; break; case 'textarea': echo '&lt;textarea name="'. $field['id']. '" id="'. $field['id']. '" cols="60" rows="4" style="width:97%"&gt;'. ($meta ? $meta : $field['default']) . '&lt;/textarea&gt;'. '&lt;br /&gt;'. $field['desc']; break; case 'select': echo '&lt;select name="'. $field['id'] . '" id="'. $field['id'] . '"&gt;'; foreach ($field['options'] as $option) { echo '&lt;option '. ( $meta == $option ? ' selected="selected"' : '' ) . '&gt;'. $option . '&lt;/option&gt;'; } echo '&lt;/select&gt;'; break; case 'radio': foreach ($field['options'] as $option) { echo '&lt;input type="radio" name="' . $field['id'] . '" value="' . $option['value'] . '"' . ( $meta == $option['value'] ? ' checked="checked"' : '' ) . ' /&gt;' . $option['name']; } break; 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;'; } // Save data from meta box function plib_save_data($post_id) { global $meta_box, $post; //Verify if (!wp_verify_nonce($_POST['plib_meta_box_nonce'], basename(__FILE__))) { return $post_id; } //Check &gt; autosave if (defined('DOING_AUTOSAVE') &amp;&amp; DOING_AUTOSAVE) { return $post_id; } //Check &gt; 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[$post-&gt;post_type]['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); } } } add_action('save_post', 'plib_save_data'); </code> ?>
To check for meta key value then display: <code> if ( get_post_meta( $post-&gt;ID, 'venue_info', true ) ) : echo get_post_meta( $post-&gt;ID, 'venue_info', true ) endif; </code> via: The Codex
Displaying Meta-Box Data Properly
wordpress
I'm using a lot of thumbnails but never the original file. To save space, I'd like to prevent the original from being saved on disk but only keep a thumbnail of 100px. How can I do this? Thanks, Dennis
<code> add_filter( 'wp_generate_attachment_metadata', 'delete_fullsize_image' ); function delete_fullsize_image( $metadata ) { $upload_dir = wp_upload_dir(); $full_image_path = trailingslashit( $upload_dir['basedir'] ) . $metadata['file']; $deleted = unlink( $full_image_path ); return $metadata; } </code>
Delete original image - keep thumbnail?
wordpress
I'm using wp_insert_post and media_sideload_image to create a post and attach a single image to the post. However, how can I mark this attached image as featured thumbnail? It would make listing the thumbnails significantly faster by using the_post_thumbnail instead of looping through each post manually showing the first image. How can I mark the attached image as featured thumbnail? Thanks, Dennis
Perhaps use <code> set_post_thumbnail() </code> ? ( Codex ref. ) EDIT To get the attachment ID using the Post ID: <code> // Associative array of attachments, as $attachment_id =&gt; $attachment $attachments = get_children( array('post_parent' =&gt; $post-&gt;ID, 'post_status' =&gt; 'inherit', 'post_type' =&gt; 'attachment', 'post_mime_type' =&gt; 'image', 'order' =&gt; 'ASC', 'orderby' =&gt; 'menu_order ID') ); $attachment = $attachments[0]; // ID of your single, attached image. </code> Then to set it as the featured image: <code> set_post_thumbnail( $attachment ); </code> I have to check to be sure; the docs are a bit confusing. The default output might be an object. Regardless, <code> get_children() </code> will get you to the ID of your lone attachment, given the Post ID.
Set (featured) thumbnail for post?
wordpress
This is what I have. <code> &lt;?php $week = date('W'); $year = date('Y'); $projects_in_news = new WP_Query( array( 'post_type' =&gt;'news', 'posts_per_page' =&gt; 5, 'orderby' =&gt;'ID', 'order' =&gt;'ASC', 'w' =&gt; $week, 'y' =&gt; $year, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'project_taxo', 'terms' =&gt; $post-&gt;post_name, 'field' =&gt; 'slug' ) ) ) ); // The Loop &lt;?php if($projects_in_news-&gt;have_posts()) : ?&gt; &lt;?php while($projects_in_news-&gt;have_posts()) : $projects_in_news-&gt;the_post(); ?&gt; &lt;ul class="side-list"&gt; &lt;li&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;strong class="title"&gt;&lt;?php the_title(); ?&gt;&lt;/strong&gt; &lt;em class="date"&gt;&lt;span&gt;&lt;?php the_author(); ?&gt;,&lt;/span&gt; &lt;?php the_time('d F Y'); ?&gt;&lt;/em&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;?php endwhile; ?&gt; &lt;?php else: ?&gt; &lt;p&gt;There is no news related to this theme&lt;/p&gt; &lt;?php endif; ?&gt; &lt;?php wp_reset_postdata(); ?&gt; </code> What I have here displays posts from the last week that match the query. Is there a way of determining if this loops query has posts and if not use a different query and loop? I tried adding the following code in place of <code> &lt;p&gt;There is no news related to this theme&lt;/p&gt; </code> <code> &lt;?php $theme_in_news = new WP_Query( array( 'post_type' =&gt;'theme', 'posts_per_page' =&gt; 5, 'orderby' =&gt;'ID', 'order' =&gt;'ASC', ) ); ?&gt; &lt;?php if($theme_in_news-&gt;have_posts()) : ?&gt; &lt;?php while($theme_in_news-&gt;have_posts()) : $theme_in_news-&gt;the_post(); ?&gt; &lt;ul class="side-list"&gt; &lt;li&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt; &lt;strong class="title"&gt;&lt;?php the_title(); ?&gt;&lt;/strong&gt; &lt;em class="date"&gt;&lt;span&gt;&lt;?php the_author(); ?&gt;,&lt;/span&gt; &lt;?php the_time('d F Y'); ?&gt;&lt;/em&gt; &lt;/a&gt; &lt;/li&gt; &lt;/ul&gt; &lt;?php endwhile; ?&gt; </code> But it returns an Internal Server Error. Thanks
The code you have provided already has a check to see if posts exist for said query. So all you need to do is expand on it. <code> ... &lt;?php else: ?&gt; &lt;p&gt;There is no news related to this theme&lt;/p&gt; &lt;?php endif; ?&gt; ... </code> Simply place you next query posts in the above code replacing <code> &lt;p&gt;There is no news related to this theme&lt;/p&gt; </code>
If have posts a week old, display, else display a different loop
wordpress
I am relatively new to Wordpress, have been handed a site developed by someone else on one server, and have to deploy it to another. This site has bbpress installed, plus a load of other stuff. However it also seems to contain (somewhere) references to the other developers server, so even though I have copied the site onto my server all the links still point to his. I'm assuming that somewhere in the template files or database there is a reference to his site but I don't know where. I've done a search / replace and replaced what I can find, but still the same thing happens. I'm just wondering if there is any really obvious place I need to look for things like that. It seems to me he has just done something pretty stupid by hard coding references to his site; but maybe it's for a good reason, I don't know.
There might be hardcoded links in the theme; download it and do a multifile search with a text editor. Editing the text dump destroys serialized data; see another Q/A here: stackexchange-url ("Why is my database import losing text widget data?") To correctly change URLs in the database, use the queires below in phpmyadmin for WordPress. You will also need to change URLs in the Buddy Press tables. See Migrating a WordPress/WPMU/BuddyPress Website - interconnectit.com <code> UPDATE wp_options SET option_value = replace(option_value, 'http://olddomain.com', 'http://newdomain.com') WHERE option_name = 'home' OR option_name = 'siteurl'; UPDATE wp_posts SET guid = replace(guid, 'http://olddomain.com','http://newdomain.com'); UPDATE wp_posts SET post_content = replace(post_content, 'http://olddomain.com', 'http://newdomain.com'); UPDATE wp_postmeta SET meta_value = replace(meta_value, 'http://olddomain.com', 'http://newdomain.com'); </code>
References to other site everywhere in Wordpress site
wordpress
I'm fairly new to wordpress. I'm trying to develop a website with search option to find available room information. I would like to add a search box where people would be able to enter their information and hit the Search button. Then it'll display the available rooms. Something like the below website http://www.easytobook.com/?amu=1972100201 If it's a duplicate question please accept my apologies. Thanks.
I just wanted to add two small things for other peoples.... if your template supports it you can just add : <code> &lt;?php include (TEMPLATEPATH . '/searchform.php'); ?&gt; </code> 2.adding the following code will put a text inside the search box. (like "Write your search and hit Enter" ) <code> &lt;form method="get" id="searchform" action="&lt;?php bloginfo('home'); ?&gt;/"&gt; &lt;div&gt;&lt;input type="text" size="put_a_size_here" name="s" id="s" value="Write your search and hit Enter" onfocus="if(this.value==this.defaultValue)this.value='';" onblur="if(this.value=='')this.value=this.defaultValue;"/&gt; &lt;input type="submit" id="searchsubmit" value="Search" class="btn" /&gt; &lt;/div&gt; &lt;/form&gt; </code> and finally, combining those two advices, just save the code from part two as searchform.php in your template folder, and you can always call it with method number 1.
How to add search form in main page body?
wordpress
I have read stackexchange-url ("here") about switching the current wp database on the fly using <code> $wpdb-&gt;select('database_name'); </code> Once done, I understand that i will have to issue the same statement to the original database. Questions: Right after changing the database, do i need to flush caches or similar stuff to get things working properly? Will I need to call again WP header? Potential issues?
Yes it works! This is the code, assuming both the databases share the same username &amp; password: <code> $wpdb-&gt;select('mydbname'); wp_cache_flush(); </code> Once done, re-issue the same statements, with the original database name. Can't see any performance issue at the moment, maybe because this is done when building a custom form picking data from two posts out of two databases. It may impact performance when used on a large amount of rows in batch loop...
Switching database on the fly
wordpress
Going through the comments table on my wordpress site, I noticed that wordpress is storing the ip address of everyone who makes a comment on my site. How do I remove this functionality? I'm not just talking about the display of the ip in the template, I mean I don't want wordpress to capture it in the first place.
Add this to your functions.php: <code> add_filter('pre_comment_user_ip', 'no_ips'); function no_ips($comment_author_ip){ return ''; } </code> You'll still have the comment_author_IP field in the db, but it will be empty... And to remove existing IP records from the db run this query: <code> UPDATE `wp_comments` SET `comment_author_IP` = '' </code>
How do I turn off wordpress comments ability to capture a users ip address?
wordpress
How do I count the number of media attachments a specific post has? Output example: This post has 22 photos. Thanks!
Use this code if you're in the loop: <code> $attachments = get_children( array( 'post_parent' =&gt; $post-&gt;ID ) ); $count = count( $attachments ); </code> If you're not in the loop, substitute <code> $post-&gt;ID </code> with the ID of the specific post. But that should count all attachments.
How to count media attachments?
wordpress
I'm looking to draw a menu listing of the latest "n" number posts, where the number "n" will be a user defined setting stored as an option. n = 5; //Pull the latest 5 posts from the database. The script I'm currently using (below) pulls all of the posts from the database and then only displays the latest 5 out of that collection. This works fine until I decided to sort the list by title. When I do that, rather than sort the latest 5 posts by title, its sorting the entire collection of posts, without regard to when they were posted Any tips on how I can change this query to only pull the latest "n" posts, then sort by title of those 5 only. ( Note : I'm really interested in the get_posts() query inside the UL element. The first query ($myquery) is just here to make sure we have posts to display before proceeding.) <code> function recent_posts(){ $catHidden=get_cat_ID('hidden'); $myquery = new WP_Query(); $myquery-&gt;query(array('cat' =&gt; "-$catHidden",'post__not_in' =&gt; get_option('sticky_posts'))); $myrecentpostscount = $myquery-&gt;found_posts; if ($myrecentpostscount &gt; 0){ ?&gt; &lt;ul&gt; &lt;?php global $post; if(get_option('mySort') == 'asc'){ $sortOrder='title';$sortDirection='asc'; } $myrecentposts = get_posts ( array ( 'post__not_in' =&gt; get_option('sticky_posts'), 'cat' =&gt; "-$catHidden", 'numberposts' =&gt; get_option('cb2_latest_count'), 'orderby' =&gt; $sortOrder, 'order' =&gt; $sortDirection ) ); foreach($myrecentposts as $idxrecent=&gt;$post) { //DRAW THE POST MENU } wp_reset_postdata(); } </code>
<code> $yourquery = new WP_Query('posts_per_page=5&amp;orderby=title'); </code> would do that. Edit Added Answer <code> &lt;?php $posts = new WP_Query('posts_per_page=5'); foreach($posts-&gt;posts as $post){ $sorted[$post-&gt;ID] = $post-&gt;post_title; } asort($sorted, SORT_STRING); foreach($sorted as $k=&gt;$v){ //your loop -- use ID's for each item call the_title($k); the_content($k); } ?&gt; </code>
How to query the latest 5 posts and sort them by title?
wordpress
Is it possible to add some html after a set amount of posts? For the purposes of a slider after 6 posts i need it to enclose in a div/li or whatever then start a new div/li for the next 6 and so on. Here is my custom query which just prints the post name in a list. <code> &lt;ul&gt; &lt;?php $args=array('post_type' =&gt; 'courses','post_status' =&gt; 'publish','posts_per_page' =&gt; -1);$my_query = null;$my_query = new WP_Query($args);if( $my_query-&gt;have_posts() ) {while ($my_query-&gt;have_posts()) : $my_query-&gt;the_post(); ?&gt; &lt;li&gt;&lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;&lt;/li&gt; &lt;?php endwhile;} wp_reset_query();?&gt; &lt;/ul&gt; </code> After at the start and end of 6 posts i need to open a div then close it after the 6th post. Is this possible with WordPress PHP? Many thanks for any help :)
Here's one way of doing it: <code> &lt;?php $courses = get_posts( array( 'post_type' =&gt; 'courses', 'posts_per_page' =&gt; -1 ) ); if ( $courses ) { print "\n" . '&lt;div style="background:pink"&gt;'; foreach ( $courses as $course_count =&gt; $post ) { setup_postdata( $post ); the_title( "\n", '&lt;br&gt;' ); if ( 5 == $course_count ) { print "\n" . '&lt;/div&gt;'; print "\n" . '&lt;div style="background:yellow;"&gt;'; } } print "\n" . '&lt;/div&gt;'; } wp_reset_postdata(); ?&gt; </code>
Query add html after set amount of posts?
wordpress
In my blog, my "pages" are really just posts sorted by categories. What's the best way to change the way the posts look for one of my category pages?
For styling archive index pages for a given category, target <code> body.category-slug </code> (where <code> slug </code> is the category slug) in CSS. For styling single blog posts that have a given category, assuming your post container is a div, target <code> div.category-slug </code> (where <code> slug </code> is the category slug) in CSS. For PHP operations, you can also use <code> is_category( 'slug' ) </code> , which returns true if you are on the archive index page for a given category, and you can use <code> in_category( 'slug' ) </code> which returns true if the current post is in a given category.
Different post views for different category views
wordpress
For my custom post type i needed to add the Attribute Meta box, but i wanted to add an extra field to it. So here i have copied the Page Attribute meta box code and added my select options, but i need help rewriting the 'Module Type' select box so it functions properly when saving the page. <code> function page_attributes_meta_box2($post) { $post_type_object = get_post_type_object($post-&gt;post_type); if ( $post_type_object-&gt;hierarchical ) { $pages = wp_dropdown_pages(array('post_type' =&gt; $post-&gt;post_type, 'exclude_tree' =&gt; $post-&gt;ID, 'selected' =&gt; $post-&gt;post_parent, 'name' =&gt; 'parent_id', 'show_option_none' =&gt; __('(no parent)'), 'sort_column'=&gt; 'menu_order, post_title', 'echo' =&gt; 0)); if ( ! empty($pages) ) { ?&gt; &lt;p&gt;&lt;strong&gt;&lt;?php _e('Parent') ?&gt;&lt;/strong&gt;&lt;/p&gt; &lt;label class="screen-reader-text" for="parent_id"&gt;&lt;?php _e('Parent') ?&gt;&lt;/label&gt; &lt;?php echo $pages; ?&gt; &lt;?php } // end empty pages check } // end hierarchical check. ?&gt; &lt;p&gt;&lt;strong&gt;&lt;?php _e('Order') ?&gt;&lt;/strong&gt;&lt;/p&gt; &lt;p&gt;&lt;label class="screen-reader-text" for="menu_order"&gt;&lt;?php _e('Order') ?&gt;&lt;/label&gt;&lt;input name="menu_order" type="text" size="4" id="menu_order" value="&lt;?php echo esc_attr($post-&gt;menu_order) ?&gt;" /&gt;&lt;/p&gt; &lt;p&gt;&lt;?php if ( 'page' == $post-&gt;post_type ) _e( 'Need help? Use the Help tab in the upper right of your screen.' ); ?&gt;&lt;/p&gt; &lt;p&gt;&lt;strong&gt;&lt;?php _e('Module Type') ?&gt;&lt;/strong&gt;&lt;/p&gt; &lt;label class="screen-reader-text" for="_cnote_module_page_type"&gt;&lt;?php _e('Module Type') ?&gt;&lt;/label&gt; &lt;select id="_cnote_module_page_type" name="_cnote_module_page_type"&gt; &lt;option value="default"&gt;Default&lt;/option&gt; &lt;option value="parent"&gt;Parent&lt;/option&gt; &lt;option value="chat"&gt;Chat&lt;/option&gt; &lt;/select&gt; &lt;?php } add_action('add_meta_boxes','add_post_template_metaboxr'); function add_post_template_metaboxr() { add_meta_box('postparentdiv', __('Post Template'), 'page_attributes_meta_box2', 'module', 'side', 'high'); } </code> **note that i have not renamed everything yet, theres a lot of copy and pasting in here
To save post meta fields from custom meta boxes you need to hook into <code> save_post </code> with something like this: <code> add_action( 'save_post', 'myplugin_save_postdata' ); </code> There is some full example code on adding meta boxes on the codex Function Reference/add meta box
Custom select box meta field
wordpress
I have managed to fill custom fields with certain predefined values of all my post, but the changes don't take effect until I manually update the posts. Example: <code> // Predefined variable and value $page_description = "This is a sample value that will be put (echo $page_description) into a custom field"; // Echo Variable into Custom Field echo '&lt;input type="text" name="custom-field-name" value="'.$page_description.'" /&gt;'; </code> The above example works as I expected. It inserts the $page_description value into the custom field; so when I go to edit that post I will see the variable value. The issue is that in the current edit screen, without updating yet, if I look at the post on the front end of the site, that custom field has not been updated/saved with that variable value, even though I see in the edit screen. It is not until I update the post that the variable value is saved for good. I have 1,800+ posts that need to be updated. I need a solution to update them. Someone suggested using ajax to auto-update all existing posts so that the new custom field values are saved to the posts. I read an article about it, but not sure how to do it. Or if there is a plugin out there that I can use. I would like some assistance with this. Thanks for any input on this! UDPATE 6-23-11: This is the coding I inserting into my theme's custom field file: <code> $postauth = get_user_meta($post-&gt;post_author, 'nickname', true); /********** UPDATE ALL POST FIELDS Function **********/ //check if data exists if ($postauth){ //if it exists just echo it out echo $postauth; }else{ //if not , update the post meta with your default value and the echo it out. $update_author = get_user_meta($post-&gt;post_author, 'nickname', true); update_post_meta($post-&gt;ID,'nickname',$update_author); echo $update_author; } /********** End UPDATE ALL POST FIELDS Function **********/ </code> I after inserting the code and adjusting my terms, I saved the file and refreshed my site. The code should update a custom field (Author) for all posts that belong to an author and save the author's nickname into that field. I have a basic search option separately installed that is set to search custom fields. So I tested if the update worked by searching for the nickname of a given author who has 8 posts published. Three of the eight were manually updated and they showed up in the custom field search I did for the author's nickname. Now the other 5 posts did not come up in the search results, which lets me know that all the posts were not updated. Are there any solutions to this? UPDATE 6-24-11: I have been searching everywhere in my theme to figure out where to place the solution provided by Bainternet, but no success. I am using the couponpress theme v6.1.4. I have placed the code below in: _header.php, _single.php, system_customfields.php. <code> //check if data exists. This is checking if the predefined field is empty or not. if ($bizname_field != ''){ //if it exists just echo it out echo 'existing value'; }else{ //if not , update the post meta with your default value and the echo it out. // New Variable Value $newvalue = 'New value here'; update_post_meta($post-&gt;ID,'custom-field-name',$newvalue); echo $newvalue; } </code> I am going around in circles and would appreciate some help. Thanks a lot.
The problem is you are not "filling" the custom field with data you are just outputting the value in the edit screen, so you must save or update, and to have that data inside all of your posts you will need to either create a custom query of all the posts and update there meta or manually edit each post. Both options are bad when there are 1500 posts. A simpler solution would be to update the data "on the fly" meaning that on your theme file (the one that displays the meta data) create a conditional check if that field exists and if not the update it, something like: <code> //get saved data $page_description = get_post_meta($post-&gt;ID,'custom-field-name',true); //check if data exists if ($page_description){ //if it exists just echo it out echo $page_description; }else{ //if not , update the post meta with your default value and the echo it out. $default_value = 'This is a sample value that will be put (echo $page_description) into a custom field'; update_post_meta($post-&gt;ID,'custom-field-name',$default_value); echo $default_value; } </code>
Automate post update for all posts?
wordpress
In the WP-Admin when creating a post or a custom post type I want to restrict certain categories to a custom post type. For example, Posts will only be able to select Category A and B. And custom post type A will only be able to select Category C and D. Would I have to write some code to hook into somewhere or is there a function built-in to the framework? Thanks in advance.
I think the best way to do this is to make a category (or taxonomy ) for a specific post type... please see this link... http://net.tutsplus.com/tutorials/wordpress/introducing-wordpress-3-custom-taxonomies/
Restrict categories to a custom post type
wordpress
My pages menu is maximum 3 levels deep and I am having a hard time figuring out how to properly list the child pages in the sidebar. If a page is a parent I want to list it's direct child pages and the title should be this parent. If a page is a child AND has children of itself, I want to list only it's children and the title should be this page If a page is a grandchild, I want to list it's siblings and the title should be this grandchild. For now I am using (from the Codex): <code> &lt;?php if($post-&gt;post_parent) { $children = wp_list_pages("title_li=&amp;child_of=".$post-&gt;post_parent."&amp;echo=0&amp;depth=1&amp;sortcolumn=menuorder"); } else { $children = wp_list_pages("title_li=&amp;child_of=".$post-&gt;ID."&amp;echo=0&amp;depth=1&amp;sortcolumn=menuorder"); } ?&gt; &lt;?php if ($children) { ?&gt; &lt;div class="left-bar-content"&gt; &lt;h2&gt;&lt;?php _e('More ','sunchine') ?&gt;&lt;?php echo get_the_title($post-&gt;post_parent);?&gt;&lt;/h2&gt; &lt;ul class="leftbar-list"&gt; &lt;?php echo $children;?&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!-- .left-bar-content --&gt; &lt;?php } ?&gt; </code> And this is almost correct. Almost, because my it doesn't do my 2nd criterium. The Codex has heaps of options, but I cannot figure out which would be applicable to what I want to accomplish. Using widgets and/or a plugin is not an option. Any help is much appreciated.
Here is the code that satisfies all your 3 requirements above. <code> &lt;?php /* * get_page_depth * Gets the page depth, calls get_post on every iteration * https://gist.github.com/1039575 */ if ( !function_exists( 'get_page_depth' ) ) { function get_page_depth( $id=0, $depth=0 ) { global $post; if ( $id == 0 ) $id = $post-&gt;ID; $page = get_post( $id ); if ( !$page-&gt;post_parent ) { // this page does not have any parent return $depth; } return get_page_depth( $page-&gt;post_parent, $depth+1 ); } } $target_page = get_page_depth( $post-&gt;ID ) &gt; 1 ? $post-&gt;post_parent : $post-&gt;ID; $children = wp_list_pages("title_li=&amp;child_of={$target_page}&amp;depth=1&amp;echo=0&amp;sort_column=menu_order"); ?&gt; &lt;div class="left-bar-content"&gt; &lt;h2&gt;&lt;?php _e('More ','sunchine'); ?&gt;&lt;?php echo get_the_title( $target_page ); ?&gt;&lt;/h2&gt; &lt;ul class="leftbar-list"&gt; &lt;?php echo $children; ?&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!-- .left-bar-content --&gt; </code>
how to properly list child pages in sidebar?
wordpress
I need to implement a state-city selection for my users to choose from. Where they first choose their state and then there is a city drop down field that shows only the cities in that state. Currently, users have to type in the state and city for their account. This concerns me because they may not enter the correct names. I would like this in order to keep these values consistent and to make the site more user friendly. I thought about creating all the states and cities as categories. I tried this which totaled to over 10,300 categories and sort of crashed my site. Certain pages that needed to access the categories would take update 10 minutes to load the page due to the large number of categories it had to process. I am looking a solution to this. I would like them to choose their state from a dropdown list and then based on the state chosen they can pick a city of that state from a dropdown list. I need some major help with this. Thanks a lot.
This isn't a WordPress question, its more suitable for StackOverflow. Regardless, your looking for a chained menu. I've seen this tutorial around a lot, hope it helps.
Dynamic User State & City selection
wordpress
Am Using Wordpress Blog.Here i want Use Tweetmeme Plugin.I want to show the output of the Tweetmeme Plugin to Customizing place(Side of the Post[Not Before or After]).The Plugin Creators are providing Shortcode.Shall i Use this shortcode in Template?I Guess this is not possible.So we need to change Shortcode as a function.How to Create a function from Shortcode?please help me.
Have you tried using the <code> do_shortcode() </code> function? EDIT I'm not familiar with the TweetMeme shortcode, but here's an example usage for putting a NextGen Gallery directly into a template file: <code> echo do_shortcode( '[slideshow id="1" w="603" h="270"]' ); </code> Simply replace with the appropriate shortcode (and parameters) for TweetMeme. Codex ref: do_shortcode() EDIT 2 With TweetMeme, you have another option: Change the Plugin "where" setting from "shortcode" to "manual" Place the <code> tweetmeme() </code> function in your Theme template file where you want to output the TweetMeme button.
May i Use ShortCode in Template?
wordpress
I have this piece of code that works great: it retrieves a particular page from my WordPress database so I can wrap custom code around it in a template. In the instance below it grabs the page called Showreel: <code> &lt;?php $page = get_page_by_title('Showreel'); ?&gt; &lt;?php $my_id = $page; $post_id = get_post($my_id, ARRAY_A); $title = $post_id['post_title']; $content = $post_id['post_content']; ?&gt; &lt;h3&gt;&lt;?php echo $title;?&gt;&lt;/h3&gt; &lt;?php echo $content ?&gt; </code> However, I have conundrum - I have some pages that do not have unique names. How can I retrieve a page only if it is a direct descendant of a certain parent e.g. I would like to retrieve a page under Showreel called The Ruth Rendell Mysteries . My initial thought was that the code below would work, but it doesn't. <code> &lt;?php $page = get_page_by_title('Showreel-&gt;The Ruth Rendell Mysteries'); ?&gt; </code>
have a look at: <code> get_page_by_path() </code> codex.wordpress.org/Function_Reference/get_page_by_path
WordPress - Retrieve a Page if it's a direct descendant of another Page
wordpress
I've got a multi-author site running on Wordpress 3.1.3 . I'm trying to place an extra header above the title for a specific author. So if "John" posts on the blog, it would have an above the post on the home page that says "John's Perpective", or something of that nature. The idea is that we want one of the many author's posts to be highlighted for users. My issue is that I cannot figure out how to check for which user wrote the post within the loop. I am doing it on various other areas of the site via WP_Query. I'm imagining I need something like this (pseudo code): <code> if ( author == 2 ) { echo '&lt;h2&gt;John's Perspective&lt;/h2&gt;' } </code> Should be an easy fix, but I'm stumped. Thanks in advance!
When you're in the loop, you can use <code> get_the_author() </code> to get the author's 'Public' name. Alternatively, you can use <code> get_the_author_meta( 'ID' ) </code> in the loop to get the author ID. So, modifying your psuedo-code: <code> if ( 2 == get_the_author_meta( 'ID' ) ) { echo '&lt;h2&gt;John's Perspective&lt;/h2&gt;' } </code>
Display posts differently depending on which author wrote it
wordpress
I was wondering is there a way to send the admin a notification (email or otherwise) whenever a user submits a post. Currently, I have to log into the admin section to see if there was anything submitted. I need to review their post before actually publishing it, so I need to be notified via email whenever a post is submitted. Does anyone know of a solution for this? Thanks a lot
You could try this inside your themes functions.php: its a function by dagon design <code> function dddn_process($id) { global $wpdb; $tp = $wpdb-&gt;prefix; $result = $wpdb-&gt;get_row(" SELECT post_status, post_title, user_login, user_nicename, display_name FROM {$tp}posts, {$tp}users WHERE {$tp}posts.post_author = {$tp}users.ID AND {$tp}posts.ID = '$id' "); if ($result-&gt;post_status == "publish") { $message = ""; $message .= "A new post was submitted on '" . get_bloginfo('name') . "'\n\n"; $message .= "Title: " . $result-&gt;post_title . "\n\n"; $message .= "Author: " . $result-&gt;display_name . "\n\n"; $message .= "Link: " . get_permalink($id); $subject = "Post Submitted on '" . get_bloginfo('name') . "'"; $recipient = get_bloginfo('admin_email'); mail($recipient, $subject, $message); } } add_action('publish_post', 'dddn_process'); </code>
How to get a nofication when post submitted
wordpress
I have a homepage witch i am trying to query a custom post type as well as everything from the default posts, right now i have 2 loops running everything looks good except i want the 2 different types to intermingle , if that makes sense. Im running a jquery function that shows and hides posts from a either the custom post type or the default "Blog" post type. but since I have to loops the default posts always show up on top and the posts from the custom post type show up on the bottom, here is a link the my live page http://themes.thefragilemachine.com/themachine_v4/ you can see that my custom post type is showing with a "w" icon, they are showing up near the end, but i want them to intermingle,. i know this is alot of type just trying to figure out the best way to explain what i would like too achieve. any help would be amazing! here is my code <code> &lt;?php if (have_posts()) : ?&gt; &lt;?php query_posts('posts_per_page=6');?&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;div class="postitem mall floatleft myblog storm_fader"&gt; &lt;div class="postitem-img lordfade"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_post_thumbnail('type2'); ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="postitem-contentwrap"&gt; &lt;div class="postitem-txt"&gt; &lt;h6&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h6&gt; &lt;?php the_excerpt(''); ?&gt; &lt;/div&gt; &lt;div class="postitem-info"&gt; &lt;ul&gt; &lt;li&gt;&lt;span class="post-label-blog"&gt;&lt;/span&gt;&lt;/li&gt; &lt;li class="spec"&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt; &lt;img src="/themachine_v4/wp-content/themes/themachine_v5_2/lib/imgs/img_gopost.jpg"&gt; &lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="postitem-shadow"&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php else : ?&gt; &lt;h2 class="center" style="color:#FFF;"&gt;ERROR&lt;/h2&gt; &lt;?php endif; ?&gt; &lt;?php rewind_posts(); ?&gt; &lt;?php if (have_posts()) : ?&gt; &lt;?php query_posts('post_type=work&amp;posts_per_page=6');?&gt; &lt;?php while (have_posts()) : the_post(); ?&gt; &lt;div class="postitem mall floatleft mywork storm_fader"&gt; &lt;div class="postitem-img lordfade"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_post_thumbnail('type2'); ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="postitem-contentwrap"&gt; &lt;div class="postitem-txt"&gt; &lt;h6&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h6&gt; &lt;?php the_excerpt(''); ?&gt; &lt;/div&gt; &lt;div class="postitem-info"&gt; &lt;ul&gt; &lt;li&gt;&lt;span class="post-label-work"&gt;&lt;/span&gt;&lt;/li&gt; &lt;li class="spec"&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt; &lt;img src="/themachine_v4/wp-content/themes/themachine_v5_2/lib/imgs/img_gopost.jpg"&gt; &lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="postitem-shadow"&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;?php else : ?&gt; &lt;h2 class="center" style="color:#FFF;"&gt;ERROR&lt;/h2&gt; &lt;?php endif; ?&gt; </code>
You are doing so many things wrong there, for example, you should only use <code> query_posts </code> once in a template file and on the main query of the page, anything else should be done using <code> get_posts </code> or <code> WP_Query </code> . So to make you post types mingle you only need on query and you set the post type with an array: <code> &lt;?php query_posts(array('posts_per_page' =&gt; 6, 'post_type' =&gt; array('work','post'))); if (have_posts()) : while (have_posts()) : the_post(); ?&gt; &lt;div class="postitem mall floatleft myblog storm_fader"&gt; &lt;div class="postitem-img lordfade"&gt; &lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_post_thumbnail('type2'); ?&gt;&lt;/a&gt; &lt;/div&gt; &lt;div class="postitem-contentwrap"&gt; &lt;div class="postitem-txt"&gt; &lt;h6&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h6&gt; &lt;?php the_excerpt(''); ?&gt; &lt;/div&gt; &lt;div class="postitem-info"&gt; &lt;ul&gt; &lt;li&gt;&lt;span class="&lt;?php if ($post-&gt;post_type =="post"){ echo 'post-label-blog'; }else{ echo 'post-label-work'; }?&gt;"&gt;&lt;/span&gt;&lt;/li&gt; &lt;li class="spec"&gt;&lt;a href="&lt;?php the_permalink() ?&gt;"&gt; &lt;img src="/themachine_v4/wp-content/themes/themachine_v5_2/lib/imgs/img_gopost.jpg"&gt; &lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="postitem-shadow"&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; else : ?&gt; &lt;h2 class="center" style="color:#FFF;"&gt;ERROR&lt;/h2&gt; &lt;?php endif; ?&gt; </code>
Wordpress, custom post type and posts query help!
wordpress
I am facing 500.0 Internal server quite frequently with my website. The error details are given below. <code> HTTP Error 500.0 - Internal Server Error C:\PHP\php-cgi.exe - The FastCGI process exceeded configured activity timeout Module FastCgiModule Notification ExecuteRequestHandler Handler PHP_via_FastCGI Error Code 0x80070102 Requested URL http://mydomain.com:80/index.php Physical Path C:\HostingSpaces\coderefl\mydomain.com\wwwroot\index.php Logon Method Anonymous Logon User Anonymous </code> When I contacted the support team, they're saying that my site is making heavy SQL Queries. I am not sure how to debug this. But my site is very small and the database is optimized. I'm running wordpress as platform. How to resolve this issue.
Your site codereflect.com is not that heavy. Could be the Suffusion theme and its options making lots of DB calls. I'd use http://wordpress.org/extend/plugins/debug-queries/ to see what queries are being called and how many. And it also could be you're on a shared box at softlayer that is "too" shared with others.
500 internal server error
wordpress
I'm wondering if anyone here has used the jquery plugin 'fullscreenr' with a wordpress theme before. I've noticed a weird bug that I'm sure anyone who has used this before for a wordpress build would have come across.. It's a niche problem so bear with the explanation. I'll be as succinct as possible. Fullscreenr is a jQuery plugin that allows you to have a scalable fullscreen bg image. For reference: http://nanotux.com/blog/fullscreen/ The problem I'm having is a weird bug involving using html anchors that target a location that is near the bottom of the target page. This forces the BG to resize below the original window size. Everything looks great at first, but if the user attempts to scroll back up, the scrollbar gets 'stuck' and a good 200 pixels of the BG get stuck as well. You can see the scalable bg working here: http://dev.citylightphilly.com/html (try zooming out and resizing the window.) To witness the problem I'm having - click "Our Blog" (the only working link on the test page) Normally, I would say - "oh well, if I really want the scalable BG, I just won't use anchors below a certain point on the target page." However, for a wordpress blog it becomes very necessary semantically to link directly to the #respond tag for comments, which are always at the bottom of the page! Any thoughts? I don't know jQuery well enough to code in a workaround.. Help!
The plugin determines the width and height of the viewport on page load, but it's using $(window).height() which looks at the size of the viewport and then absolutely positions the content div over the image, relative to the viewport/window. Because the page isn't loading at the top of the document, the content is absolutely positioned incorrectly, and at that point, there's no way to get it back down. (The scroll bar issue is bizarre, but I guess just a side effect.) The plugin needs to check scrollPosition somehow, and adjust the dimensions accordingly. I'm still thinking about exactly how that would work... OK Smock and I just talked. Try changing the #bg div from position: absolute; to position: fixed; and see if that solves your problem. You might lose iPad functionality at that point, FYI, but it should fix the weird anchor problem. Then it's your call how to handle it. Also, we both suggest: maybe don't use this plugin if you can help it cause it's a nightmare of positioning hassles that will never stop tormenting you. :D
Using Fullscreenr with a wordpress blog - weird bug
wordpress
How can I programmatically create a connection between one custom post type, cpt, (with post id known) to another on cpt on publish? I am using VoodooPress's front-end posting method to publish a post type called post-type-A . One input field in the post-type-A form is the public inventory number, which through some wp_query love gives me the post id of the post-type-B that I wish to create a relationship with. I know that I can use this function to create a one-way connection from post-type-A to post-type-B using a custom field. <code> add_action('publish_page', 'add_custom_field_automatically'); add_action('publish_post', 'add_custom_field_automatically'); function add_custom_field_automatically($post_ID) { global $wpdb; if(!wp_is_post_revision($post_ID)) { add_post_meta($post_ID, 'field-name', 'custom value', true); } } </code> But how do I programmatically create a connection using @Scribu's Posts 2 Posts plugin? A two-way relationship would reduce a lot of hassle and programming time. :) For reference, the snippet below is the connect api reference for the plugin... <code> /** * Connect a post to another one * * @param int $post_a The first end of the connection * @param int $post_b The second end of the connection * @param bool $bydirectional Wether the connection should be bydirectional */ function p2p_connect( $post_a, $post_b, $bydirectional = false ) { add_post_meta( $post_a, P2P_META_KEY, $post_b ); if ( $bydirectional ) add_post_meta( $post_b, P2P_META_KEY, $post_a ); } </code>
Just call <code> p2p_connect( $id_of_post_type_a, $id_of_post_type_b ); </code> in the form handling code.
How to programmatically create a connection with [Plugin: Posts 2 Posts] on cpt publish?
wordpress
What I'm working on are the pages that you go to after clicking on a custom taxonomy on the front-end. I'm to the point where I've duplicated category.php, renamed it taxonomy-tr_property_region.php so that I can edit how posts with the taxonomy tr_property_region are displayed. If I understand correctly I need to edit loop.php, but I don't want taxonomy-tr_property_region.php to look the same as taxonomy-language.php is there a way to not use get_template_part( 'loop', 'category' ); Example being I want to change this <code> get_template_part( 'loop', 'category' ); </code> To be something more like this, <code> &lt;div&gt; &lt;?php $loop = whatever replaces get_template_part( 'loop', 'category' ); ?&gt; &lt;?php while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;div class="fullWidthContent"&gt; &lt;div class="trPropSearchHeader"&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt; &lt;?php $meta = get_post_meta(get_the_ID(), 'rw_propCity', true); echo $meta; ?&gt; &lt;/div&gt; &lt;div class="trPropSearchThumbnail"&gt; &lt;?php if ( has_post_thumbnail()) : ?&gt; &lt;a href="&lt;?php the_permalink(); ?&gt;" title="&lt;?php the_title_attribute(); ?&gt;" &gt; &lt;?php the_post_thumbnail('thumbnail'); ?&gt; &lt;/a&gt; &lt;?php endif; ?&gt; &lt;/div&gt; &lt;div class="trPropSearchDetailsContainer"&gt; &lt;?php $meta = get_post_meta(get_the_ID(), 'rw_propBedrooms', true); echo $meta; ?&gt; &lt;?php $meta = get_post_meta(get_the_ID(), 'rw_propBathrooms', true); echo $meta; ?&gt; &lt;?php $meta = get_post_meta(get_the_ID(), 'rw_propDesc', true); echo $meta; ?&gt; &lt;/div&gt; &lt;div class="clear"&gt;&lt;/div&gt; &lt;/div&gt; &lt;?php endwhile; ?&gt; &lt;/div&gt; </code>
This is how i would do it: why not just include another loop.php in its place, for example copy <code> loop.category.php </code> , rename it to something like <code> loop-copy.php </code> make your changes to it and call it to the template as <code> &lt;?php get_template_part( 'loop', 'copy' ); ?&gt; </code> .
Customize category page for different custom taxonomies
wordpress
It is referenced in load_template but Wp does nothing with it ?!!! so what's the use ? <code> 1105 function load_template( $_template_file, $require_once = true ) { 1106 global $posts, $post, $wp_did_header, $wp_did_template_redirect, $wp_query, $wp_rewrite, $wpdb, $wp_version, $wp, $id, $comment, $user_ID; 1107 1108 if ( is_array( $wp_query-&gt;query_vars ) ) 1109 extract( $wp_query-&gt;query_vars, EXTR_SKIP ); 1110 1111 if ( $require_once ) 1112 require_once( $_template_file ); 1113 else 1114 require( $_template_file ); 1115 } </code>
It's a global variable that can be checked by user functions and filters to see whether or not WordPress has already sent headers. It's just there to help.
What's the purpose of $wp_did_header?
wordpress
My code validates and returns the custom field value. However, I can't get the value to return inside of the anchors. Here is the code: <code> &lt;div id="meta_mblink"&gt; &lt;? if(function_exists('get_custom_field_data')) { echo '&lt;a href="'.get_custom_field_data('mblink', true).'"&gt;&lt;/a&gt;'; } ?&gt; &lt;/div&gt; </code> This is what is returned: <code> &lt;div id="meta_mblink"&gt; http://yada.yadayada.yada:5000/pop.jsp?id=1711436 &lt;a href=""&gt;&lt;/a&gt; &lt;/div&gt; </code>
This is how I would code this: <code> $url = get_post_meta( get_the_ID(), 'mblink', true ); if ( ! empty( $url ) ) { print '&lt;a href="' . esc_url( $url ) . '"&gt;MBLINK&lt;/a&gt;'; } </code>
Value prints outside of the echo
wordpress
Basically, I've got a plugin that searches for certain tokens in the entire page and replaces the tokens with images. The problem is, I've got one of those tokens in the footer and, as far as I can tell, there's no filter for the footer. So the question is, is there a way to make a custom filter? And is that the best way to go about doing this? My plugin does a preg_match in the content and, if it finds, for example "{picture here}", it replaces it. I'm not sure how to extend this functionality to the footer, though?
Most of the footer is straight-up PHP/HTML markup. You apply filters to dynamic content, which is why there isn't a typical footer "filter." That said, it's relatively easy to add your own filters to WordPress. Let's say your <code> footer.php </code> consists of the following: <code> &lt;/div&gt; &lt;!-- close main content div&gt; &lt;div id="footer"&gt; &lt;p class="copyright"&gt;Copyright 2011 By Me&lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code> And lets say you want to dynamically replace the word "copyright" with the standard C image using your filter. You'd replace this with: <code> &lt;/div&gt; &lt;!-- close main content div&gt; &lt;div id="footer"&gt; &lt;p class="copyright"&gt; &lt;?php echo apply_filters( 'my_footer_filter', 'Copyright 2011 By Me' ); ?&gt; &lt;/p&gt; &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code> This creates a custom filter called "my_footer_filter" and applies it to the text "Copyright 2011 By Me." In your <code> functions.php </code> file, you can use this filter just like you would any other: <code> function replace_copyright( $copyright ) { // do something to $copyright return $copyright; } add_filter( 'my_footer_filter', 'replace_copyright' ); </code>
Custom Filter in Wordpress to modify footer information via plugin?
wordpress
I've been searching for how to do this for a while but to no avail. Part of my template is using a lot of the same code, i.e. retrieving a specific page. If this was Javascript I'd set up a function and keep calling the function. How can I call the code below repeatedly? <code> &lt;?php $page = get_page_by_title('Excerpts Showreel'); &lt;-- This piece of code will change // the code below will never change. ?&gt; &lt;?php $my_id = $page; $post_id = get_post($my_id, ARRAY_A); $title = $post_id['post_title']; $content = $post_id['post_content']; ?&gt; &lt;?php echo $content ?&gt; </code>
You can define your own custom functions in PHP just like you would in JavaScript. Here's your code example rewritten using a function: <code> $page = get_page_by_title('Excerpts Showreel'); &lt;-- This piece of code will change // the code below will never change. function get_my_content( $page ) { $my_id = $page; $post_id = get_post($my_id, ARRAY_A); $title = $post_id['post_title']; $content = $post_id['post_content']; return $content; } echo get_my_content($page); </code> So long as you have your <code> get_my_content() </code> function defined, you can use it anywhere you need to.
How to reduce repetitive code
wordpress
My custom 'Home' page is set to sort my custom posts via the custom date field with this (updated to be custom named) code in functions.php: <code> // sort order for home page add_action('wp', 'wwgo_check_page'); function wwgo_check_page () { if (is_page()) { add_filter('get_previous_post_sort', 'sort_it'); add_filter('get_next_post_sort', 'sort_it'); add_filter('posts_orderby', 'sort_it' ); add_filter('posts_join', 'join_it' ); add_filter('posts_where', 'where_it' ); function sort_it () { global $wpdb; return " $wpdb-&gt;postmeta.meta_value ASC "; } function join_it( $join ) { global $wpdb; $join .= " LEFT JOIN $wpdb-&gt;postmeta ON($wpdb-&gt;posts.ID = $wpdb-&gt;postmeta.post_id) "; return $join; } function where_it( $where ) { global $wpdb; $where .= "AND $wpdb-&gt;postmeta.meta_key = 'deadline' "; return $where; } } } </code> Which is dandy and simple. Now. I want this to work across the whole site. I want posts on archive pages, categories etc to be sorted first by the custom date field. Any ideas? I have tried changing the ' <code> if </code> ' to <code> is_archive() </code> but that had no effect. I tried <code> &lt;! is_single()&gt; </code> too. I'm sure it should be something simple. But I'm new to php and thus clueless. Here is the site, where you can see the home page is nicely sorted, but if you click 'poetry' (the only one with a few posts), sorting doesn't work. Any suggestions will be met with much joy. Thank You Kindly.
Use the <code> query_vars </code> or request filter to add <code> orderby </code> if <code> orderby </code> is not presented in the query string
Order posts (across the whole site) by metadata date
wordpress
I'm trying to output an ordered list of the top five tags for my site into the sidebar. At the moment, I'm using <code> wp_tag_cloud </code> like this to get it to output a nice <code> &lt;ul&gt; </code> : <code> wp_tag_cloud('smallest=12&amp;largest=12&amp;orderby=count&amp;order=DESC&amp;format=list&amp;unit=px&amp;number=5'); </code> However, I'd like it to output as an <code> &lt;ol&gt; </code> instead of a <code> &lt;ul&gt; </code> . Is it possible to do this without hacking the core? Presumably via functions.php or the like? Also, in the output from <code> wp_tag_cloud </code> , the font size is being set by inline styles. Seeing as I don't need the tag cloud to actually function as a tag cloud, is there any way to simply remove all inline styling from it? Finally, if there's an easier or less convoluted way of getting an ordered list of tags, please let me know. Thanks.
one possibility: using the 'format=array' and 'echo=0' parameters; and building a foreach loop to output each tag: <code> &lt;ol&gt; &lt;?php $wptc = wp_tag_cloud('smallest=12&amp;largest=12&amp;orderby=count&amp;order=DESC&amp;format=array&amp;unit=px&amp;number=5&amp;echo=0'); foreach( $wptc as $wpt ) echo "&lt;li&gt;" . $wpt . "&lt;/li&gt;\n"; ?&gt; &lt;/ol&gt; </code>
Getting an ordered list of tags - via wp_tag_cloud or not?
wordpress
Currently I'm working on a project where site is driven by user articles, how it works: Any user goes to compose post page and writes post along with few details, has upload file option for image and then submits Post is uploaded in wordpress and the image attached is set as featured image Admin approves the post and it gets published. Here user is not required to have an account. I am using <code> wp_insert_post </code> to create a new post but not able to figure out how to add featured image via PHP.
Use the set_post_thumbnail function. <code> set_post_thumbnail( $post_ID, $thumbnail_id ); </code> Require you use WordPress 3.1.0 or later. You need call this function after you have successfully created your post via <code> wp_insert_post </code> and have a valid <code> $post_ID </code> .
Adding featured image via PHP
wordpress
Is there a way to disable update notifications for specific plugins? As a plugin developer, I have some plugins installed on my personal site using the svn trunk version for testing, but the same plugins are available from the plugin site. In these cases WP considers the latest version to be the most recently published version and constantly tries to warn me that updates are available. I still want to see notifications for updates on other plugins, but it's anoying to constantly ignore the <code> Updates (2) </code> notice in the header!
For example if you don't want Wordpress to show update notifications for akismet, you will do it like: <code> function filter_plugin_updates( $value ) { unset( $value-&gt;response['akismet/akismet.php'] ); return $value; } add_filter( 'site_transient_update_plugins', 'filter_plugin_updates' ); </code>
Disable update notification for individual plugins
wordpress
I have picked through Scribu's post very carefully and cannot determine where the issue is. Here is the code: <code> // Register the column function event_date_column_register( $columns ) { $columns['event-date'] = __( 'Event Date', 'my-plugin' ); return $columns; } add_filter( 'manage_edit-event_columns', 'event_date_column_register' ); // Display the column content function event_date_column_display( $column_name, $post_id ) { if ( 'event-date' != $column_name ) return; $event_date = get_post_meta($post_id, 'event-date', true); if ( !$event_date ) $event_date = '&lt;em&gt;' . __( 'undefined', 'my-plugin' ) . '&lt;/em&gt;'; echo $event_date; } add_action( 'manage_event_custom_column', 'event_date_column_display', 10, 2 ); // Register the column as sortable function event_date_column_register_sortable( $columns ) { $columns['event-date'] = 'event-date'; return $columns; } add_filter( 'manage_edit-event_sortable_columns', 'event_date_column_register_sortable' ); function event_date_column_orderby( $vars ) { if ( isset( $vars['orderby'] ) &amp;&amp; 'event-date' == $vars['orderby'] ) { $vars = array_merge( $vars, array( 'meta_key' =&gt; 'event-date', 'orderby' =&gt; 'meta_value', 'order' =&gt; 'asc' ) ); } return $vars; } add_filter( 'request', 'event_date_column_orderby' ); </code> I have a custom post type for Event with a custom field: event-date dates are entered: 2011/06/21 Is this something stupid I have missed or this won't do what I want? It does put the heading up at the top of the admin events list but nothing shows in each line item.
i believe the right hook for displaying the actual column content (each line) is <code> manage_{$post_type}_posts_custom_column </code> so change in your code: <code> add_action( 'manage_event_custom_column', 'event_date_column_display', 10, 2 ); </code> to: <code> add_action( 'manage_event_posts_custom_column', 'event_date_column_display', 10, 2 ); </code>
sortable columns on a custom post type won't work
wordpress
I'm creating a theme where i want it to have different widgets and plugins. Each plugin would ideally have it's own css file. However, this approach is not so good because i can end up having multiple files included in my header. Is there an approach where i can sort of cache all different css files in a single one upon the first user request and then just use that ?
Yes: put them all in a function, and then enqueue that function at the <code> wp_enqueue_scripts </code> hook. That way, you can define the CSS dynamically (e.g. based on Theme option settings), and let WordPress output it in the document head.
Combining CSS files into a single cached one
wordpress
When I add content to a page as the original admin user, I can past in the following code and it saves fine (old google search set up by another user): <code> &lt;form action="http://www.google.com/cse" enctype="application/x-www-form-urlencoded" id="searchbox_001294947689528032268:0gmklvjoyzm" method="get"&gt; &lt;input name="cx" type="hidden" value="001294947689528032268:0gmklvjoyzm" /&gt; &lt;input name="q" size="40" type="text" /&gt; &lt;input name="sa" type="submit" value="Search" /&gt; &lt;input name="cof" type="hidden" value="FORID:0" /&gt; &lt;/form&gt; &lt;p&gt; &lt;script src="http://www.google.com/coop/cse/brand?form=searchbox_001294947689528032268%3A0gmklvjoyzm" type="text/javascript"&gt;&lt;/script&gt; &lt;/p&gt; </code> Unfortunately other users that I created on the same site, set as administrators can paste in the same code on a page, but as soon as they hit update, wordpress strips the above code and only inserts: <code> &lt;form action="http://www.google.com/cse" enctype="application/x-www-form-urlencoded" method="get"&gt; &lt;/form&gt; &lt;p&gt;&lt;/p&gt; </code> Why is it stripping content from other users with the administrator role, but not the original admin user?
Super Admins have different privileges than other admins. By default WordPress strips out a lot of html tags from all users by the super admin. (Assuming that the super admin must be trusted, but most users should not be trusted by default to put in iframes, inputs and other such lovely tags.
Wordpress stripping html and script tags from some admin users on save
wordpress
So I know that _x() and it's wrappers allow a developer to specify the context of a translated string. I'm pretty clear on "how" to use this function as well as "why" it should be used. I am wondering how this function is helpful to people who perform translations. Poedit does not seem to treat it any differently. Does use of this function aid in translation? Is there a way for translators to somehow see the context during the translation process?
When using other translation tools (other then poedit) like GlotPress you can see the context in which the string for translation is called upon.
The effect of x() family of functions
wordpress
I have developed a custom script that uses <code> wp_insert_post </code> to create new posts, however i'd like to use similar code to create the same data in another wp database. Could be this done on the fly before insertion? For example instruct wordpress to point another database and then insert data? Or should I do this "manually" using raw mySQL code?
You could avoid SQL altogether and use the XML-RPC API. This would also let you post to remote wordpress installs too. ( note if XML-RPC is not an option, scroll further down ) If Using XML-RPC Here's some code from a quick google search using XML-RPC to post to a remote Wordpress blog: http://en.forums.wordpress.com/topic/great-code-for-remote-posting?replies=5 Here's a simpler set of examples with an explanation of the XML-RPC APIs http://life.mysiteonline.org/archives/161-Automatic-Post-Creation-with-Wordpress,-PHP,-and-XML-RPC.html And here's an example from WP-Recipes using Curl and XML-RPC: http://www.wprecipes.com/post-on-your-wordpress-blog-using-php <code> function wpPostXMLRPC($title,$body,$rpcurl,$username,$password,$category,$keywords='',$encoding='UTF-8') { $title = htmlentities($title,ENT_NOQUOTES,$encoding); $keywords = htmlentities($keywords,ENT_NOQUOTES,$encoding); $content = array( 'title'=&gt;$title, 'description'=&gt;$body, 'mt_allow_comments'=&gt;0, // 1 to allow comments 'mt_allow_pings'=&gt;0, // 1 to allow trackbacks 'post_type'=&gt;'post', 'mt_keywords'=&gt;$keywords, 'categories'=&gt;array($category) ); $params = array(0,$username,$password,$content,true); $request = xmlrpc_encode_request('metaWeblog.newPost',$params); $ch = curl_init(); curl_setopt($ch, CURLOPT_POSTFIELDS, $request); curl_setopt($ch, CURLOPT_URL, $rpcurl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 1); $results = curl_exec($ch); curl_close($ch); return $results; ?&gt; </code> If afterall that XML-RPC is not for you Perhaps a wordpress multisite might be best for you? Creating the new post would be as simple as calling <code> switch_to_blog($blog_id); </code> then doing your business creating the new post, before calling <code> restore_current_blog(); </code> If you MUST use SQL Use stackexchange-url ("this question linked to") by mike23 in order to gain access via a wpdb object
Insert post in another database
wordpress
How can i get taxonomies of a post type? If I have a post type <code> event </code> and i need to find out the list of taxonomies that are attached to that post type. How do I find them?
Hey guys i think i got it! After looking at couple of functions in taxonomy.php file in wordpress i have found this function <code> get_object_taxonomies(); </code> which did the tricks :) Here is the function <code> function get_post_taxonomies($post) { // Passing an object // Why another var?? $output = 'objects'; // name / objects $taxonomies = get_object_taxonomies($post, 'objects'); /*// Passing a string using get_post_type: return (string) post, page, custom... $post_type = get_post_type($post); $taxonomies = get_object_taxonomies($post_type, 'objects');*/ /*// In the loop with the ID $theID = get_the_ID(); $post_type = get_post_type($theID); $taxonomies = get_object_taxonomies($post_type, 'objects');*/ // You can also use the global $post // edited to fix previous error $tazonomies // edited to force type hinting array return (array) $taxonomies; // returning array of taxonomies } </code>
How to get all taxonomies of a post type?
wordpress
I have a function to instantiate a class to provide var access to other functions. <code> function my_data(){ global $post,$the_data; $postid = get_the_ID(); $the_data = new MY_Class ( $postid ); return $the_data; } </code> This function will be called by every post, and each post will call it many times whenever need a var from MY_Class. The data is saved in WordPress postmeta and retrived in My_Class. Does WP automatically cache the object, or should I find a way to cache it? How?
If you use the WordPress API to retrieve the metadata, then it should be cached for you. If you do other complex stuff, there is the Transients API for caching data yourself, which will take advantage of whatever object cache you use with WordPress. EDIT - I should clarify, it'll be loaded for each request unless you use some sort of caching plugin, though it should load only once for each request.
Is the object cached?
wordpress
I'm creating a website using Wordpress. Users are registering on it as "Subscribers". When you register, you have a small panel with some custom info on it (that I made, creating a custom template) Each user shouldn't know other users exist. I started developing this without knowing if when registered users are available "to the world" (google indexing them, for example). Is user registration data is publicy available in a Wordpress installation, by some url, perhaps? Can Anonymous users see registered ones, or can Registered Ones see all others registered ones? Where I can get this information on wordpress docs? Are registered users on Wordpress supposed to be available to all? I couldn't get any information about this. Can someone help?
No, user data is not visible to the outside world, or to google, unless you specifically make it visible in the theme somehow. One piece of user data is exposed for authors of posts though. Specifically, their login names are visible in many places.
Is user listing on wordpress private?
wordpress
Any ideas how to accomplish this? Something like this would work, but if there are threaded comments you get the wrong number, because pages with threaded comments have actually more comments than the <code> comments_per_page </code> setting: <code> $c_page = get_query_var('cpage'); $c_per_page = get_query_var('comments_per_page'); $number = ($c_page * $c_per_page) - $c_per_page + $current_c_index; </code> ( <code> $current_c_index </code> is a global variable storing comment count for the current page loop) Later edit: A partial solution is to extend the Walker_Comment class, do a clone of the paged_walk() function in which you increase the counter within the <code> $top_elements </code> loop. But still that doesn't count child comments :(
Try the following custom Comment Walker class. The walker keep tracks for print index in a global variable named <code> $current_comment_print_index </code> ; which is intialized in the <code> paged_walk </code> function. You can print global variable <code> $current_comment_print_index </code> to show the current printed comment number. <code> &lt;?php /* Plugin Name: Comment Count Walker for WPSE 20527 Author: Hameedullah Khan Author URI: http://hameedullah.com Version: 0.1 */ class CC_Custom_Walker_Comment extends Walker_Comment { function paged_walk( $elements, $max_depth, $page_num, $per_page ) { global $current_comment_print_index; $current_comment_print_index = 0; /* sanity check */ if ( empty($elements) || $max_depth &lt; -1 ) return ''; $args = array_slice( func_get_args(), 4 ); $output = ''; $id_field = $this-&gt;db_fields['id']; $parent_field = $this-&gt;db_fields['parent']; $count = -1; if ( -1 == $max_depth ) $total_top = count( $elements ); if ( $page_num &lt; 1 || $per_page &lt; 0 ) { // No paging $paging = false; $start = 0; if ( -1 == $max_depth ) $end = $total_top; $this-&gt;max_pages = 1; } else { $paging = true; $start = ( (int)$page_num - 1 ) * (int)$per_page; $end = $start + $per_page; if ( -1 == $max_depth ) $this-&gt;max_pages = ceil($total_top / $per_page); } // flat display if ( -1 == $max_depth ) { if ( !empty($args[0]['reverse_top_level']) ) { $elements = array_reverse( $elements ); $oldstart = $start; $start = $total_top - $end; $end = $total_top - $oldstart; } if ( $paging ) { // HK: if paging enabled and its a flat display. // HK: mark the current print index from page number * comments per page $current_comment_print_index = ( (int) $page_num - 1 ) * $per_page; } $empty_array = array(); foreach ( $elements as $e ) { $count++; if ( $count &lt; $start ) continue; if ( $count &gt;= $end ) break; $this-&gt;display_element( $e, $empty_array, 1, 0, $args, $output ); } return $output; } /* * separate elements into two buckets: top level and children elements * children_elements is two dimensional array, eg. * children_elements[10][] contains all sub-elements whose parent is 10. */ $top_level_elements = array(); $children_elements = array(); foreach ( $elements as $e) { if ( 0 == $e-&gt;$parent_field ) $top_level_elements[] = $e; else $children_elements[ $e-&gt;$parent_field ][] = $e; } $total_top = count( $top_level_elements ); if ( $paging ) $this-&gt;max_pages = ceil($total_top / $per_page); else $end = $total_top; if ( !empty($args[0]['reverse_top_level']) ) { $top_level_elements = array_reverse( $top_level_elements ); $oldstart = $start; $start = $total_top - $end; $end = $total_top - $oldstart; } if ( !empty($args[0]['reverse_children']) ) { foreach ( $children_elements as $parent =&gt; $children ) $children_elements[$parent] = array_reverse( $children ); } foreach ( $top_level_elements as $e ) { $count++; // HK: current iteration index, will be added to global index // NOTE: will only be added to global index if already printed $iteration_comment_print_index = 1; // HK: count of current iteration children ( includes grand children too ) $iteration_comment_print_index += $this-&gt;count_children( $e-&gt;comment_ID, $children_elements ); //for the last page, need to unset earlier children in order to keep track of orphans if ( $end &gt;= $total_top &amp;&amp; $count &lt; $start ) $this-&gt;unset_children( $e, $children_elements ); if ( $count &lt; $start ) { // HK: if we have already printed this top level comment // HK: then just add the count (including children) to global index and continue $current_comment_print_index += $iteration_comment_print_index; continue; } if ( $count &gt;= $end ) break; $this-&gt;display_element( $e, $children_elements, $max_depth, 0, $args, $output ); } if ( $end &gt;= $total_top &amp;&amp; count( $children_elements ) &gt; 0 ) { $empty_array = array(); foreach ( $children_elements as $orphans ) foreach( $orphans as $op ) $this-&gt;display_element( $op, $empty_array, 1, 0, $args, $output ); } return $output; } function display_element( $element, &amp;$children_elements, $max_depth, $depth=0, $args, &amp;$output ) { global $current_comment_print_index; if ( !$element ) return; // increment for current comment we are printing $current_comment_print_index += 1; parent::display_element( $element, $children_elements, $max_depth, $depth, $args, $output ); } function count_children( $comment_id, $children_elements ) { $children_count = 0; if ( isset( $children_elements[$comment_id] ) ) { $children_count = count( $children_elements[$comment_id] ); foreach( $children_elements[$comment_id] as $child ) { $children_count += $this-&gt;count_children( $child-&gt;comment_ID, $children_elements ); } } return $children_count; } } ?&gt; </code>
Getting the comment number relative to all the post's comments
wordpress
I'm using the following code to produce a different TinyMCE bar to the default WordPress setup: <code> if (function_exists('wp_tiny_mce')) { add_filter("mce_external_plugins", "add_myplugin_tinymce_plugin"); add_filter('mce_buttons', 'register_myplugin_button'); add_filter('teeny_mce_before_init', create_function('$a', ' $a["theme"] = "advanced"; $a["skin"] = "wp_theme"; $a["height"] = "75"; $a["width"] = "800"; $a["onpageload"] = ""; $a["mode"] = "exact"; $a["elements"] = "elm1, elm2"; $a["editor_selector"] = "mceEditor"; $a["plugins"] = "safari,inlinepopups,spellchecker"; $a["forced_root_block"] = false; $a["force_br_newlines"] = true; $a["force_p_newlines"] = false; $a["convert_newlines_to_brs"] = true; return $a;')); wp_tiny_mce(true); } </code> Can anyone tell me how to work a basic custom button in there? All I need is a straightforward button which prints [ph_min] into the editor area. I've tried using the following filters to no avail: <code> function register_tcustom_button($buttons) { array_push($buttons, "|", "highlight"); return $buttons; } function add_tcustom_tinymce_plugin($plugin_array) { $plugin_array['highlight'] = WP_PLUGIN_URL . '/sf-tinyMCE-custom-buttons/mce/min_max_buttons/editor_plugin.js'; return $plugin_array; } add_filter("mce_external_plugins", "add_tcustom_tinymce_plugin"); add_filter('mce_buttons', 'register_tcustom_button'); </code> Is there any way of doing this, or will I have to use write a manual TinyMCE init which isn't supported by WP?
I believe that you have already registered your shortcode. Now what we need to do is to initiate the Button. Once the shortcode is registered [ph_min] let's check if user can use rich editing: <code> function add_highlight_button() { if ( ! current_user_can('edit_posts') &amp;&amp; ! current_user_can('edit_pages') ) return; if ( get_user_option('rich_editing') == 'true') { add_filter('mce_external_plugins', 'add_tcustom_tinymce_plugin'); add_filter('mce_buttons', 'register_tcustom_button'); } } add_action('init', 'add_highlight_button'); </code> Now lets register the button <code> function register_tcustom_button( $buttons ) { array_push( $buttons, "|", "highlight" ); return $buttons; } </code> Now let's register TinyMCE plugin <code> function add_tcustom_tinymce_plugin( $plugin_array ) { $plugin_array['mylink'] = get_bloginfo( 'template_url' ) . '/script/mybuttons.js'; return $plugin_array; } </code> And this is for the JS file called from the previous function: <code> (function() { tinymce.create('tinymce.plugins.highlight', { init : function(ed, url) { ed.addButton('highlight', { title : 'Highlight', image : url+'/yourlink.png', onclick : function() { ed.selection.setContent('[ph_min]'); } }); }, createControl : function(n, cm) { return null; }, }); tinymce.PluginManager.add('highlight', tinymce.plugins.highlight); })(); </code> That's about it.
Adding TinyMCE custom buttons when using teeny_mce_before_init
wordpress
I have a simple contact form using CONTACT FORM 7 PLUGIN on a page on my site. I want user to be able to download a video file only after he/she fills out the form and the form submission is successful. How do i check whether the form is successfully submitted so that I can then put in the code for force download of the file?
In Additional Settings, use <code> on_sent_ok: "location = 'http://example.com/';" </code> to redirect to another page, but as said above, it's not that secure. You can hide the page via robots.txt.
Wordpress Contact Form 7
wordpress
In the WP menu creation GUI there's the <code> Automatically add top level pages </code> option. I would like to do the opposite, for any page that is in the menu, automatically add it's child pages. Is there a way to do that ?
Simply put: no. If you want dynamic updating of your menu items, you would probably be better-served using <code> wp_list_pages() </code> or <code> wp_page_menu() </code> .
How can I automatically add child pages to pages in a WP menu?
wordpress
I have a post with audio player with autostart enabled, and i decided to put it in the beginning of the post, before putting "read more" excerpt feature. So the problem is, that audio player plays music on the main page, but i want it to work only on post page. Is it possible to do? I've put my post in drafts for now, until i solve this little problem...
The simplest solution would be to put the audio player after the read-more link. If that would prove cumbersome (e.g. you've already got too may posts with audio players), you could try hooking into the <code> the_content </code> filter, and remove the audio player if not on a single-post view. e.g.: <code> function mytheme_remove_audio_player_from_home( $content ) { // is_singular() is true for // single posts, pages, and attachments if ( ! is_singular() ) { // do something, such as a str_replace() or // whatever else would be appropriate, to // filter out the audio player markup } return $content; } add_filter( 'the_content', 'mytheme_remove_audio_player_from_home' ); </code>
How to disable "Audio Player" to show up on the main page
wordpress
I have 3 custom post types each of these CPT's have posts that are set to auto delete via a given time scale by cron jobs, thing is when they are deleted it leaves behind orphaned taxonomy terms in dropdowns etc, needless to say when these are clicked it goes to a "quack quack oops 404 error", i can find sql queries to run for orphaned tags, but there seems to be very little (infact i have found nothing at all) that pertains to taxonomy terms, anubody have any ideas on this? More Info All my terms are pre-assigned to the taxonomies and are listed in wp_terms table, the reason they are pre-assigned is that authors choose them from option menus when creating a new post, so all un-attached (un-used terms) still need to stay in the wp_terms table for later inclusion, the tables i need to be getting info from to run the delete query are wp_terms_taxonomy, wp_terms_relationships and wp_posts to look for a match of a NULL post id and thats the part what stumps me. I am showing the terms for selection via Scribus Query Multiple Taxonomies plugin. UPDATE: From theDeadMedics answer below im deducing that i can do something on the lines of: <code> &lt;?php require_once 'wp-load.php'; global $wpdb; $expireds = $wpdb-&gt;get_results("SELECT ID, post_title FROM $wpdb-&gt;posts WHERE post_type = 'sales' AND HOUR(TIMEDIFF(NOW(), post_date_gmt)) &gt;=4321 "); foreach ($expireds as $expired) { wp_delete_post( $post-&gt;ID, true ); } ?&gt; </code> LAST UPDATE i see a couple of folks have set this as a favourite, below is a full working query that will delete time expired posts (and all meta associated with that post) set to a "n"th number of hours after post_date_gmt. In the code below <code> &gt;=2 </code> denotes delete posts 1 hour old, the number of hours you wish to set for delete should always be plus 1. <code> &lt;?php require_once 'wp-load.php'; global $wpdb; $expireds = $wpdb-&gt;get_results("SELECT ID, post_title FROM $wpdb-&gt;posts WHERE post_type = 'sales' AND HOUR(TIMEDIFF(NOW(), post_date_gmt)) &gt;=1"); foreach ($expireds as $post) { wp_delete_post( $post-&gt;ID, false ); } ?&gt; </code> Regards
You shouldn't need to use a custom SQL query - stick to the built-in method <code> wp_delete_post() </code> . This will also clear out all term relationships too.
orphaned taxonomy terms remove by sql query
wordpress
Has anyone come across any good reviews/comparisons of gravity forms and formidable pro? I am trying to find more information on both. I have a couple of sites that need several forms for adding items to our physical collections, leave requests and reserving specific rooms and resources and the like. I need something that will email form submissions as well as store entries in a database and which I can use to generate reports. Any information or personal experience with either of these or other options would be much appreciated.
I've just begun using Gravity Forms but I've used Formidable quite a lot. My biggest complaints about Formidable is the way it handles upgrades. If you have a 'Pro' account, when an upgrade is available you have to go through a multi-step, not very intuitive upgrade process every time. Other than that, so far Formidable has worked very well for me. It doesn't have all the 'extras' that Gravity Forms seems to offer, like MailChimp integration, but that hasn't been that big a deal. And, it's far cheaper in the long term with a one-time, unlimited license for $99 (when I bought). Gravity Forms makes you renew every year or lose support.
Comparing formidable pro and gravity forms
wordpress
I have to insert posts programatically in Wordpress. I want that I should be able to publish posts via a url. Something like www.mypage.com/insertnewpost.php?title=blah&amp;content=blahblahblah&amp;category=1,2,3 The following code works only if I use it inside the functions.php file of the themes. <code> include '../../../wp-includes/post.php'; global $user_ID; $new_post = array( 'post_title' =&gt; 'My New Post', 'post_content' =&gt; 'Lorem ipsum dolor sit amet...', 'post_status' =&gt; 'publish', 'post_date' =&gt; date('Y-m-d H:i:s'), 'post_author' =&gt; $user_ID, 'post_type' =&gt; 'post', 'post_category' =&gt; array(0) ); $post_id = wp_insert_post($new_post); </code> However when I try to create a new page like insertnewposts.php and use the above code there I get errors like Fatal error: Call to undefined function add_action() in Z:\www\wordpress\wp-includes\post.php on line 144 Please help.
I finally got the answer to the problem. To make this code work: <code> global $user_ID; $new_post = array( 'post_title' =&gt; 'My New Post', 'post_content' =&gt; 'Lorem ipsum dolor sit amet...', 'post_status' =&gt; 'publish', 'post_date' =&gt; date('Y-m-d H:i:s'), 'post_author' =&gt; $user_ID, 'post_type' =&gt; 'post', 'post_category' =&gt; array(0) ); $post_id = wp_insert_post($new_post); </code> we need to make sure that wordpress' bootstrap has been started... Wordpress bootstrap ensures that all wordpress configuration has been loaded into the memory. This includes all the core functions etc. Coming back to the original problem of "inserting posts programatically", we need to call wp_insert_post() at the appropriate place after starting the wp bootstrap. For this create a new php file like www.yourdomain.com/wpinstalldir/autoposts.php <code> &lt;?php /** * Writes new posts into wordpress programatically * * @package WordPress */ /** Make sure that the WordPress bootstrap has run before continuing. */ require(dirname(__FILE__) . '/wp-load.php'); global $user_ID; $new_post = array( 'post_title' =&gt; 'My New Post', 'post_content' =&gt; 'Lorem ipsum dolor sit amet...', 'post_status' =&gt; 'publish', 'post_date' =&gt; date('Y-m-d H:i:s'), 'post_author' =&gt; $user_ID, 'post_type' =&gt; 'post', 'post_category' =&gt; array(0) ); $post_id = wp_insert_post($new_post); ?&gt; </code> Now when you will execute this script at www.yourdomain.com/wpinstalldir/autoposts.php your post will be created. Easy and simple! Just adding the line <code> require(dirname(__FILE__) . '/wp-load.php'); </code> made all the difference.
wordpress inserting posts programatically through a url
wordpress
I Installed Recent Posts Plugin in my Wordpress site.It Shows Correct Answer but it Shows "Recent Post" at Header position.I don't want that text. Unfortunately i can't remove that.please help me ...Is there any other php coding Available?
Ah gotcha. Either you can use a different plugin that allows you to leave the title blank, or using the default Recent Posts widget type a single blank space in the Title area and click Save. That way the title will show as blank. Hope this helps! Michelle
How to Get Recent 5 post in My Title bar?
wordpress
What should be taken care of while coding a mobile theme as compared to a simple one? Is there any tutorial available that teaches how to develop a mobile theme from scratch?
It's really not a "wordpress" specific, it's just the css. You just give it a css for mobile browsers. That's it. here are few good readings on how to get about the css for mobile: http://www.html5rocks.com/en/mobile/mobifying.html http://net.tutsplus.com/tutorials/html-css-techniques/responsive-web-design-a-visual-guide/ if you still have some questions, feel free to ask. ;)
How does a mobile WordPress theme differ from a simple theme?
wordpress
I have a custom post type, called 'job', and I have the following templates in my theme: single-job.php (works fine, displays single job as expected) archives-job.php (is not recognized?) archives-current.php (also not recognized) archives.php (is not recognized either?) index.php (archives page uses this page) Here is how I've registered my custom content type in functions.php: <code> add_action( 'init', 'create_jobs' ); function create_jobs() { $labels = array( 'name' =&gt; _x('Jobs', 'post type general name'), 'singular_name' =&gt; _x('Job', 'post type singular name'), 'add_new' =&gt; _x('Add New', 'Job'), '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; '' ); $supports = array('title', 'editor', 'custom-fields', 'revisions', 'excerpt'); register_post_type( 'Job', array( 'labels' =&gt; $labels, 'public' =&gt; true, 'has_archive' =&gt; 'current', 'supports' =&gt; $supports ) ); } </code> When i go to the url http://mywebsite/wordpress/current/, it displays all of my jobs as expected-- but it is not using ANY of the archive templates, and instead uses index.php. My understanding of the wordpress documentation was that it would look for archives-(special archive for post type name).php, then archives-(post type).php, then archives.php, then index.php... but it just goes straight to index.php? I did visit the permalinks settings page and clicked save to refresh everything, so I'm not getting 404's, it's just not outputting to the correct templates... did I name them incorrectly? Is there a registration setting I missed when I created my custom post type?
try <code> 'has_archive' =&gt; 'true'; </code> and do the permalink reset before testing! and it should be singular archive-job.php rather than archives -job.php
Custom Post Type Template - Archive
wordpress
I am trying to enqueue/print scripts in the admin area. But they dont seem to appear. <code> add_action('admin_init', function() { add_meta_box('portfolio-meta', 'Details', 'portfolio_metabox_details', 'portfolio'); wp_register_script('jqeury-validate', 'http://ajax.aspnetcdn.com/ajax/jquery.validate/1.8.1/jquery.validate.min.js'); wp_enqueue_script('jquery-validate'); wp_register_script('ae-admin', get_bloginfo('template_directory') . '/js/admin.js', array('jquery', 'jquery-validate')); wp_enqueue_script('ae-admin'); wp_localize_script('ae-admin', 'WpAjax', array( 'AjaxUrl' =&gt; admin_url('admin-ajax.php') )); wp_register_style('ae-validate', get_bloginfo('template_directory') . '/css/validate.css'); wp_enqueue_style('ae-validate'); }); </code> But my script ( <code> admin.js </code> ) does not seem to get printed. I even tried to put those in 'init' instead of 'admin_init' still I dont see my scripts ... why is that? How can I debug?
Use the <code> admin_enqueue_scripts </code> hook instead of <code> admin_init </code> Note: you should use hooks that target admin pages as specifically as possible. e.g.: Plugins : Use the <code> admin_print_scripts-{plugin-page} </code> hook Themes : Use the <code> admin_print_scripts-{theme-page} </code> hook (where <code> {theme-page} </code> is whatever string you use in the <code> add_theme_page() </code> call) Custom Post-Type Edit Page : Use the <code> admin_print_scripts-edit.php </code> hook, For Custom Post Types, inside your function, do something like the following: <code> global $typenow; if( 'portfolio' == $typenow ) { // wp_enqueue_script() calls go here } </code> (h/t stackexchange-url ("t31os"))
Why are admin scripts not printed
wordpress
this is my function : <code> $prefix = 'dbt_'; $meta_box = array( 'id' =&gt; 'my-meta-box', 'title' =&gt; 'Custom meta box', 'page' =&gt; 'post', 'context' =&gt; 'normal', 'priority' =&gt; 'high', 'fields' =&gt; array( array( 'name' =&gt; 'Checkbox', 'id' =&gt; $prefix . 'checkbox', '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); } } } </code> i try to use this code in my template if check box checked : <code> &lt;?php if ($meta_box = get_post_meta($post-&gt;ID, "checkbox", true) ) : ?&gt; Show this when checkbox checked &lt;?php endif; ?&gt; </code> And it doesnt work
Your missing the prefix: Make sure you call <code> global $prefix </code> after your query and use <code> $prefix.'checkbox' </code> to your <code> get_post_meta </code> <code> &lt;?php if ($meta_box = get_post_meta($post-&gt;ID, $prefix.'checkbox', true) ) : ?&gt; Show this when checkbox checked &lt;?php endif; ?&gt; </code>
How can i use this meta box function in my template ? (Wordpress)
wordpress