question
stringlengths 0
34.8k
| answer
stringlengths 0
28.3k
| title
stringlengths 7
150
| forum_tag
stringclasses 12
values |
---|---|---|---|
As the title says, if a single dash is used with a space between each side eg. 'Die Hard - Action Film' is written in to a WordPress post, once published it comes out as 'Die Hard -- Action Film'. If no spaces are used around the dash it works, but obviously this isn't desired. I've obviously found out it's not something that happens with a default install of Wordpress but I can't seem to pinpoint what the cause is in my theme.
|
It's lines 396 - 398 in the smart youtube plugin's <code> smartyoutube.class.php </code> file: <code> function check($the_content, $side = 0) { if (strpos($the_content, "httpv") !== false ) { $char_codes = array('&#215;', '&#8211;'); // <-- 8211 is an en dash $replacements = array("x", "--"); // <-- here's where it's swapping in -- $the_content = str_replace($char_codes, $replacements, $the_content); // <-- </code>
|
Single dash converted to double dash
|
wordpress
|
We are looking into creating a solution that allows user to contribute media files by filling out a form (without access to the admin) and have it ןד created as a custom post type. The files will be either YouTube Movies, PowerPoint Files etc. Is that possible at all? Do you know any example of something similar?
|
Yes, this is pretty easy using something like Gravity Forms
|
user contributed content as custom post types
|
wordpress
|
I have the following custom function to replace the <code> gallery_shortcode </code> function from core. It hooks in at the beginning and works. The problem is that I can't get my custom key/values from the gallery shortcode in there. I receive them in the core function, but they don't get passed into my custom function. I can't really investigate what's going wrong or where they get missing, because i don't get any <code> print_r </code> output for <code> $attr </code> inside my custom function. Any ideas? Note: I added comments for everything I changed from the core to my custom function. <code> function modified_post_gallery( $attr ) { // I can't get any output from the following echo '<pre>'; print_r( $attr ); echo '</pre>'; // But: i get the expected output if i place the same line inside the core function: /root/wp-include/media.php line 759 and get the actual output including all custom key/values. global $post, $wp_locale; static $instance = 0; $instance++; $output = ''; // We're trusting author input, so let's at least make sure it looks like a valid orderby statement if ( isset( $attr['orderby'] ) ) { $attr['orderby'] = sanitize_sql_orderby( $attr['orderby'] ); if ( ! $attr['orderby'] ) unset( $attr['orderby'] ); } // extract result from user input & defaults extract( shortcode_atts( array( 'order' => 'ASC' ,'orderby' => 'menu_order ID' ,'id' => $post->ID ,'itemtag' => 'span' // CHANGED ,'icontag' => 'span' // CHANGED ,'captiontag' => 'span' // CHANGED ,'columns' => 3 ,'size' => 'thumbnail' ,'include' => '' ,'exclude' => '' ,'class' => '' // ADDED ,'test' ), $attr ) ); $id = intval( $id ); if ( 'RAND' == $order ) $orderby = 'none'; if ( !empty( $include ) ) { $include = preg_replace( '/[^0-9,]+/', '', $include ); $_attachments = get_posts( array( 'include' => $include ,'post_status' => 'inherit' ,'post_type' => 'attachment' ,'post_mime_type' => 'image' ,'order' => $order ,'orderby' => $orderby ) ); $attachments = array(); foreach ( $_attachments as $key => $val ) { $attachments[$val->ID] = $_attachments[$key]; } } elseif ( !empty( $exclude ) ) { $exclude = preg_replace( '/[^0-9,]+/', '', $exclude ); $attachments = get_children( array( 'post_parent' => $id ,'exclude' => $exclude ,'post_status' => 'inherit' ,'post_type' => 'attachment' ,'post_mime_type' => 'image' ,'order' => $order ,'orderby' => $orderby ) ); } else { $attachments = get_children( array( 'post_parent' => $id ,'post_status' => 'inherit' ,'post_type' => 'attachment' ,'post_mime_type' => 'image' ,'order' => $order ,'orderby' => $orderby ) ); } // No attachments, so abort if ( empty( $attachments ) ) return ''; // RSS/Atom if ( is_feed() ) { $output = "\n"; foreach ( $attachments as $att_id => $attachment ) $output .= wp_get_attachment_link( $att_id, $size, true )."\n"; return $output; } $itemtag = tag_escape( $itemtag ); $captiontag = tag_escape( $captiontag ); $columns = intval( $columns ); $itemwidth = $columns > 0 ? floor( 100/$columns ) : 100; $float = is_rtl() ? 'right' : 'left'; $selector = 'gallery-'.$instance; $gallery_div = ''; $size_class = sanitize_html_class( $size ); $gallery_div = '<div id="'.$selector.'" class="gallery galleryid-'.$id.' gallery-columns-'.$columns.' gallery-size-'.$size_class.'">'; $i = 0; foreach ( $attachments as $id => $attachment ) { $class = $columns > 0 && ++$i % $columns == 0 ? ' last' : ''; // ADDED for the single item/image $link = isset( $attr['link'] ) && 'file' == $attr['link'] ? wp_get_attachment_link( $id, $size, false, false ) : wp_get_attachment_link( $id, $size, true, false ); $output .= '<'.$itemtag.' class="gallery-item '.$class.'">'; // ADDED class $output .= '<'.$icontag.' class="gallery-icon">'.$link.'</'.$icontag.'>'; if ( $captiontag && trim($attachment->post_excerpt) ) { $output .= '<'.$captiontag.' class="wp-caption-text gallery-caption">'; $output .= wptexturize( $attachment->post_excerpt ); $output .= '</'.$captiontag.'>'; } $output .= '</'.$itemtag.'>'; } $output .= ''."\n"; return $output; } add_filter( 'post_gallery', 'modified_post_gallery', 10, 2 ); </code>
|
<code> <?php function modified_post_gallery( $blank = NULL, $attr ) { echo '<pre>'; print_r( $attr ); echo '</pre>'; } add_filter( 'post_gallery', 'modified_post_gallery', 10, 2); ?> </code> In media.php it shows the filter like this: <code> // Allow plugins/themes to override the default gallery template. $output = apply_filters('post_gallery', '', $attr); </code> Its passing two variables not one and $attr is on the second variable.
|
Replacement for gallery_shortcode function not taking all attributes
|
wordpress
|
Is there a plugin available that does for custom fields what stackexchange-url ("Scribu")'s excellent Taxonomy Drill-Down (formerly called Query Multiple Taxonomies) does for taxonomies?
|
I used to have a plugin that did exactly this. It was called Custom Field Taxonomies. Then custom taxonomies happened: http://scribu.net/wordpress/custom-field-taxonomies/change-of-direction.html That said: http://wordpress.org/extend/plugins/query-custom-fields/ Let me know if you would like to adopt it.
|
Plugin similar to Taxonomy Drill-Down for custom fields?
|
wordpress
|
Golden Apples Design created (as far as I know) the media upload function that many people on WP.A and elsewhere seem to recommend. But all of the Q&As I can find on StackExchange deal with creating an entirely new post. What is the best way to get this (or another snippet) to upload media from the front-end, attach it to the current post, generate the appropriate thumbnails, and then refresh the page showing the new image in the [gallery]? Here is Than's code: In functions file... <code> function insert_attachment($file_handler,$post_id,$setthumb='false') { // check to make sure its a successful upload if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false(); require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); $attach_id = media_handle_upload( $file_handler, $post_id ); if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id); return $attach_id; </code> In page template header... <code> // set $post_id to the id of the post you want to attach // these uploads to (or 'null' to just handle the uploads // without attaching to a post) if ($_FILES) { foreach ($_FILES as $file => $array) { $newupload = insert_attachment($file,$post_id); // $newupload returns the attachment id of the file that // was just uploaded. Do whatever you want with that now. } } </code> Upload form used... <code> <form method="post" action="#" enctype="multipart/form-data" > <input type="file" name="an_uploaded_attachment"> <input type="file" name="another_uploaded_attachment"> <input type="file" name="yet_another_uploaded_attachment"> <input type="submit"> <form> </code>
|
@AboSami actually stackexchange-url ("answered this question") in an older post that was not showing up in my search diligence. While he was actually looking for something else his example code worked great. Here's the script: <code> <?php $post_id = $post->ID; if ( isset( $_POST['html-upload'] ) && !empty( $_FILES ) ) { require_once(ABSPATH . 'wp-admin/includes/admin.php'); $id = media_handle_upload('async-upload', $post_id); //post id of Client Files page unset($_FILES); if ( is_wp_error($id) ) { $errors['upload_error'] = $id; $id = false; } if ($errors) { echo "<p>There was an error uploading your file.</p>"; } else { echo "<p>Your file has been uploaded.</p>"; } } ?> <form id="file-form" enctype="multipart/form-data" action="<?php echo $_SERVER['REQUEST_URI']; ?>" method="POST"> <p id="async-upload-wrap"><label for="async-upload">upload</label> <input type="file" id="async-upload" name="async-upload"> <input type="submit" value="Upload" name="html-upload"></p> <p><input type="hidden" name="post_id" id="post_id" value="<?php echo $post_id ?>" /> <?php wp_nonce_field('client-file-upload'); ?> <input type="hidden" name="redirect_to" value="<?php echo $_SERVER['REQUEST_URI']; ?>" /></p> <p><input type="submit" value="Save all changes" name="save" style="display: none;"></p> </form> </code>
|
How to add media from front-end to an existing post?
|
wordpress
|
I have a custom post type archive template archive-my-posttype.php with pagination. These post types have a custom taxonomy called theme. I am displaying these themes(terms) in the sidebar as a checkbox list. How can I filter the custom post type based on the selected themes/checkboxes? Can this be accomplished by adding a query_var parameter (theme_filter) and somehow modifing wp_query with the pre_get_posts filter? I am trying to let WP handle pagination rather than have to rewrite it myself. Thanks
|
I believe that what you are describing is how WordPress works out of the box. You will just need to create custom links in your sidebar. Something like <code> example.com/?post_type=your-custom-post-type-slug&theme=taco </code> should query for "all custom posts about the theme named taco".
|
Custom post type archive with dynamic taxonomy filtering - is it possible
|
wordpress
|
I have a lot of custom post types and I have them showing in my "Right Now" Dashboard but it's gotten pretty long so I want to separate them to a custom widget within the dash. See example below: So my question is how do I add the CPTs to a custom dashboard widget? Any help would be awesome. Thanks! EDIT: This is what I have (What am I missing?) <code> // wp_dashboard_setup is the action hook add_action('wp_dashboard_setup', 'mycustom_moviestats'); // add dashboard widget function mycustom_moviestats() { wp_add_dashboard_widget('custom_movie_widget', 'Movie Stats', 'custom_dashboard_movie_list'); } function custom_dashboard_movie_list(){ // here is the code to add custom post types + count see below function my_right_now() { $num_widgets = wp_count_posts( 'widget' ); $num = number_format_i18n( $num_widgets->publish ); $text = _n( 'Widget', 'Widgets', $num_widgets->publish ); if ( current_user_can( 'edit_pages' ) ) { $num = "<a href='edit.php?post_type=widget'>$num</a>"; $text = "<a href='edit.php?post_type=widget'>$text</a>"; } echo '<tr>'; echo '<td class="first b b_pages">' . $num . '</td>'; echo '<td class="t pages">' . $text . '</td>'; echo '</tr>'; } add_action( 'right_now_content_table_end', 'my_right_now' ); } </code>
|
Lokks like you have a function declared inside another function, your code is wrong, try this: <code> // wp_dashboard_setup is the action hook add_action('wp_dashboard_setup', 'mycustom_moviestats'); // add dashboard widget function mycustom_moviestats() { wp_add_dashboard_widget('custom_movie_widget', 'Movie Stats','custom_dashboard_movie_list'); } function custom_dashboard_movie_list(){ $args = array( 'public' => true , '_builtin' => false ); $output = 'object'; $operator = 'and'; echo '<table>'; //loop over all custom post types $post_types = get_post_types( $args , $output , $operator ); foreach( $post_types as $post_type ) { $num_posts = wp_count_posts( $post_type->name ); $num = number_format_i18n( $num_posts->publish ); $text = _n( $post_type->labels->singular_name, $post_type->labels->name , intval( $num_posts->publish ) ); if ( current_user_can( 'edit_posts' ) ) { $num = "<a href='edit.php?post_type=$post_type->name'>$num</a>"; $text = "<a href='edit.php?post_type=$post_type->name'>$text</a>"; } echo '<tr><td class="first b b-' . $post_type->name . '">' . $num . '</td>'; echo '<td class="t ' . $post_type->name . '">' . $text . '</td></tr>'; } //loop over all taxonomies $taxonomies = get_taxonomies( $args , $output , $operator ); foreach( $taxonomies as $taxonomy ) { $num_terms = wp_count_terms( $taxonomy->name ); $num = number_format_i18n( $num_terms ); $text = _n( $taxonomy->labels->singular_name, $taxonomy->labels->name , intval( $num_terms )); if ( current_user_can( 'manage_categories' ) ) { $num = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$num</a>"; $text = "<a href='edit-tags.php?taxonomy=$taxonomy->name'>$text</a>"; } echo '<tr><td class="first b b-' . $taxonomy->name . '">' . $num . '</td>'; echo '<td class="t ' . $taxonomy->name . '">' . $text . '</td></tr>'; } echo '</table>'; } </code>
|
Add custom post types stats to a custom dashboard widget
|
wordpress
|
I'm trying to use WordPress template tags (through shortcodes) to merge the post title and url into hyperlink html code. Which looks like this: <code> <a href="[Permalink]">[Post Title]</a>. </code> Problem is the text output uses curly quotes around the "Permalink" that are not compatible with html code. I tried placing hyperlink code using template tags (shortcodes) into a code snippet box, however then the shortcodes won't run. I would like to merge the template tags (through shortcodes) into the hyperlink html code first, then have it show up in a code snippet box. Any ideas on how to do that?
|
Just tested this and it worked on my end. The shortcode itself would be [titlelink] <code> function titlelink_ssc($content = null) { ob_start(); echo '<a href="'.get_permalink().'" title="'.get_the_title().'">'.get_the_title().'</a>'; $titlelink_ssc = ob_get_clean(); return $titlelink_ssc; } add_shortcode("titlelink", "titlelink_ssc"); </code>
|
Use template tags in code snippets wordpress
|
wordpress
|
The following bit of code results in a duplicate attribute site validation error. This template script: <code> <div class="clearfix" <?php post_class() ?>> </code> produces this source output: <code> <div class="clearfix" class="post-263 post type-post status-publish format-st… </code> WordPress adds its own post-related classes to format the blog entry. Is there any way I can add my "clearfix" class to the template without producing the duplicate attributes? Thanks.
|
Simple fix: <code> <div <?php post_class("clearfix"); ?>> </code> See post_class() for more details
|
Duplicate attribute class causing site validation error
|
wordpress
|
OK so i have <code> custom post types </code> and <code> custom taxonomies </code> . I have a sub-menu that is made of the custom taxonomies. Example: registered taxonomy: Movies and terms: action , adventures , etc . (= menu items) Problem: Now I need to add a highlight -class to the terms when the currently displayed page is an archive of one of the terms. I am almost looking to use my nav menu as a breadcrumb so to speak.
|
Ok. So instead of pasting the code here ill just link to it since i do not feel like adding the code format to each line. This is most likely just temporary but will get what i need done. It is used with some of jquery scripting but should not need it. Feel free to edit as you wish and update this question with your re-writes http://pastebin.com/bWC7a1ej
|
Highlight nav menu terms
|
wordpress
|
I hope this makes any type of sense. I want to be able to add clauses to a specific query object without effecting the main loop on a page, for example for content in a side bar or footer. Is it possible?
|
The most reliable way is to define your own query var and then check it: <code> $my_query = new WP_Query( array( ... 'context' => 'my_query' ) ); </code> Then, from your callback: <code> function alter_post_clauses( $clauses, $wp_query ) { if ( 'my_query' == $wp_query->get( 'context' ) ) { // do stuff } return $clauses; } add_filter( 'posts_clauses', 'alter_post_clauses', 10, 2 ); </code>
|
Limiting posts_join, where, etc to a specific WP_Query object?
|
wordpress
|
Is there any way to change the aspect ratio of the WordPress Avatars? Or is this hardcoded? Greetings, .wired
|
Possible sollutions: Use Css with something like <code> overflow: hidden; </code> and "cut out" what you need. Use the filter <code> apply_filters('get_avatar', $avatar, $id_or_email, $size, $default, $alt); </code> and override the output of <code> $avatar </code> completely. The function <code> get_avatar() </code> is pluggable. That means if you hook a plugin function early enough that already defines <code> get_avatar() </code> then this function will be used instead of the core function. See Core (link) .
|
Change the avatar ratio?
|
wordpress
|
I am using products as a 'custom post type' then I'm displaying a gallery of all products on the home page with a buy button next to each one. When the buy button is clicked, I would like it to redirect to a page with some more info of that product and a checkout form. What do I need to send to the URL using the button to retrieve this type of page? Should I just write my own query or is there something in wordpress that can do this for me? This is my form right now: <code> <form class='product_form' action="checkout" method="get"> <input name="post_id" type="hidden" value="<?=$post->ID?>"/> <input type='image' src='<?php bloginfo('template_url'); ?>/images/buy.png' class='wpsc_buy_button' /> </form> </code>
|
If you want to reach the "single" page of a custom post type (or even a regular post), you can do this by going to <code> http://example.com?p=[post_id]&post_type=[post_type_name] </code> . If you use Pretty permalinks WordPress will redirect you to the "canonical" link, which may look like <code> http://example.com/my-post-type/my-post-name/ </code> . So by changing the <code> target </code> of your form and the <code> post_id </code> hidden input to <code> p </code> it should work: <code> <form class='product_form' action="checkout" method="get" target="<?php home_url(); ?>"> <input name="p" type="hidden" value="<?=$post->ID?>"/> <input type='image' src='<?php bloginfo('template_url'); ?>/images/buy.png' class='wpsc_buy_button' /> </form> </code>
|
Display one post based on ID from $_GET
|
wordpress
|
I'm completely open on how to do this: I have the line: <code> echo implode(', ',get_field('categories')); </code> Which is outputting this: <code> Branding, Web, Print </code> I have 20 or so options it can output depending on what checkboxes were ticked. At the moment, what it's outputting is just plain text. How can I make each tag a link? The link would need to be unique per tag so: <code> <a href="tags/design/branding">Branding</a>, <a href="tags/design/web">Web</a>, <a href="tags/marketing/print">print</a> </code> UPDATE: The first part of the question is working thanks to Brady. I now have an additional question - Using Brady's answer on the line: <code> $elements[] = '<a href="/tags/design/' . strtolower($category) . '" title="' . $category . '">' . $category .'</a>'; </code> If you look at the href it has the link /tags/design/, some of the tags it's outputting are using the correct link but some are from another section and the link should be /tags/marketing/. How can I account for this? (Not that I know how to do this, someone will need to show me!) Could I create an array with the tags "Branding, Web, Print" and if the $category variable matches this then give it the variable $design. Could I then create another array with "Advertising, Analysis, Campaign" and give it the variable $marketing if the $category matches that. Then in the link I could put href="/tags/$design/$category" or href="/tags/$marketing/$category"? So a couple of examples would be (I'll put them as normal links): From the design section: <code> <a href="/tags/design/branding">Branding</a> <a href="/tags/design/web">Web</a> <a href="/tags/design/print">Print</a> </code> From the marketing section: <code> <a href="/tags/marketing/advertising">Advertising</a> <a href="/tags/marketing/analysis">Analysis</a> <a href="/tags/marketing/campaign">Campaign</a> </code> There are only two sections design and marketing, within those sections there are several tags, if that makes sense. The sections in WP are setup like this: tags > design > (each tag - branding, web, print is it's own page). tags > marketing > (each tag - advertising, analysis, campaign is it's own page).
|
<code> <?php $categories = get_field('categories'); $elements = array(); foreach($categories as $category) { //do something $elements[] = '<a href="' . $url . '" title="' . $title . '">' . $name .'</a>'; } echo implode(',', $elements); ?> </code> at the <code> //do something </code> here you should find what the URL should be for your category/tag something like get_tag_link() might be of use. Also have you looked at using the_tags() It does what your after and can be used in the loop.
|
Convert imploded plain text into links
|
wordpress
|
I want to show the projects that has had it's checkbox ticked as Branding, if it's on the Branding page (i.e the page title is Branding). To explain the code a bit: This line show's all the checkboxes that have been ticked for each project so it will output "Branding", "Web", "Print" if they have been ticked. <code> implode(', ',get_field('categories') </code> This next line is just checking the page title is "Branding": <code> implode(', ',get_field('categories') </code> I'm trying to put these both in an if statement where it would just output the checked boxes and if they match the title then output them. <code> <?php if(implode(', ',get_field('categories')) && $grid_title == "Branding"); { echo "testing"; } ?> </code> The code above shows what I want to do but it doesn't quite work. IMPORTANT: I'm using this plugin to create the custom checkboxes so please bear that in mind.
|
I managed to figure it out myself reading around, solved it with this: <code> <div id="grid"> <?php $args = array( 'depth' => 0, 'child_of' => 411 ); $pages = get_pages(array('child_of')); $grid_title = $post->post_title; foreach($pages as $post) { setup_postdata($post); $fields = get_fields();?> <?php if($fields->company_name != "") : ?> <!-- Any new tags will need to be added below --> <?php if((in_array("Branding", get_field('categories')) && $grid_title == "Branding") || (in_array("Creative", get_field('categories')) && $grid_title == "Creative") || (in_array("Development", get_field('categories')) && $grid_title == "Development") || (in_array("Exhibition", get_field('categories')) && $grid_title == "Exhibition") || (in_array("Packaging", get_field('categories')) && $grid_title == "Packaging") || (in_array("Print", get_field('categories')) && $grid_title == "Print") || (in_array("SEO", get_field('categories')) && $grid_title == "SEO") || (in_array("Usability", get_field('categories')) && $grid_title == "Usability") || (in_array("Web", get_field('categories')) && $grid_title == "Web") || (in_array("Campaign", get_field('categories')) && $grid_title == "Campaign") || (in_array("Copywriting", get_field('categories')) && $grid_title == "Copywriting") || (in_array("Feasibility", get_field('categories')) && $grid_title == "Feasibility") || (in_array("Research", get_field('categories')) && $grid_title == "Research") || (in_array("Social Media", get_field('categories')) && $grid_title == "Social Media")){ echo " <div class=\"grid-box\" onclick=\"location.href='" . get_page_link($post->ID) ."';\" style=\"cursor: pointer;\"> <div class=\"phase-1\"> <img class=\"grid-image\" src=\"" . $fields->thumb_image . "\" alt=\"" . $fields->company_name ."\" height=\"152\" width=\"210\" /> <div class=\"grid-heading\"> <h2>". $fields->company_name ."</h2> <h3>" . implode(', ',get_field('categories')) ."</h3> </div> </div> <div class=\"phase-2\"> <div class=\"grid-info\"> <h4>". $fields->project_name ."</h4> <p>". $fields->description ."</p> </div> <div class=\"grid-heading-hover\"> <h2>". $fields->company_name ."</h2> <h3>". implode(', ',get_field('categories')) ."</h3> </div> </div> </div> "; } else { echo " <div class=\"grid-box\" onclick=\"location.href='" . get_page_link($post->ID) ."';\" style=\"cursor: pointer;\"> <div class=\"phase-1\"> <img class=\"grid-image\" src=\"" . $fields->thumb_image . "\" alt=\"" . $fields->company_name ."\" height=\"152\" width=\"210\" /> <div class=\"grid-heading\"> <h2>". $fields->company_name ."</h2> <h3>" . implode(', ',get_field('categories')) ."</h3> </div> </div> <div class=\"phase-2\"> <div class=\"grid-info\"> <h4>". $fields->project_name ."</h4> <p>". $fields->description ."</p> </div> <div class=\"grid-heading-hover\"> <h2>". $fields->company_name ."</h2> <h3>". implode(', ',get_field('categories')) ."</h3> </div> </div> </div>"; } else : ?> <?php endif; ?> <?php } wp_reset_query(); ?> </div> </code>
|
Match checkbox data with page title to show certain items
|
wordpress
|
I have a custom post type whose permalink needs to sit in the same space as pages, like so: <code> /an-example-thing <-- custom post type 'thing' /about-the-things <-- a normal page </code> I'm well aware that this isn't the recommended way to do it , but I don't really have a choice - that's what the client has specified. I've created the custom types with register_post_type , and used the Custom Post Permalinks plugin to set their permalink like so: <code> /%thing%/ </code> However, this creates a conflict between the rule that recognises my custom posts, and the one for normal pages - which turns all normal pages into 404s. This problem disappears when the permalink is changed to something like this: <code> /things/%thing%/ </code> Using the Monkeyman Rewrite Analyser shows that the rule for the custom post is coming first. Even when I try forcing it to use verbose rules: <code> global $wp_rewrite; $wp_rewrite->use_verbose_page_rules = true; </code> the custom post type rule is higher priority than the verbose rules for pages so they still get a 404. I'd like it to look for things first, and when none is found with that name look for pages. The other way round would be acceptable. Is there no way of persuading it to look for both things and pages before hitting a 404?
|
You start with one bonus point for using my rewrite analyzer :-) Indeed, even if you use verbose page rules, since version 3.1 (or something around that) the taxonomy rewrite rules come even before that. I stackexchange-url ("recently answered another question") with a way to move them really to the top. This should work if you don't mind having verbose page rules (if you don't have more than 25 pages or so). If you don't want verbose page rules you will have to extend the core <code> WP </code> class so it can deal with "ambiguous" situations where the URL can refer to a page or a custom post type. Mike stackexchange-url ("once provided a nice way to do this"). His answer is written for a custom taxonomy, but it should be adaptable to a custom post type too.
|
Using /%postname% for a custom post type
|
wordpress
|
Basically I've made a plugin to create a new post type (event). Now I want to create a <code> single-event.php </code> layout file. I don't want to have to stick it in the theme folder, I want to put it into my plugin folder. How do I make wordpress know its there? Thanks
|
Here is the code that will let you return your single-event.php if the post type is event: <code> function my_event_template($single_template) { global $post; if ($post->post_type == 'event') { return dirname( __FILE__ ) . '/single-event.php'; return $single_template; } add_filter( "single_template", "my_event_template" ) ; </code>
|
Create theme files for plugin
|
wordpress
|
I'm working on a project where I need display 2 post from one category and also I need to put another loop between this post post to display random list of post from other category. Easiest way to do so is to create 3 queries, but when I created 2 queries for one category, but here I got problem one loop breaks and display both posts, second works fine. I used offset parameter for second query but it doesn't work. <code> <?php $first_query_args = array( 'category_name' => 'first-category', 'tag' => 'special-tag', 'post_per_page' => 1, ); $first_query = new WP_Query( $first_query_args ); if ( $first_query->have_posts() ) : while ( $first_query->have_posts() ) : $first_query->the_post(); // First query stuff goes here endwhile; endif; wp_reset_query(); // Query for Random posts $query_for_random_args = array( 'category_name' => 'cat-for-rand', 'post_per_page' => 3, 'orderby' => 'rand', ); $query_for_random = new WP_Query( $query_for_random_args ); if ( $query_for_random->have_posts() ) : ?> <ul> <?php while ( $query_for_random->have_posts() ) : $query_for_random->the_post(); ?> <li> <?php if ( has_post_thumbnail() ) { ?> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail( 'list-image' ); ?></a> <a href="<?php the_permalink(); ?>" ><?php the_title(); ?></a> </li> <?php } endwhile; ?> </ul> <?php endif; wp_reset_query(); ?> <?php $second_query_args = array( 'category_name' => 'first-category', 'tag' => 'special-tag', 'offset' => 1, 'post_per_page' => 1, ); $second_query = new WP_Query( $second_query_args ); if ( $second->have_posts() ) : while ( $second_query->have_posts() ) : $second_query->the_post(); // Second query stuff goes here endwhile; endif; ?> </code> ( This code What I use for those loops ) Any ideas how can I solve this problem? or how can I use 2 queries for similar task? Cheers George
|
I would use <code> get_posts() </code> for your two ad hoc Loops. (Actually, you only need one ad hoc Loop, if you're modifying the main Loop so that only 2 posts are retrieved.) e.g. <code> \\ code modify main Loop to return only 2 posts goes here $firstpost = true; if ( have_posts() ) : while ( have_posts() ) : the_post(); \\ main Loop Post output goes here if ( $firstpost ) { $randomposts = get_posts( array( 'category' => $categoryid, 'numberposts' = $numberposts, 'orderby' => 'rand' ); \\ Output ad-hod Loop content, e.g. ?> <ul> <?php foreach ( $randomposts as $randompost ) { ?> <li><a href="<?php echo get_permalink( $randompost->ID ); ?>"><?php echo $randompost->post_title; ?></a></li> <?php } ?> </ul> <?php } $firstpost = false; // end the main Loop endwhile; endif; </code> (Untested example code)
|
Loop inside the loop
|
wordpress
|
Within "install plugins" I'm receiving an error stating "An Unexpected HTTP Error occurred during the API request." When I do a plugin search it throws me back to my site's 404 page. Any idea what would prevent my site from syncing properly with WordPress's servers? I added Hameedullah's code to functions.php and recevied this returned <code> object(WP_Error)#21 (2) { ["errors"]=> array(1) { ["http_request_failed"]=> array(1) { [0]=> string(75) "Could not resolve host: api.wordpress.org; No data record of requested type" } } ["error_data"]=> array(0) { } } </code> Is this a curl transport issue?
|
You can use the following code to dump the HTTP Api response, will help you figure out the cause of error. <code> function dump_http_api_response($response, $type="", $transport=null ) { if ( $type == "response" ) var_dump ( $response ); } add_action('http_api_debug', 'dump_http_api_response', 1, 3); </code> Example Output: <code> object(WP_Error)#15 (2) { ["errors"]=> array(1) { ["http_request_failed"]=> array(1) { [0]=> string(41) "Couldn't resolve host 'api.wordpress.org'" } } ["error_data"]=> array(0) { } } </code>
|
What causes an Unexpected HTTP Error within install plugins?
|
wordpress
|
I'm looking for a way to add body class depending on the User Agent of the client with php. I'm looking to implement it this way: page.php: <code> <body id="front" <?php ( function_exists ( 'body_class' ) : body_class($classes) ? NULL ); ?> > </code> Or by using adding it to the functions.php file FYI: The whole purpose of this is to sniff out particular mobile styles and disable javascript for the some mobile user-agents. p.s. I'm not looking for a mobile plugin. p.p.s. no, i'm not interested in using a mobile theme.
|
something like this maybe: <code> function my_class_names($classes) { $useragent = $_SERVER['HTTP_USER_AGENT']; if(strchr($useragent,'Safari')) $classes[] = 'Safari'; // etc.. return $classes; } add_filter('body_class','my_class_names'); </code> Edit - as per Chip's suggestion, here's the function using the WordPress useragents checks: <code> function my_class_names($classes) { global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone; if($is_lynx) $classes[] = 'lynx'; elseif($is_gecko) $classes[] = 'gecko'; elseif($is_winIE) $classes[] = 'winIE'; elseif($is_macIE) $classes[] = 'macIE'; elseif($is_opera) $classes[] = 'opera'; elseif($is_NS4) $classes[] = 'NS4'; elseif($is_safari) $classes[] = 'safari'; elseif($is_chrome) $classes[] = 'chrome'; elseif($is_iphone) $classes[] = 'iphone'; else $classes[] = 'other'; return $classes; } add_filter('body_class','my_class_names'); </code>
|
Add Useragent to the body class?
|
wordpress
|
I can't use any of the import plugins because of the older version -- so it's kind of a pain, plus the URL permalinks arent very optimal. Any ideas on how to do this? I'm afraid I'd have to do this manually! import plugin I mean. the xml import file format changed so I can use it to upload content =/ –
|
If you site is live then you shouldn't directly update that, although update in the recent version of wordpress is very easy and seemless but that wasn't the case in 2.1 though. Also here is the list of steps that I will recommend you to take: Make the list of all plugins. Make sure none of the plugin's are responsible for site's main functionality. (As kaiser said its okay if they are only presentational). There is 99% chance that your theme will break with or at least will complain of deprecated functions with wordpress 3.1, so you have two options, either switch to standard theme or check your site for errors from theme after each upgrade until you are at 3.1 Install the Wordpress 2.1 on test machine and clone your live site, not all the data but at least the functionality. Disable all the plugins responsible for main functionlaity that you noted in Step 2 Upgrade to the next stable version of wordpress that was released after your current version. Enable the plugins one by one and check your test site. If there are errors see if you can fix them or disable the plugin. You might also see errors from your theme if you haven't switched to standard theme, so try to fix them too. If you have upgraded to Wordpress 3.1 then Congratulations else goto Step 5. Hope this will be helpful to you and you will have easy upgrade to 3.1.
|
How can I migrate a super old version (2.0) of my blog to 3.1?
|
wordpress
|
Ive got some super old links that have a lot of SEO juice and I dont want to lose that if I change permalink structure. This is partly due to the older version of WP i have (2.1) I want to use post ids in the structure now, and not the slug name or maybe both myblog.com/post/12121/slug-name If i use htaccess for this will Google and other search engines update their links without penalizing me?
|
Yes you need 301 redirection and you will carry on your SEO juice to the new URLs.
|
If I change permalink structures, can I use htaccess to permanantly redirect links?
|
wordpress
|
Is there a plugin that will notify users of comment replies? I don't want a email notification but something on the sidebar where a user can click and see what posts have been replied to. Kind of like a subscription thing?
|
Recent Comments Widget shows recent comments(including author name and link to the blogpost). You can add it to the sidebar as well.
|
Looking for plugins that notify users of comment replies
|
wordpress
|
I'm trying to do a MySQL-style search with Wordpress' built-in functions for fetching posts. There's likely a simple way to do this and I'm probably just a little bit off from the solution. We have posts with custom fields in them. This is legacy data imported as a custom post type with custom_fields being the extra data from our older database. The custom fields are setup like this for each post in Wordpress right now: <code> key = subject val = Subject One, Subject Two, Subject Three </code> I'm trying to fetch all posts where custom_field value is LIKE "Subject Two", as an example. There's probably an easy way to do this that just hasn't hit me yet. Thanks for your help! I already have a properly working MySQL query. Just wanted to use Wordpress' functions to handle the query instead of me having to do it manually for this theme view. Here's the working example: <code> // Get posts that match LIKE this subject $cft_by_subject = $wpdb->get_results( "SELECT wp_posts.ID, wp_posts.post_title, wp_posts.post_date, wp_posts.post_name, wp_postmeta.meta_value FROM wp_posts, wp_postmeta WHERE (wp_posts.ID = wp_postmeta.post_id) AND (wp_posts.post_type = 'our-custom-post-type') AND (wp_posts.post_status = 'Publish') AND (wp_postmeta.meta_key = 'subject') AND (wp_postmeta.meta_value LIKE '%".$this-is-our-subject."%') ORDER BY wp_posts.ID ASC ", ARRAY_A ); </code>
|
You can use meta_query in WP_Query <code> $args = array( 'post_type' => 'post', 'meta_query' => array( array( 'key' => 'subject', 'value' => 'Subject Two', 'compare' => 'LIKE' ) ) ); $query = new WP_Query( $args ); </code>
|
Get all posts WHERE custom_field is LIKE value
|
wordpress
|
Im searching for some clue about this behavior? I think it is a PHP memory_limit or WP define('WP_MEMORY_LIMIT', 'X') issue? Sometimes images are resized and sometimes not, in other scenarios the browser crash: Im using Dreamhost as shared hosting, and their 7 upload limit. Error printed with an uploaded image of 6.4MB of size and with a width and height of: 11684x3855: Fatal error: Allowed memory size of 268435456 bytes exhausted (tried to allocate 46736 bytes) in /PATH/wp-includes/media.php on line 254 Other users reports the same issue with files, for example, of 3MB but with higher width and height (superior to 2000px or 3000px). Any help is welcome. Thanks in advance.
|
I've had the same issue in the past when uploading very large images. When it comes to crunching the image it fails and shows HTTP ERROR in red. However other images continue to load. It wasnt file size where it would fail but rather the pixel width and height of the images. By default PHP settings, the most GD libary can handle per image is 1,000,000 pixels which is 1024px*1024px Did you know: 8,000 pixels times 8,000 pixels times four bytes for truecolor equals a walloping 256 megabytes. Now I know no shared hosting webhost that allows you a PHP memory limit of 256MB The only solution I was able to find, of which I'm offering to you, is to reduce the size of the images beging uploaded. Alternativly convince your webhost to up PHP memory limit, which is unlikely.
|
Looks like image resize is not working well
|
wordpress
|
I want to make one long post, but have it paginate. I read that you could add this: <code> <!--nextpage--> </code> , but all it did was hide the content under the tag. Is there a plugin that helps do this? Is it possible that my theme may not allow this?
|
Your theme must have support for the <code> <!--nextpage--> </code> tag. You will need to add <code> <?php wp_link_pages(); ?> </code> in your post loop. http://codex.wordpress.org/Function_Reference/wp_link_pages
|
How can I split long posts into pages?
|
wordpress
|
I need to import users via csv file. I see lots of plugins that do mass imports, but they all seem to send out new user emails to the new users. Since this is currently being set up on a dev site, I don't want to send out the new user emails. Are there any plugins that import users without sending out new user notifications
|
The CSV User Import looks promising...looking through the plugin file, I don't see anything regarding registration emails.
|
Mass Import Users without sending new user notification
|
wordpress
|
i was making a gallery on my clients site using <code> [gallery] </code> sortcode. The gallery appears but when clicked it goes to clients other website which i have no idea why? here is the link http://www.build12.com/promotions-pictures/pictures/ check the wired link of the pictures. The wordpress version is 3.1.1. Please let me know what is your advice. Thanks!
|
look at your javascript in the header for the thumb info: <code> script> var thumbfile = "http://bricksandwindows.build12.com"; </code> also repeated on line 179 when viewing source
|
Whats wrong with my wp gallery?
|
wordpress
|
can anyone help me with this? I need to print the slug of my custom taxonomy, can this be done? The following kind of works but it just shows the name, rather than the slug which i need for a class purpose.. <code> <?php $terms = get_the_terms( $post->ID , 'area' ); foreach( $terms as $term ) {print $term->name; unset($term);}?> </code> Any way of just getting the slug for my custom taxonomy 'area' ?? Many thanks for any help :)
|
<code> $term->slug </code> Here is an example return of $term: <code> stdClass Object ( [term_id] => 31 [name] => Architectural Items / Salvage [slug] => architectural-items-salvage [term_group] => 0 [term_taxonomy_id] => 31 [taxonomy] => dcategory [description] => [parent] => 5 [count] => 10 [object_id] => 197 ) </code> If you don't know what's in <code> $term </code> or any other variable then print_r() and var_dump() are your friend.
|
Show Custom Taxonomy Slug(s)?
|
wordpress
|
I'm adding a custom profile field to users of a specific role, like this : <code> function add_custom_profile_fields( $fields ) { // get current user ID $user = new WP_User( $_GET['user_id'] ); // get current user role if ( !empty( $user->roles ) && is_array( $user->roles ) ) { foreach ( $user->roles as $role ) { // filter roles if ($role == "paying_member"){ $fields['paypal_account'] = 'Paypal account'; } } } return $fields; } add_filter('user_contactmethods','add_custom_profile_fields',10,1); </code> The problem is, the field's value doesn't get saved. When I login as admin an I edit a user's profile. It somehow has to do with the fact that I'm filtering by user role, because when I remove that part, the values get saved perfectly. EDIT : I think maybe the whole method is wrong, I'm going to try this instead.
|
Ok, I was doing it wrong, here's a working solution, based on Justin Tadlock's tutorial . <code> <?php /* Add custom profile fields (call in theme : echo $curauth->fieldname;) */ add_action( 'show_user_profile', 'my_show_extra_profile_fields' ); add_action( 'edit_user_profile', 'my_show_extra_profile_fields' ); function my_show_extra_profile_fields( $user ) { ?> <?php if(user_can($user->ID, "paying_member")) : ?> <h3>Extra profile information</h3> <table class="form-table"> <tr> <th><label for="paypal_account">Paypal</label></th> <td> <input type="text" name="paypal_account" id="paypal_account" value="<?php echo esc_attr( get_the_author_meta( 'paypal_account', $user->ID ) ); ?>" class="regular-text" /><br /> <span class="description">Please enter your Paypal account.</span> </td> </tr> </table> <?php endif; ?> <?php } add_action( 'personal_options_update', 'my_save_extra_profile_fields' ); add_action( 'edit_user_profile_update', 'my_save_extra_profile_fields' ); function my_save_extra_profile_fields( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; /* Copy and paste this line for additional fields. Make sure to change 'paypal_account' to the field ID. */ update_usermeta( $user_id, 'paypal_account', $_POST['paypal_account'] ); } ?> </code> The main addition to his code, is this line of code: <code> <?php if(user_can($user->ID, "paying_member")) : ?> </code> Which displays the custom fields only for users with the role of "paying_member" and admins.
|
Saving custom profile fields
|
wordpress
|
I've been strugling with the following issue for over a week now so please excuse the long description. I want it to be as accurate and clear as possible: I'm using the "simplr registration form" plugin to register new users. I need to add to the form an "address" field for the users to fill, and when the submit button is clicked the address should be sent to google maps API and recieve back the latitude and longitude which should then be saved in wpdb together with the rest of the user's data. To achieve this I've added the following to the php function which builds the html form: - address input field - 2 hidden fields for the lat&long - jquery function that responds to the submit button and is supposed to do its thing after the button's clicked but before the form is actually submitted and handled by the plugin's php function. Since using Google Maps API is asynchronous to get the job done I need to do the following: Write a function that responds to the submit click. That function should prevent the form from being submitted and call another function which does the google maps stuff and after it's finished submits the form. The problem lies with the second submit. It just doesn't happen. I have tried different ways (with jquery): - a submit function that calls itself with the use of a flag that tells the first iteration not to submit and the second one to submit. The code works fine until the second iteration submit which simply doesn't work. - a submit function that calls "this.submit()". Again, "this.submit()" doesn't cause the form to submit. - a click function that should respond to the submit being clicked, do the google stuff and then call the submit function. Here even the click function doesn't fire at all. <code> // This is the button's definition: $form .= apply_filters('simplr-reg-submit', '<input type="submit" name="submit-reg" id="submit-reg" value="Register" class="submit button">'); // This is the php code that starts handling the submitted form if(isset($_POST['submit-reg'])) { </code> Here's an example for one of my attempts: <code> function codeAddress(callback) { // do the google stuff // when finished submit the form $('#simplr-reg').get(0).submit(); // it's all being done except for the submit part } $('#simplr-reg').submit(function(event) { codeAddress(function(success){}); //callback from googlemaps event.preventDefault(); } // Here's a simplified example: $('#simplr-reg').submit(function(event) { this.submit(); //doesn't cause the form to submit event.preventDefault(); }); </code> If I don't use event.preventDefault() and submit in the first iteration it submits fine. I've tried solving this with the help of the guys on stackoverflow but no one could find what's wrong so I'm guessing it's got something to do with WordPress or the plugin.
|
The php function which handles the submitted values in this plugin checks first if the button's value <code> isset </code> . When using the original submit it is. When using <code> preventDefault() </code> and then calling <code> submit() </code> it isn't and therefor the php doesn't handle the submitted form but rebuilds it. To fix this I just added to the <code> isset() </code> check a check if the lat/long values are true. That did the trick.
|
Form doesn't submit on second submit call
|
wordpress
|
I'm using the Newsletter plugin (http://wordpress.org/extend/plugins/newsletter/) to compose e-mail newsletters. Using the "auto-compose" feature to pull website data via the theme included with the plugin, which I have begun to customise. It's pulling posts just fine, which is a good start - but I would also like to pull some data that a custom widget on our site is displaying. I'm fairly new to Wordpress and the custom widget in question was not developed by me. Can I include a specific widget via my theme template? Thanks
|
You may already know this, but you need to specify the widget's class name as the $widget_name variable in the template tag. For example, Depending on the widget, you may also need to add parameters to the_widget() to get it to display properly — see notes on thewidget() $instance and $args in the codex. http://codex.wordpress.org/Function_Reference/the_widget Alternatively, you can use a plugin like Widgets on Pages, which will let you include a widget anywhere using by using a shortcode like this: [widgets_on_pages id=WidgetName] http://wordpress.org/extend/plugins/widgets-on-pages/
|
Include widget within newsletter template?
|
wordpress
|
For the Stack Exchange Community Blogs, we have a network install that we've set up. I am being told that the site administrator role is not allowing an option for user editing. On the site's users page when hovering over a user, there is only an option for <code> delete </code> , not one for <code> edit </code> . The only option related to user permissions is the following, but not really what I'm going for here... How can I enable the site administrator to have full control over the users on that specific site?
|
As explained in the description of the Network Admin Users screen, in a network install (multisite mode) users are added on a global basis to the entire network, then assigned to specific sites Normal administrators are not permitted to modify these global profiles, since their privileges extend only to their given site. This task is reserved for super administrators, who have full control across the entire network. In prior versions of WordPress, when multisite installations relied on separate WordPress MU support, you could define <code> EDIT_ANY_USER </code> to be true in your wp-config.php file. However, since multisite support was natively integrated, I believe that this was removed. To manage network users from the Network Admin Users screen, a user must belong to a role that has at least the <code> manage_network_users </code> and <code> edit_users </code> permissions. You could try creating a custom role that included these and the standard administrator permissions, but I'm not convinced how effective that would be. Personally, I'd just try to avoid circumventing these restrictions.
|
Site admin in a network install can't edit users?
|
wordpress
|
I am working in a new project, and I just realized that in the page/post edit pages, I don´t have the option to set a featured image/ post thumbnail. I have checked and Twenty Ten has thumbnails support by default ( add_theme_support( 'post-thumbnails' is in functions.php). I also tried setting the thumbnails size with set_post_thumbnail_size, but no luck. Any ideas? P.D: I installed this in a new server, is it possible that it has something to do with that? Are there any specific requirements to use post thumbnails?
|
The featured image meta box is enabled under following conditions: <code> if ( current_theme_supports( 'post-thumbnails', $post_type ) && post_type_supports( $post_type, 'thumbnail' ) && ( ! is_multisite() || ( ( $mu_media_buttons = get_site_option( 'mu_media_buttons', array() ) ) && ! empty( $mu_media_buttons['image'] ) ) ) ) add_meta_box('postimagediv', __('Featured Image'), 'post_thumbnail_meta_box', $post_type, 'side', 'low'); </code> So check that: nothing messes up theme's declaration of thumbnails support; you are not using CPT with thumbnails support undeclared; whatever that multisite-related stuff means, if you are using multisite (I do and I don't remember having to do anything specific for featured images).
|
Post thumbnails not working in my new install of WP 3.1 with Twenty Ten theme
|
wordpress
|
trying to stop get_the_excerpt() from defaulting to the_content() if its empty. this kinda works - well it seems to return 'xxx' so i think has_excerpt() isn't working? <code> function get_link_excerpt(){ if(has_excerpt()){ $LinkExcerpt = get_the_excerpt(); return $LinkExcerpt."..."; } return 'no excerpt'; } add_filter('get_the_excerpt', 'get_link_excerpt'); </code> what's the best way to control this? best,Dc
|
WordPress sets up a default filter for <code> get_the_excerpt </code> : <code> wp_trim_excerpt() </code> . It is this function that will generate an excerpt from the content "if needed" . If you don't want this behavior, you can just unhook the filter: <code> add_action( 'init', 'wpse17478_init' ); function wpse17478_init() { remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' ); } </code> Now <code> get_the_excerpt() </code> will just return the contents of the <code> post_excerpt </code> database field. If you want to return something when it is empty, you only need to check this case: <code> add_filter( 'get_the_excerpt', 'wpse17478_get_the_excerpt' ); function wpse17478_get_the_excerpt( $excerpt ) { if ( '' == $excerpt ) { return 'No excerpt!'; } return $excerpt; } </code> There is no need to call <code> get_the_excerpt() </code> - it could even introduce an endless recursion because it applies your filter again!
|
excerpt - don't use main content if empty
|
wordpress
|
i'm using the BAAP Mobile version plugin and the footer link that switches between desktop and mobile version is being displayed outside of the wrapper> footer divs. Is there a hook or a method to have the switcher link display in the footer section? This is the function that creates and displays the links in the wpmp_switcher.php file. <code> function wpmp_switcher_wp_footer($force=false) { if(!$force && (get_option('wpmp_switcher_mode')=='none' || get_option('wpmp_switcher_footer_links')!='true')) { return; } switch (wpmp_switcher_outcome()) { case WPMP_SWITCHER_MOBILE_PAGE: print wpmp_switcher_link('desktop', __('Switch 2 our desktop site', 'wpmp')); break; case WPMP_SWITCHER_DESKTOP_PAGE: print "<p>" . wpmp_switcher_link('mobile', __('Switch to our mobile site', 'wpmp')) . "</p>"; break; } } </code>
|
If you look in the plugin's directory <code> plugins/wpmp_switcher/wpmp_switcher.php </code> on line 53 you will see this: <code> add_action('wp_footer', 'wpmp_switcher_wp_footer'); </code> so you can either remove this action and call it in your theme your self with: <code> remove_action('wp_footer', 'wpmp_switcher_wp_footer'); </code> or you just make sure that <code> wp_footer(); </code> is inside your wrapper> footer divs.
|
How to display a link in the footer section
|
wordpress
|
I'm attempting to set up a wiki within a Wordpress install and love the way codex.wordpress.org is set up. Are they using a specific plugin to accomplish that or just well structured pages? Is there a similar plugin available to users?
|
Hi in the wordpress.org header is this: <code> <meta name="generator" content="MediaWiki 1.15.5" /> </code> which leads me to think that it is this that is used MediaWiki regards Martin edit: something similar was aked before and it looks like a plugin solution was found <a href="stackexchange-url Plugin Similar To MediaWiki by Bainternet
|
Does codex.wordpress.org use a plugin of some sort? If so what plugin?
|
wordpress
|
I have several sites with Custom Post Types and Taxonomies registered by different plugins. Is there a way to add or change a parameter like this <code> "'rewrite' => array( 'hierarchical' => true )" </code> by adding something to functions.php—without completely re-registering the type/taxonomy? I want to continue to use certain plugins to manage types and taxonomies, but not all parameters are provided.
|
you could modify the global variable $wp_post_types or in the case of taxonomies, $wp_taxonomies for example, this will change the menu name and all the labels for the default Posts to Bacon: <code> function change_post_menu_label() { global $menu; global $submenu; $menu[5][0] = 'Bacon'; $submenu['edit.php'][5][0] = 'Bacon'; $submenu['edit.php'][10][0] = 'Add Bacon'; $submenu['edit.php'][16][0] = 'Bacon Tags'; echo ''; } function change_post_object_label() { global $wp_post_types; $labels = &$wp_post_types['post']->labels; $labels->name = 'Bacon'; $labels->singular_name = 'Bacon'; $labels->add_new = 'Add Bacon'; $labels->add_new_item = 'Add Bacon'; $labels->edit_item = 'Edit Bacon'; $labels->new_item = 'Bacon'; $labels->view_item = 'View Bacon'; $labels->search_items = 'Search Bacon'; $labels->not_found = 'No Bacon found'; $labels->not_found_in_trash = 'No Bacon found in Trash'; } add_action( 'init', 'change_post_object_label' ); add_action( 'admin_menu', 'change_post_menu_label' ); </code> source: http://new2wp.com/snippet/change-wordpress-posts-post-type-news/
|
Add/overwrite a parameter on an existing post type/taxonomy
|
wordpress
|
When using a modal window such as lightbox or shadowbox to display a post's images, client would like to be able to choose the background color that would be used for the modal window according to the image to be shown: color would be either black, white or grey. I'm thinking such hack should be done via a plugin but i didn't find any, so i guess i should do it myself. It scarces me a bit: where should i store the chosen value? What hooks ? Any help would be welcome.
|
You can store the chosen color in a meta field. We have a question about stackexchange-url ("adding a custom field to attachments"), it contains an example. The hooks you need are <code> attachment_fields_to_edit </code> and <code> attachment_fields_to_save </code> .
|
Set a background color per image added to a post
|
wordpress
|
I've used the wordpress plugin - advanced custom field and would like to show an array of a child, here's my code: I'm using this code to show the custom fields data from a specific page ID's children: <code> <?php $args = array( 'depth' => 0, 'child_of' => 411 ); $pages = get_pages(array('child_of')); foreach($pages as $post) { setup_postdata($post); $fields = get_fields(); if($fields->company_name != "") : ?> <h2><?php echo $fields->company_name; ?></h2> <?php else : ?> <?php endif; ?> <?php } wp_reset_query(); ?> </code> This is the code I'm using to show the checkbox data of the page itself (i.e it's not a parent/child): <code> <?php $catNames = array( 'branding','creative','development','exhibition','packaging','print','seo','social_media','usability','web','advertising','campaign','content','feasibility','publishing','research','strategy'); foreach($catNames as $name){ if(in_array($name, get_field('categories') )){ echo '<a href="/tags/design/'.$name.'" title="'.$name.'">'.ucwords($name).'</a>'; } } ?> </code> I want to combine the two together so underneath the H2 tag in the first code box I want to show the checkbox data of the child, how can this be done? UPDATE: When I add the checkbox code to the child code, I can't get the data to display, it's either blank or has an error. This is the page I'm working on . The first thumbnail has been hardcoded, the second and third thumbnails should pick up the tags with the code above but it doesn't.
|
This will show the checkboxes that have been ticked (much simpler!!): <code> <?php $categories = get_field('categories'); $elements = array(); foreach($categories as $category) { //do something $elements[] = '<a href="/tags/design/' . strtolower($category) . '" title="' . $category . '">' . $category .'</a>'; } echo implode(',', $elements); ?> </code>
|
Wordpress - Display array data of a child
|
wordpress
|
I have my own theme that I've created and I need to support 3 languages. I started by adding the gettext functions to my template _e("string","namespace") etc, generated the po file with Poedit, and then created the .mo file for Spanish (es_ES) My current setup which is not working > Update wp-config.php <code> define ('WPLANG', 'es_ES'); </code> functions.php <code> define('TPL_LANGUAGES',TEMPLATEPATH.'/languages/'); function theme_init(){ load_theme_textdomain( 'protoman', TPL_LANGUAGES); } add_action('init', 'theme_init'); </code> languages mo file <code> themes/protoman/languages/es_ES.mo </code> index.php <code> <ul> <li><a href="#"><?php _e('Home', 'protoman'); ?> </a></li> <li><a href="#"><?php _e('Account', 'protoman'); ?></a></li> <li><a href="#"><?php _e('Shop', 'protoman'); ?> </a></li> <li><a href="#"><?php _e('Corporate', 'protoman'); ?> </a></li> </code> STILL NO LUCK!
|
You need to load_theme_textdomain() in your theme. Place this in theme functions file: <code> function theme_init(){ load_theme_textdomain('theme_name', get_template_directory() . '/languages'); } add_action ('init', 'theme_init'); </code> Then you put you language files in you theme /languages folder you language files should be es_ES.mo and es_ES.po without the text domain at the front as the codex states <code> File names such as: my_theme-sv_SE.mo will NOT work. </code>
|
How do you install a .MO (language file) to use as part of a theme?
|
wordpress
|
I would like to modify WordPress default search. I have 2 questions: which template file to modify, and how can I include posts ids that I want to include in search? I need to search from specific post ids, so I want to modify search in this particular way.
|
The output of search results is controlled by <code> search.php </code> template (or generic <code> index.php </code> if it's not present). And search is technically a usual WordPress loop with <code> s </code> query argument, so any snippets that apply to loops can be used to tweak search.
|
modify wordpress default search
|
wordpress
|
I have 2 sizes thumbs for featured images with the same height: 300 x 200 540 x 200 I've checked the uploads folder and both thumbs with different sizes appear correctly: file_name-300x200.jpg file_name-540x200.jpg I'm trying to get the bigger thumb size (540x200) as following: <code> $width = 540; $height = 200; echo get_the_post_thumbnail( $post->ID, array($width,$height) ); </code> However, the image markup that is returned is for the smaller thumb zise (300x200). Interestingly, the class is displayed with the correct domantions as 'attachment-540x200': <code> <img width="300" height="200" src="http://mysite.com/wp-content/uploads/file_name-300x200.jpg" class="attachment-540x200 wp-post-image" alt="file_name" title="file_name" /> </code> Would really appreciate if anyone could explain what's happening and why the correct size thumb isn't returned. Many thanks, Dasha
|
I think you've hit interesting logic issue in <code> image_get_intermediate_size() </code> . This function loops through available images and tries to find best possible match for custom dimensions you provided. First it attempts to find image as per comment in code: <code> // already cropped to width or height; so use this size </code> See the issue? Not image, perfectly matching dimensions, but image that matches in width or height, with remaining dimension being smaller or equal than required to fit in dimensions. So your 300×200 image has equal height and fits inside 540×200 dimension you want (and probably comes earlier in meta data) so WP happily grabs it to use. Interestingly, the class is displayed with the correct... No mystery there, class is simply generated from your input, without regard if values make sense and/or available.
|
Featured image with the same height thumbs returns wrong thumb
|
wordpress
|
On the single-post page within the loop I need an array of the_tags() which is a string. and get_tags() gives me all of the tags not only this posts. Is there an easy way to get this?
|
the function <code> get_the_tags() </code> does for a single post, what <code> get_tags() </code> does for the site.
|
In need of array of post tags
|
wordpress
|
So i got the RSS feed which output some custom post types, but the GUID looks bad to me, it's like: <code> ?post_type=mycustompost&p=124 </code> The reason i want to change this is that I don't need people to know it's Wordpress or to see my custom post type name (this is very important in this project) Is there a filter or hook to rewrite this? Thanks
|
The feed template files call <code> the_guid() </code> , which calls <code> get_the_guid() </code> , which has a filter named (surprisingly) <code> get_the_guid </code> . You can hook into this filter to change the output. The filter only gets the current GUID, not the post ID, so look this up in the global variable if you need it. <code> add_filter( 'get_the_guid', 'wpse17463_get_the_guid' ); function wpse17463_get_the_guid( $guid ) { return 'http://example.com/guid/' . sha1( $guid ); } </code> See also this Trac ticket which proposes to change the current GUID format to a more unique hash.
|
Change custom post type GUID in RSS
|
wordpress
|
I have in the following code in the template: <code> <img src="<?php header_image(); ?>" /> </code> However, I want to change this image according to the language selected (through GET parameter lang). The question is, how to change this function to look for different images according to the received GET parameter? I thought of: Change this code on header.php to a fixed image path, so I could put an if and choose between the images I want. Replace the result of the function get_header_image() and use it instead on header.php according to the received parameter, sort of replacing the string suffix .png to _en.png or .png to _es.png. Change the header_image() function to behave the way I want. All these ways look ugly to me. Are there better ways?
|
Filter the <code> get_theme_mod() </code> function ( <code> wp-includes/theme.php </code> ): <code> add_filter( 'theme_mod_header_image', 'localized_header' ); function localized_header( $img ) { // Do something awesome with the $img path. return $img; } </code>
|
How to internationalize header image?
|
wordpress
|
I am trying to add oEmbed DeviantArt integration to a custom theme. I found that first step is quite easy, I added <code> wp_oembed_add_provider( 'http://*.deviantart.com/#/d*', 'http://backend.deviantart.com/oembed' ); </code> to theme's functions.php . Now, I would like to change the default HTML output to add more information, available in DeviantArt JSON response ( DeviantART reference ), like author_name, author_url, etc. If I have studied well the WP code that manage the output is inside function data2html in class-oembed.php , but I don't like change the code here. How can I add a function to my theme, to achieve the desired result?
|
<code> WP_oEmbed::data2html() </code> has a filter, <code> oembed_dataparse </code> . You can use this to change the output, based on the extra data which is passed as the second parameter. Something like this for example: <code> add_filter( 'oembed_dataparse', 'wpse17461_oembed_dataparse', 10, 3 ); function wpse17461_oembed_dataparse( $html, $data, $url ) { if ( FALSE !== strpos( $url, 'deviantart.com' ) ) { return $html . '<br/>Author: ' . $data->author_name; } return $html; } </code>
|
How to modify the HTML formatting of an oEmbed link?
|
wordpress
|
I changed my user profile name with WP-Optimize from 'admin' to 'indie' (not really 'indie', just to show you better) but author page still is available only trough example.com/author/admin - not example.com/author/indie. Is there anything I missed? Greetings, .wired
|
take a look at Change the Author Slug from Username to Nickname more specifically at Jan's answer.
|
Author page doesn't change after username change
|
wordpress
|
The following code was mentioned from one of the commentors, however it is breaking the pagination. Any corrections please <code> <?php include(TEMPLATEPATH. '/includes/headline.php'); rewind_posts(); if (have_posts()) { echo '<div class="gridrow clear">'; while (have_posts()) : the_post(); global $post; $query_string; query_posts( $query_string .'&posts_per_page=5' ); include(TEMPLATEPATH. '/includes/loop.php'); $q = $wp_query->current_post; $maxq = tj_current_postnum(); if($q < $maxq-1 && is_int(($q+1)/2)) echo '</div><div class="gridrow clear">'; $postcount++; endwhile; echo '</div> <!--end .gridrow-->'; } else { include(TEMPLATEPATH. '/includes/not-found.php'); } if ( $wp_query->max_num_pages > 1 ) tj_pagenavi();?> </code>
|
You need to tell Wordpress to get only 5 posts per page. The parameter to do this is posts_per_page. You should use query_posts() function before your have posts as in the following example. <code> <?php // your includes and stuff global $query_string; query_posts( $query_string . '&posts_per_page=5' ); // now your have_posts if ( have_posts() ) { // list the posts } else { // not found msg here.. } ?> </code>
|
Limit number of posts on a custom category template - breaking pagination
|
wordpress
|
There is a site at <code> http://theprimarkonlineshop.com </code> that I want to be redirected to <code> http://theprimarkonlineshop.com/category/blog </code> when a user enters the site. I've tried some stuff like <code> RewriteEngine on RewriteCond %{REQUEST_FILENAME} ^/$ [OR] RewriteCond %{REQUEST_FILENAME} ^$ RewriteRule . http://theprimarkonlineshop.com/category/blog/ [R=301,L] </code> but it doesn't work. Also there are some redirections that were put into <code> .htaccess </code> by WordPress <code> RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </code> I guess they should remain as is?
|
Here is how I'd do it: http://wordpress.org/extend/plugins/redirect/ Install above plugin Create a page Add custom field: redirect of a value of http://theprimarkonlineshop.com/category/blog Set page you have created to the sites homepage.
|
Redirect from home page to post list page?
|
wordpress
|
I've encountered an issue on a site I'm looking after. The 'admin' account no longer has access to the plugins page, if I try and manually type in the URL to the page, I get the following error: "Page disabled by the administrator" Any idea what could be causing that? Thanks!
|
I've actually just fixed it myself. The problem was as follows: I had changed the username of the admin account to 'new-admin'. What I had missed when making this change was to update the 'wp_sitemeta' table in the database. meta_id 8 (site_admins) still had the old admin name set. Once I updated this, the plugins menu reappeared!
|
Plugins Page - "Page disabled by the administrator"
|
wordpress
|
If I use the wp_insert_post in a plugin, will I have to check the content for SQL injection problems and XSS or will the wp_insert_post function do this for me?
|
The short answer; absolutely . <code> wp_insert_post() </code> will only SQL escape the content. Use the KSES library & wp_kses() to filter out the nasties, or <code> esc_html() </code> to escape all HTML. Most importantly, check out the codex on data validation (read: sanitization). A Note On KSES: Use wp_filter_kses() or <code> wp_kses_data() </code> to apply the same KSES rules as post comments. The subtle difference between the two is the former expects data escaped with slashes (and returns the same), whilst the latter does not. WordPress (bizarrely) enforces magic quotes , so <code> $_POST </code> , <code> $_GET </code> (and the like) will have escape slashes added by default. A Note On wp_insert_post(): This function also expects the data array to have slashes added, so you'll need to sanitize it with add_magic_quotes() if that's not the case. Update: And put in practice; <code> $_POST['post_title'] = wp_filter_nohtml_kses( $_POST['post_title'] ); // also expects & returns slashes $_POST['post_content'] = wp_filter_kses( $_POST['post_content'] ); $post_ID = wp_insert_post( $_POST ); // add to the fun - wp_update_post() will add slashes if $postdata is an object! $update = ( object ) stripslashes_deep( array( 'ID' => $post_ID ) + $_POST ); $update->post_title .= ' Updated!'; wp_update_post( $update ) </code>
|
Does wp_insert_post validate the input?
|
wordpress
|
I created a custom post type:products which also has custom fields: price & shipping. Occasionally, if I leave the edit product window open or refresh it, I lose the values inside price and shipping. Can someone please advise on this. <code> add_action('save_post', 'save_details'); function save_details() { global $post; update_post_meta($post->ID, "price", $_POST["price"] ); update_post_meta($post->ID, "shipping", $_POST["shipping"] ); update_post_meta($post->ID, "long_title", $_POST["long_title"] ); update_post_meta($post->ID, "upload_image", $_POST["upload_image"] ); } </code>
|
Check your variables before you work with them. Your save function gets a parameter <code> $post_id </code> . Use it. From my meta box class for a check box : <code> /** * Saves the content to the post meta. * * @return void */ public function save( $post_id ) { $this->is_allowed_save( $post_id ) and update_post_meta( $post_id, $this->vars['key'], empty ( $_POST[ $this->vars['key'] ] ) ? 'off' : 'on' ); } /** * Checks if we should trigger the save action. * * @param int $post_id * @return bool */ protected function is_allowed_save( $post_id ) { // Check integrity, proper action and permission if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) { return FALSE; } if ( ! wp_verify_nonce( $this->nonce, $this->vars['title'] ) ) { return FALSE; } if ( ! current_user_can( 'edit_post', $post_id ) and ! current_user_can( 'edit_page', $post_id ) ) { return FALSE; } return TRUE; } </code> As you can see, <code> DOING_AUTOSAVE </code> is something you want to avoid. Authorization is the next point, otherwise anybody can post anything to your blog. And prepare the data before you insert them into the DB.
|
Custom field values get deleted
|
wordpress
|
I am trying to use ids to control the structure of the output of my categories. I need to exclude a category that is part of the parent category that is being queried. What I am trying is : <code> <?php $the_query = new WP_Query('cat=14$cat=-45&showposts=20'); $permalink = get_permalink( $post_id ); while ($the_query->have_posts()) : $the_query->the_post();?> <li> <a href="<?php the_permalink() ?>" rel="bookmark" class="postTitleLink"> <?php the_title(); ?></a> </li> <?php wp_reset_query(); ?><?php endwhile; ?> </code> What would be the correct way to show everything in category id 14, except for category 45? I want to treat 45 differently and show all of its sub categories in a different way. To try and help describe what I want : <code> #12 - #14 - #14 - #14 -- #45 --- #50 ---- #60 --- #51 - #14 </code> instead of cat=- should I be using conditional statements instead .. !in_category ? Thanks for any help!
|
First you should move <code> wp_reset_query(); </code> outside of the loop instead of resetting the query every post of the loop. And as for your query you can use <code> category__not_in </code> <code> $args = array( 'cat' => 14, 'category__not_in' => array('45'), 'posts_per_page' => 20 ); $the_query = new WP_Query($args); while ($the_query->have_posts()) : $the_query->the_post();?> <li> <a href="<?php the_permalink() ?>" rel="bookmark" class="postTitleLink"> <?php the_title(); ?></a> </li> <?php endwhile; ?> <?php wp_reset_query(); ?> </code> this will exclude all posts of category 45.
|
Exclude a category from a query that includes its parent category
|
wordpress
|
I'd like to offer my custom post type as a Plugin, so that people can use it without touching their theme folder. But custom post type templates -- such as single-movies.php -- reside in the theme folder. Is there a way to get WP to check for a single-movies.php in the plugin's folder? Hooking a function into the Filer Hierarchy? Or get_template_directory(); ?
|
you can use <code> single_template </code> filter hook <code> /* Filter the single_template with our custom function*/ add_filter('single_template', 'my_custom_template'); function my_custom_template($single) { global $wp_query, $post; /* Checks for single template by post type */ if ($post->post_type == "POST TYPE NAME"){ if(file_exists(PLUGIN_PATH. '/Custom_File.php')) return PLUGIN_PATH . '/Custom_File.php'; } return $single; } </code>
|
Custom Post Type Templates from Plugin Folder?
|
wordpress
|
I'm using a custom post type to let contributors have a personal page on the site. Any time a user registers to my site a script creates a custom type post that has the registering user as author. To moderate users entries this post is pubblished by an editor. I would like users (contributors) to be: - uncapable to add other posts of this custom type - capable to edit the already pubblished post they are author of - their changements must be approved by an editor before being pubblished I'm using User Role Editor to manage roles and capabilities. is there a way to do that?
|
Mine didn't work until I added the '99' , 2); to the end of the add_filter. Here is the reference as to why: http://codex.wordpress.org/Plugin_API/Filter_Reference/wp_insert_post_data <code> add_filter('wp_insert_post_data','re_aprove', '99', 2); function re_aprove( $data , $postarr ){ global $current_user; get_currentuserinfo(); //check if current user is not admin if (!current_user_can('manage_options') && $postarr['post_type'] == "candy-item" ){ if ($data['post_status'] = "publish"){ $data['post_status'] = "pending"; } } return $data; } </code>
|
How to let contributors to create a new revision(draft) editing their published posts
|
wordpress
|
I have a custom pagination function in functions.php. If I'm at the URL: http://mysite.com/tag/dogs , the Next link currently just contains /page/2. How can I make it so it will look like /tag/dogs/page/2? Here is the function I am using: (originally posted here ) <code> function pagination( $query, $baseURL = '' ) { if ( ! $baseURL ) $baseURL = get_bloginfo( 'url' ); $page = $query->query_vars["paged"]; if ( !$page ) $page = 1; $qs = $_SERVER["QUERY_STRING"] ? "?".$_SERVER["QUERY_STRING"] : ""; // Only necessary if there's more posts than posts-per-page if ( $query->found_posts > $query->query_vars["posts_per_page"] ) { echo '<ul class="paging">'; // Previous link? if ( $page > 1 ) { echo '<li class="previous"><a href="'.$baseURL.'page/'.($page-1).'/'.$qs.'">« previous</a></li>'; } // Loop through pages for ( $i=1; $i <= $query->max_num_pages; $i++ ) { // Current page or linked page? if ( $i == $page ) { echo '<li class="active">'.$i.'</li>'; } else { echo '<li><a href="'.$baseURL.'page/'.$i.'/'.$qs.'">'.$i.'</a></li>'; } } // Next link? if ( $page < $query->max_num_pages ) { echo '<li><a href="'.$baseURL.'page/'.($page+1).'/'.$qs.'">next »</a></li>'; } echo '</ul>'; } } </code> Any help would be greatly appreciated. Thanks!
|
Why can you not use the core functions <code> previous_posts_link() </code> / <code> next_posts_link() </code> or <code> posts_nav_link() </code> , all of which already account for the taxonomy archive context? EDIT: I think I understand your question now. You want pagination links, rather than previous/next page links. WordPress also has a native function for pagination links: <code> paginate_links() </code> ( Codex ref ). Here's how I use this function in my own Theme: <code> function oenology_paginate_archive_page_links( $type = 'plain', $endsize = 1, $midsize = 1 ) { global $wp_query, $wp_rewrite; $wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1; // Sanitize input argument values if ( ! in_array( $type, array( 'plain', 'list', 'array' ) ) ) $type = 'plain'; $endsize = (int) $endsize; $midsize = (int) $midsize; // Setup argument array for paginate_links() $pagination = array( 'base' => @add_query_arg('page','%#%'), 'format' => '', 'total' => $wp_query->max_num_pages, 'current' => $current, 'show_all' => false, 'end_size' => $endsize, 'mid_size' => $midsize, 'type' => $type, 'prev_text' => '&lt;&lt;', 'next_text' => '&gt;&gt;' ); if( $wp_rewrite->using_permalinks() ) $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' ); if( !empty($wp_query->query_vars['s']) ) $pagination['add_args'] = array( 's' => get_query_var( 's' ) ); echo paginate_links( $pagination ); } </code>
|
How to get category/tag in URL for Pagination links?
|
wordpress
|
I have learned how to create a post from the frontend but how about editing it ? This is the code stackexchange-url ("I am trying to create a simple frontend form for posting.") Thank you
|
Just like the example you linked, but instead of using <code> wp_insert_post() </code> you use: <code> wp_update_post() </code> so your form becomes: <code> <?php $post_to_edit = get_post($post_id); ?> <!-- edit Post Form --> <div id="postbox"> <form id="new_post" name="new_post" method="post" action=""> <p><label for="title">Title</label><br /> <input type="text" id="title" value="<?php echo $post_to_edit->post_title; ?>" tabindex="1" size="20" name="title" /> </p> <p><label for="description">Description</label><br /> <textarea id="description" tabindex="3" name="description" cols="50" rows="6"><?php echo $post_to_edit->content; ?></textarea> </p> <p><?php $cat = wp_get_post_terms( $post_to_edit->ID, 'category'); wp_dropdown_categories( 'show_option_none=Category&tab_index=4&taxonomy=categoryselected='.$cat[0]->term_id); ?></p> <p><label for="post_tags">Tags</label> <input type="text" value="<?php the_terms( $post_to_edit->ID, 'post_tag', '', ', ', '' ); ?>" tabindex="5" size="16" name="post_tags" id="post_tags" /></p> <p align="right"><input type="submit" value="Publish" tabindex="6" id="submit" name="submit" /></p> <input type="hidden" name="action" value="f_edit_post" /> <input type="hidden" name="pid" value="<?php echo $post_to_edit->ID; ?>" /> <?php wp_nonce_field( 'new-post' ); ?> </form> </div> <!--// edit Post Form --> </code> and the processing becomes: <code> if( 'POST' == $_SERVER['REQUEST_METHOD'] && !empty( $_POST['action'] ) && $_POST['action'] == "f_edit_post" && isset($_POST['pid'])) { //get the old post: $post_to_edit = get_post((int)$_POST['pid']); //do you validation //... //... // Add the content of the form to $post_to_edit array $post_to_edit['post_title'] = $_post['title'] $post_to_edit['post_content'] = $_post['description'] $post_to_edit['tags_input'] = array($_post['post_tags']) //save the edited post and return its ID $pid = wp_update_post($post_to_edit); //set new category wp_set_post_terms($pid,(array)($_POST['cat']),'category',true); } </code> now this has no validation so i leave it up to you.
|
How can I edit a post from the frontend?
|
wordpress
|
I know there are other, maybe better ways to do what I want to achieve, but I have to use this solution. I have two stylesheets: <code> style.css </code> - normal stylesheet <code> style-dynamic.php </code> - dynamic stylesheet linked to the first one I'm using some PHP code in the second one, like: <code> #body { background-color: <?php echo get_option('theme_background'); ?>; } </code> Now the point is that the <code> style-dynamic.php </code> file doesn't know WordPress functions, and the code above gives: Fatal error : Call to undefined function <code> get_option() </code> in C:\xampp\htdocs\wordpress\wp-content\themes\mytheme\style-dynamic.php on line 12 I guess I have to load <code> wp_load.php </code> (only?) and that's tricky, because I'm not sure how exactly? I was trying <code> require_once </code> , but I'm not sure I'll be able to jump from theme directory right to the WordPress main dir where <code> wp-load.php </code> file is? Edit Of course <code> require_once(ABSPATH . 'wp-load.php'); </code> Outputs another error: Use of undefined constant <code> ABSPATH </code> - assumed <code> 'ABSPATH' </code>
|
Christ, once again I was fighting with something for a few days straight and found a solution 20 minutes after asking on StackExchange. WHY? <code> require_once('../../../wp-load.php'); </code>
|
Call to undefined function issue
|
wordpress
|
So here's the problem, I want to have a few different meta boxes on my sites, but I'd like to be able to store each of them in separate files and included them into functions, so I can just copy specific ones to new installs and included them on a case by case basis. From what I can gather though, it seems like I need to put them all into one array?
|
Save each meta box out to a file with the code as if they were in your functions.php file. Maybe place these in a folder called meta_boxes. Then to include into your theme just <code> include() </code> them into your functions file <code> <?php // all the code that your functions file contains include("meta_boxes/meta1.php"); include("meta_boxes/meta2.php"); include("meta_boxes/meta3.php"); include("meta_boxes/meta4.php"); // As so on.... ?> </code>
|
Multiple Meta Boxes in separate files
|
wordpress
|
I'm trying to make something more meaningful out of the <code> wp_link_pages() </code> result: <code> $paged_page_nav = wp_link_pages( array( 'echo' => false ) ); // Now let's wrap the nav inside <li>-elements $paged_page_nav = str_replace( '<a', '<li class="'.$classes.'"><a', $paged_page_nav ); $paged_page_nav = str_replace( '/a>', '/a></li>', $paged_page_nav ); // here I'd need to wrap the currently displayed page element echo '<ul>'.$pages_page_nav.'</ul>'; </code> Currently my link pages (numbered nav/pagination) displays like this: <code> <!-- assuming we display page(d) 2/5 --> <ul> <li><a href="...">1</a></li> 2 <!-- This is the currently displayed paged, wrapped in nothing --> <li><a href="...">3</a></li> <li><a href="...">4</a></li> <li><a href="...">5</a></li> </ul> </code>
|
I wouldn’t use WordPress’ internal function. We had a very similar question recently: stackexchange-url ("How to style current page number (wp_link_pages)?") I wrote a small but flexible function to replace <code> wp_link_pages() </code> . It is probably easier to extend this than hacking around the return value of the native function.
|
wp_link_page - wrap current page element
|
wordpress
|
I need to clean up my database and I think that a way to do and keep it that way is by deleting all posts that have 3 days of life. One good thing is that those posts I want to delete are in a specific category. So, how can I clean up my database correctly by deleting or moving thoem and also their posts_meta or terms or anything ? I want to just have/show the posts that are 3 days or earlier.
|
here is a quick plugin i cooked for you :) <code> <?php /* Plugin Name: Post Auto Removal Plugin URI: http://en.bainternet.info Description: Post Auto Removal lets you schedule when the post / page / custom type will be deleted automatically. Version: 0.1 Author: bainternet Author URI: http://en.bainternet.info */ /* hook meta box */ add_action("admin_init", "admin_init"); /* hook meta box function */ function admin_init(){ add_meta_box("Post Auto Removal", "Post Auto Removal", "Post_Auto_Removal_options", "post", "normal", "high"); add_meta_box("Post Auto Removal", "Post Auto Removal", "Post_Auto_Removal_options", "page", "normal", "high"); } /* display meta box */ function Post_Auto_Removal_options() { global $post; $custom['active_removal'] = get_post_meta($post->ID,'active_removal',true); $custom['Remove_after'] = get_post_meta($post->ID,'Remove_after',true); echo '<input type="hidden" name="wp_meta_box_nonce" value="'. wp_create_nonce('Auto_Removal'). '" />'; ?> <table border=0> <tr> <th style="width:20%"><label for="active_removal">Activate auto removal:</label></th> <td><input type="checkbox" name="active_removal" id="active_removal" value="yes" <?php echo $custom['active_removal'] ? 'checked' : ''; ?>/><br/> when check post will be deleted in the given time. </td> </tr> <tr> <th style="width:20%"><label for="Remove_after">Delete post after:</label></th> <td><input type="text" name="Remove_after" id="Remove_after" value="<?php echo $custom['Remove_after'] ? $custom['Remove_after'] : ''; ?>"/><br/> Enter time in Seconds Ex: 1 Hour = 3600 Seconds , 1 Day = 86400 Seconds. </td> </tr> <?php $next = wp_get_schedule( 'Clean_my_posts', array($post_id)); print_r($next); if ($next){ ?> <tr> <th>next schedule is set to : <?php echo $next; ?></th> </tr> <?php } ?> </table> <?php } /* save meta box hook*/ add_action('save_post', 'save_Post_Auto_Removal_options'); /* save meta box function*/ function save_Post_Auto_Removal_options($post_id) { if (!wp_verify_nonce($_POST['wp_meta_box_nonce'], "Auto_Removal")) { return $post_id; } // check autosave if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $post_id; } If (isset($_POST['Remove_after']) && isset($_POST['active_removal'])){ //cerate scheduled event $time = time() + $_POST['Remove_after']; wp_schedule_single_event($time, 'Clean_my_posts',array($post_id)); //save meta data update_post_meta($post_id, 'Remove_after', $_POST['Remove_after']); update_post_meta($post_id, 'active_removal', $_POST['active_removal']); } } /* hook removal event function */ add_action('Clean_my_posts','auto_remove_post',1,1); // the function that deletes a post everything that is tied to it, This includes comments, post meta fields, and terms associated with the post. function auto_remove_post($post_id) { $delete = get_post_meta($post_id, 'active_removal', true); if ($delete){ wp_delete_post( $post_id, true ); } } </code>
|
Your ideas on my though "delete or move all of the posts in a specific category when 3 days are passed"
|
wordpress
|
Is there a way to know what functions are hooked to a particular hook? For example if I'd like to know what functions are hooked to the <code> wp_head </code> hook.
|
I'm pretty sure that this does what you want: @Rarst's Debug WordPress hooks
|
How to know what functions are hooked to an action/filter?
|
wordpress
|
I am in the process of migrating my blog from my wordpress.com address to a self-hosting (wordpress v3.1.2) address . Blog has migrated across nicely. Appears my users have also migrated across, but they cannot login with there old credentials (which are tied to wordpress.com, right)? I have around 30 users, and I would like to minimise the amoutn of work they have to do, to re-register to get access to the wp-admin console. What is the best way to keep the new users, but perhaps reset all there password to 'password'?
|
I don't know if you can see the email addresss of your users in wordpress.com blog as i never used it. If you can, as you have not too many users you may try to add them manually from wordpress dashboard and send them an email with the password if you have access to the email address.
|
Migrating users from .com to .org?
|
wordpress
|
I have a problem using the register_post_type and register_taxonomy on my Wordpress. I created the code on my functions.php and it does not update my panel. Why? <code> //Categorias personalizadas register_taxonomy('produtos', 'produto', array('hierarchical' => true, 'label' => 'Categorias de Produtos', 'query_var' => true, 'rewrite' => true)); //Posts personalizados add_action('init', 'create_post_type'); function create_post_type() { register_post_type('produto', array( 'labels' => array( 'name' => __('Produto'), 'singular_name' => __('Produto')), 'public' => true, 'rewrite' => true, 'supports' => array('title','editor','author','thumbnail','excerpt','comments','custom-fields','image'), 'has_archive' => true) ); } </code>
|
I copy pasted your code into my functions.php and it worked for me, make sure you are using a recent version of WordPress that supports Custom Post Types
|
register_taxonomy and register_post_type does not work
|
wordpress
|
I'm working on an internal project/idea (a directory of sorts for a vertical market) where I will have 40 Categories with each Category having (potentially) 30 Sub-Categories. For each Category and Sub-Category page we need to present (unique for each Cat and Sub-Cat) a block of rich text (and possibly an image) in the top of the first page, and some additional text in the bottom of the first page. Subsequent pages in the page-navi would just have standard Category (or Sub-Category) title. The text in the bottom of the page would be updated from time to time - so (relatively) easy content management would be ideal. I know I can create a conditional statement above the loop in a category.php page template to place the various text elements -- but that's one monster conditional statement. And I obviously don't want to create a unique category template for each. I'd rank myself an intermediate WP coder so I'm wondering if any of you Pro's have some insight. I'm not looking for code, just a general sense of best practice/strategy for how I might approach this so it's easy to manage through the WP Admin (ideally) going forward. Looking for a point in the right direction. I just can't seem to get my head around it.
|
If i understand correctly then this shouldn't be too hard and i would suggest using this Taxonomy Meta Script to simply add a rich editor , an image field and anything else you need for each category , this would make your life easier.
|
Dynamically Adding Category Specific Content To Specific Category & Subcategory Pages
|
wordpress
|
I'm using the advanced custom field plugin for wordpress and wondering if I'm able to do the following: If checkbox ticked = web and it equals the page title echo this. Does anyone know what code to use for this? UPDATE: The closest I've got is this: <code> <?php $fields = get_acf(); print_r ($fields->categories); ?> </code> But that is printing out this: <code> Array ( [0] => option_1 [1] => option_2 [2] => option_9 ) </code> 1. How can I print out the real names (without it saying array)? 2 Also say if it = web and matches the page title then echo something?
|
The way advanced custom field plugin handles checkboxes is in an array so you work with that array, for example if you field name is <code> categories </code> and you want to see if web (on of the checkboxes) was check you can use: <code> <?php if(in_array('web', get_field('categories') )): ?> <h1>Web was ticked!</h1> <?php endif; ?> </code> To answer your questions: How can I print out the real names (without it saying array)? if you want to print out the names instead of the array you can use: <code> $cats = get_field('categories'); echo '<ul>'; foreach ($cats as $key => $val){ echo '<li>'.$val.'</li>'; } echo '<ul>'; </code> this should give you something like: option_1 option_2 option_9 2 Also say if it = web and matches the page title then echo something? just like the first code snippet but just add another condition: <code> <?php if(in_array('web', get_field('categories') ) && $post->post_title == "web"){ echo '<h1>Web was ticked! and matches the page title</h1> } </code>
|
Displaying a checkbox array from advanced custom field
|
wordpress
|
I've got an issue with using the WP-Navi plugin and posts sorted alphabetically. The first page of posts (5 - set in the plugin settings) appearing properly, but when one navigates to subsequent pages, I lose that sort. In fact, I can't tell how the posts are being sorted - it appears to be random. The plugin's author has a description of this problem, but says that it's fixed in the plugin version that I have and I can't figure out where in the plugin code to verify. Should I abandon the plugin and try to code into the template or functions file? Can anyone help?
|
Switching to a new navigation plugin solved this problem! <code> http://wordpress.org/extend/plugins/wp-paginate/ </code>
|
WP-navi plugin and post sorted alphabetically
|
wordpress
|
Currently I'm using Simple Local Avatars on several of my blogs allowing people to upload their own custom avatar. As far as I know Simple Local Avatars uses <code> get_avatar </code> to check whether a custom avatar is selected, if not defaults to Gravatar.com. Would it be possible to disable the Gravatar.com bit somehow, disabling Gravatar.com completely and returning just some local hosted image if no custom avatar is selected? I hope it would be OK to post this here, but this would be the Simple Local Avatars file <code> <?php /* Plugin Name: Simple Local Avatars Plugin URI: http://www.get10up.com/plugins/simple-local-avatars-wordpress/ Description: Adds an avatar upload field to user profiles if the current user has media permissions. Generates requested sizes on demand just like Gravatar! Simple and lightweight. Version: 1.2.3 Author: Jake Goldman (10up), Oomph Inc Author URI: http://www.get10up.com */ // add field to user profiles class simple_local_avatars { function simple_local_avatars() { add_filter('get_avatar', array($this, 'get_avatar'), 10, 5); add_action('admin_init', array($this, 'admin_init')); add_action('show_user_profile', array($this, 'edit_user_profile')); add_action('edit_user_profile', array($this, 'edit_user_profile')); add_action('personal_options_update', array($this, 'edit_user_profile_update')); add_action('edit_user_profile_update', array($this, 'edit_user_profile_update')); add_filter('avatar_defaults', array($this, 'avatar_defaults')); } function get_avatar($avatar = '', $id_or_email, $size = '96', $default = '', $alt = false) { if (is_numeric($id_or_email)) $user_id = (int) $id_or_email; elseif (is_string($id_or_email)) { if ($user = get_user_by_email($id_or_email)) $user_id = $user->ID; } elseif (is_object($id_or_email) && !empty($id_or_email->user_id)) $user_id = (int) $id_or_email->user_id; if (!empty($user_id)) $local_avatars = get_user_meta($user_id, 'simple_local_avatar', true); if (!isset($local_avatars) || empty($local_avatars) || !isset($local_avatars['full'])) { if (!empty($avatar)) // if called by filter return $avatar; remove_filter('get_avatar', 'get_simple_local_avatar'); $avatar = get_avatar($id_or_email, $size, $default); add_filter('get_avatar', 'get_simple_local_avatar', 10, 5); return $avatar; } if (!is_numeric($size)) // ensure valid size $size = '96'; if (empty($alt)) $alt = get_the_author_meta('display_name', $user_id); // generate a new size if (empty($local_avatars[$size])) { $upload_path = wp_upload_dir(); $avatar_full_path = str_replace($upload_path['baseurl'], $upload_path['basedir'], $local_avatars['full']); $image_sized = image_resize($avatar_full_path, $size, $size, true); if (is_wp_error($image_sized)) // deal with original being >= to original image (or lack of sizing ability) $local_avatars[$size] = $local_avatars['full']; else $local_avatars[$size] = str_replace($upload_path['basedir'], $upload_path['baseurl'], $image_sized); update_user_meta($user_id, 'simple_local_avatar', $local_avatars); } elseif (substr($local_avatars[$size], 0, 4) != 'http') $local_avatars[$size] = site_url($local_avatars[$size]); $author_class = is_author($user_id) ? ' current-author' : ''; $avatar = "<img alt='" . esc_attr($alt) . "' src='" . $local_avatars[$size] . "' class='avatar avatar-{$size}{$author_class} photo' height='{$size}' width='{$size}' />"; return $avatar; } function admin_init() { load_plugin_textdomain('simple-local-avatars', false, dirname(plugin_basename(__FILE__)) . '/localization/'); register_setting('discussion', 'simple_local_avatars_caps', array($this, 'sanitize_options')); add_settings_field('simple-local-avatars-caps', __('Local Avatar Permissions', 'simple-local-avatars'), array($this, 'avatar_settings_field'), 'discussion', 'avatars'); } function sanitize_options($input) { $new_input['simple_local_avatars_caps'] = empty($input['simple_local_avatars_caps']) ? 0 : 1; return $new_input; } function avatar_settings_field($args) { $options = get_option('simple_local_avatars_caps'); echo ' <label for="simple_local_avatars_caps"> <input type="checkbox" name="simple_local_avatars_caps" id="simple_local_avatars_caps" value="1" ' . @checked($options['simple_local_avatars_caps'], 1, false) . ' /> ' . __('Only allow users with file upload capabilities to upload local avatars (Authors and above)', 'simple-local-avatars') . ' </label> '; } function edit_user_profile($profileuser) { ?> <h3><?php _e('Avatar', 'simple-local-avatars'); ?></h3> <table class="form-table"> <tr> <th><label for="simple-local-avatar"><?php _e('Upload Avatar', 'simple-local-avatars'); ?></label></th> <td style="width: 50px;" valign="top"> <?php echo get_avatar($profileuser->ID); ?> </td> <td> <?php $options = get_option('simple_local_avatars_caps'); if (empty($options['simple_local_avatars_caps']) || current_user_can('upload_files')) { do_action('simple_local_avatar_notices'); wp_nonce_field('simple_local_avatar_nonce', '_simple_local_avatar_nonce', false); ?> <input type="file" name="simple-local-avatar" id="simple-local-avatar" /><br /> <?php if (empty($profileuser->simple_local_avatar)) echo '<span class="description">' . __('No local avatar is set. Use the upload field to add a local avatar.', 'simple-local-avatars') . '</span>'; else echo ' <input type="checkbox" name="simple-local-avatar-erase" value="1" /> ' . __('Delete local avatar', 'simple-local-avatars') . '<br /> <span class="description">' . __('Replace the local avatar by uploading a new avatar, or erase the local avatar (falling back to a gravatar) by checking the delete option.', 'simple-local-avatars') . '</span> '; } else { if (empty($profileuser->simple_local_avatar)) echo '<span class="description">' . __('No local avatar is set. Set up your avatar at Gravatar.com.', 'simple-local-avatars') . '</span>'; else echo '<span class="description">' . __('You do not have media management permissions. To change your local avatar, contact the blog administrator.', 'simple-local-avatars') . '</span>'; } ?> </td> </tr> </table> <script type="text/javascript"> var form = document.getElementById('your-profile'); form.encoding = 'multipart/form-data'; form.setAttribute('enctype', 'multipart/form-data'); </script> <?php } function edit_user_profile_update($user_id) { if (!wp_verify_nonce($_POST['_simple_local_avatar_nonce'], 'simple_local_avatar_nonce')) //security return; if (!empty($_FILES['simple-local-avatar']['name'])) { $mimes = array( 'jpg|jpeg|jpe' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png', 'bmp' => 'image/bmp', 'tif|tiff' => 'image/tiff' ); $avatar = wp_handle_upload($_FILES['simple-local-avatar'], array('mimes' => $mimes, 'test_form' => false)); if (empty($avatar['file'])) // handle failures { switch ($avatar['error']) { case 'File type does not meet security guidelines. Try another.': add_action('user_profile_update_errors', create_function('$a', '$a->add("avatar_error",__("Please upload a valid image file for the avatar.","simple-local-avatars"));')); break; default: add_action('user_profile_update_errors', create_function('$a', '$a->add("avatar_error","<strong>".__("There was an error uploading the avatar:","simple-local-avatars")."</strong> ' . esc_attr($avatar['error']) . '");')); } return; } $this->avatar_delete($user_id); // delete old images if successful update_user_meta($user_id, 'simple_local_avatar', array('full' => $avatar['url'])); // save user information (overwriting old) } elseif (isset($_POST['simple-local-avatar-erase']) && $_POST['simple-local-avatar-erase'] == 1) $this->avatar_delete($user_id); } // remove the custom get_avatar hook for the default avatar list output on options-discussion.php function avatar_defaults($avatar_defaults) { remove_action('get_avatar', array($this, 'get_avatar')); return $avatar_defaults; } // delete avatars based on user_id function avatar_delete($user_id) { $old_avatars = get_user_meta($user_id, 'simple_local_avatar', true); $upload_path = wp_upload_dir(); if (is_array($old_avatars)) { foreach ($old_avatars as $old_avatar) { $old_avatar_path = str_replace($upload_path['baseurl'], $upload_path['basedir'], $old_avatar); @unlink($old_avatar_path); } } delete_user_meta($user_id, 'simple_local_avatar'); } } $simple_local_avatars = new simple_local_avatars; if (!function_exists('get_simple_local_avatar')): /* * more efficient to call simple local avatar directly in theme and avoid gravatar setup * * @param int|string|object $id_or_email A user ID, email address, or comment object * @param int $size Size of the avatar image * @param string $default URL to a default image to use if no avatar is available * @param string $alt Alternate text to use in image tag. Defaults to blank * @return string <img> tag for the user's avatar */ function get_simple_local_avatar($id_or_email, $size = '96', $default = '', $alt = false) { global $simple_local_avatars; return $simple_local_avatars->get_avatar('', $id_or_email, $size, $default, $alt); } endif; // on uninstallation, remove the custom field from the users and delete the local avatars register_uninstall_hook(__FILE__, 'simple_local_avatars_uninstall'); function simple_local_avatars_uninstall() { $simple_local_avatars = new simple_local_avatars; $users = get_users_of_blog(); foreach ($users as $user) $simple_local_avatars->avatar_delete($user->user_id); delete_option('simple_local_avatars_caps'); } </code>
|
If you want a super-lightweight solution and don't mind dabbling in a little code, drop this in your <code> functions.php </code> ; <code> function __default_local_avatar() { // this assumes default_avatar.png is in wp-content/themes/active-theme/images return get_bloginfo('template_directory') . '/images/default_avatar.png'; } add_filter( 'pre_option_avatar_default', '__default_local_avatar' ); </code> Alternatively, if you want a bit more juice, with the ability to manage everything in the admin, check out Add New Default Avatar. UPDATE: I wrote a quick plugin to be used alongside Simple Local Avatars. <code> <?php /** * Plugin Name: Disable Default Avatars * Plugin URI: stackexchange-url * Description: To be used alongside <a href="http://www.get10up.com/plugins/simple-local-avatars-wordpress/">Simple Local Avatars</a>, disabling all default avatars and falling back to a single image. Use the filter <code>local_default_avatar</code> to set the path of the image. * Version: 1.0 * Author: TheDeadMedic * Author URI: stackexchange-url */ if ( !function_exists( 'get_avatar' ) ) : /** * Retrieve the avatar for a user who provided a user ID or email address. * * @since 2.5 * @param int|string|object $id_or_email A user ID, email address, or comment object * @param int $size Size of the avatar image * @param string $default URL to a default image to use if no avatar is available * @param string $alt Alternate text to use in image tag. Defaults to blank * @return string <img> tag for the user's avatar */ function get_avatar( $id_or_email, $size = '96', $default = '', $alt = false ) { if ( ! get_option('show_avatars') ) return false; static $default_url; // use static vars for a little caching if ( !isset( $default_url ) ) $default_url = apply_filters( 'local_default_avatar', get_template_directory_uri() . '/images/default_avatar.png' ); if ( false === $alt) $safe_alt = ''; else $safe_alt = esc_attr( $alt ); if ( !is_numeric( $size ) ) $size = '96'; $avatar = "<img alt='{$safe_alt}' src='{$default_url}' class='avatar avatar-{$size} photo avatar-default' height='{$size}' width='{$size}' />"; return apply_filters( 'get_avatar', $avatar, $id_or_email, $size, $default, $alt ); } endif; function __limit_default_avatars_setting( $default ) { return 'local_default'; } add_filter( 'pre_option_avatar_default', '__limit_default_avatars_setting' ); if ( is_admin() ) : function __limit_default_avatars( $defaults ) { return array( 'local_default' => get_bloginfo( 'name' ) . ' Default' ); } add_filter( 'avatar_defaults', '__limit_default_avatars' ); endif; ?> </code> The plugin description should be self-explanatory, but essentially the default avatar is <code> http://wordpress-theme-path/images/default_avatar.png </code> , which can be filtered in your theme's <code> functions </code> .php if it exists elsewhere; <code> function __my_theme_default_avatar( $url ) { return 'http://somewhere/else.jpg'; } add_filter( 'local_default_avatar', '__my_theme_default_avatar' ); </code>
|
Removing Gravatar.com support for WordPress and Simple Local Avatars
|
wordpress
|
i'm trying to set up a mobile theme for my wordpress site. My desktop version uses themejunkie's weekly theme and my mobile version uses dotmobi theme. the Dotmobi theme pulls out the first image and displays as a thumbnail where as the weekly theme displays the 'featured image' as a thumbnail or a picture that is defined in a custom field value 'thumb' How can I make use of this same logic for dotmobi as well? I tried get_thumbnail() but that doesn't work. Any help on this please. I also tried by putting this code into my functions.php <code> // Get image attachment (sizes: thumbnail, medium, full) function get_thumbnail($postid=0, $size='full') { if ($postid<1) $postid = get_the_ID(); $thumb_key = get_theme_mod('thumb_key'); if($thumb_key) $thumb_key = $thumb_key; else $thumb_key = 'thumb'; $thumb = get_post_meta($postid, $thumb_key, TRUE); // Declare the custom field for the image if ($thumb != null or $thumb != '') { return $thumb; } elseif ($images = get_children(array( 'post_parent' => $postid, 'post_type' => 'attachment', 'numberposts' => '1', 'post_mime_type' => 'image', ))) { foreach($images as $image) { $thumbnail=wp_get_attachment_image_src($image->ID, $size); return $thumbnail[0]; } } else { return get_bloginfo ( 'stylesheet_directory' ).'/images/default_thumb.gif'; } } </code> and called the same in my index.php through <code> <?php echo '<a href="'.get_permalink($post->ID).'" rel="bookmark"><img src="'.get_bloginfo('template_url').'/timthumb.php?src='.get_thumbnail($post->ID, 'full').'&amp;h='.$height.'&amp;w='.$width.'&amp;zc=1" alt="'.get_the_title().'" /></a>' ?> </code> For some odd reason the thumbnails aren't displaying
|
Try this code. Then temporarily set permissions to the cache folder to 774 and the timthumb.php file to 750, you can increase or decrease the permissions as you see fit (or aslong as it stops working, then it'll be time to loosen up the permissions). <code> <?php // If there are images get them if ( $images = get_children(array( 'post_type' => 'attachment', 'numberposts' => 1, 'post_status' => null, 'post_parent' => $post->ID ))); foreach( $images as $image ) { $attachment = wp_get_attachment_image_src( $image->ID ); // Variables for timthumb $width = 160; $height = 160; $zoom_crop = 1; ?> <a href="<?php the_permalink() ?>" rel="bookmark" title="<?php esc_attr( printf( __( 'Click to read %s', 'truereps' ), get_the_title() ) ); ?>"> <img src="<?php bloginfo( 'template_directory' ); ?>/inc/scripts/timthumb.php?src=<?php echo $attachment[0]; ?>&amp;w=<?php echo $width; ?>&amp;h=<?php echo $height; ?>&amp;zc=<?php echo $zoom_crop; ?>" alt="<?php the_title(); ?>" /> </a> <?php } ?> </code>
|
Display featured image as post thumbnail
|
wordpress
|
1 custom taxonomy registered for 2 different CPT (custom post type). When i entered to edit tag section on edit-tags.php?taxonomy=mytaxonomy&post_type=cpt1 it displays total post count of 2 different CPT. Is there any way to fix that?
|
This is a known issue see Custom taxonomy count includes draft & trashed posts . It might not be fixed in version 3.2 but most likely in the next version.
|
post count is wrong when using same taxonomy for 2 different CPT
|
wordpress
|
Ok, bit of a weird one... I want to include php code on one of my pages within the content by adding something like: <code> Welcome to the payment page [paymentform] Blash blah vlha... </code> And then [paymentform] resolves to a bit of code either somewhere on the filesystem or within the database and handled by a settings page in the backend. I didn't want to use the exec-php plugin for several reasons - mainly I don't want our client messing with the php code, secondly there are limitations using that with the visual editor etc..etc.. Cheers, John.
|
Have a look at the Shortcodes API http://codex.wordpress.org/Shortcode_API
|
Looking for a good way to include php code in posts, but using special include markup rather than direct php code
|
wordpress
|
As you can guess from the title, Im looking for a solution that allows me to alter the way Wordpress processes/saves its newly created images according to the media settings in the dashboard. This is very important since I primarily use Wordpress as a way to present portfolio images so they need to maintain the same color profile, etc. as they had when they were first uploaded. The problem is, once an image is resized by wordpress it tends to become desaturated because it changes the color profile, this needs to be altered somehow so that it stays the same as the original and only the pixel dimensions are changed. The easiest solution to this is to prepare your images to the exact size to be used prior to upload and then use the images actual size setting in wordpress' dialog while placing an image into a post, however this is not very convenient, nor is it exactly a very nice solution for clients that dont understand how to do such a thing before uploading.... Ultimately, Id like to avoid the use of a plugin and just alter the existing script that wordpress uses to process its photos/images, or possibly create a special function for the functions.php template if thats possible.... Thanks for the help in advance.
|
You can try looking at this plugin WordPress ImageMagick Engine Replaces wordpress image resizing from GD to ImageMagick. You need a compatible host to use it though
|
How to resize images in wordpress without adding any compression or changing the color profile of the images, possible?
|
wordpress
|
How do I hide the page editor (WYSIWYG editor) if the current page is set to a certain template. I have the following code already to add in custom meta boxes when certain templates are chosen: <code> add_action('admin_init','my_meta_init'); function my_meta_init() { $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID']; $template_file = get_post_meta($post_id, '_wp_page_template', TRUE); $savemeta = true; if ($template_file == 'template-page-2quotes.php') { add_meta_box('main_quote_meta-meta', 'Top Quote', 'main_quote_meta', 'page', 'side', 'low'); add_meta_box('sub_quote_meta-meta', 'Right Hand Side Quote', 'sub_quote_meta', 'page', 'normal', 'low'); } elseif ($template_file == 'template-page-1quote.php') { add_meta_box('sub_quote_meta-meta', 'Right Hand Side Quote', 'sub_quote_meta', 'page', 'normal', 'low'); } elseif ($template_file == 'template-page-factsnfigures.php') { add_meta_box('facts_n_figures-meta', 'Amount Raised', 'facts_n_figures', 'page', 'normal', 'low'); } elseif ($template_file == 'template-page-fundraising.php') { add_meta_box('fundraising_ideas-meta', 'Fundraising Ideas', 'fundraising_ideas', 'page', 'side', 'low'); } else { $savemeta = false; } if($savemeta == true) { add_action('save_post','my_meta_save'); } } </code> What I would like for example is that the editor is removed if <code> $template_file == 'template-page-2quotes.php' </code> Edit (Working Code): <code> add_action('admin_init','my_meta_init'); function my_meta_init() { $post_id = $_GET['post'] ? $_GET['post'] : $_POST['post_ID']; $template_file = get_post_meta($post_id, '_wp_page_template', TRUE); $savemeta = true; $hideeditor = false; if ($template_file == 'template-page-2quotes.php') { add_meta_box('main_quote_meta-meta', 'Top Quote', 'main_quote_meta', 'page', 'side', 'low'); add_meta_box('sub_quote_meta-meta', 'Right Hand Side Quote', 'sub_quote_meta', 'page', 'normal', 'low'); } elseif ($template_file == 'template-page-1quote.php') { add_meta_box('sub_quote_meta-meta', 'Right Hand Side Quote', 'sub_quote_meta', 'page', 'normal', 'low'); } elseif ($template_file == 'template-page-factsnfigures.php') { add_meta_box('facts_n_figures-meta', 'Amount Raised', 'facts_n_figures', 'page', 'normal', 'low'); } elseif ($template_file == 'template-page-fundraising.php') { add_meta_box('fundraising_ideas-meta', 'Fundraising Ideas', 'fundraising_ideas', 'page', 'side', 'low'); } elseif($template_file == 'template-page-news.php') { $hideeditor = true; $savemeta = false; } else { $savemeta = false; } if($savemeta == true) { add_action('save_post','my_meta_save'); } if($hideeditor == true) { add_action('admin_print_styles', 'admin_no_editor_style'); } } function admin_no_editor_style() { echo "<style>#postdivrich{display:none;}</style>"; } </code>
|
<code> add_action('init', 'remove_editor_init'); function remove_editor_init() { // if post not set, just return // fix when post not set, throws PHP's undefined index warning if (isset($_GET['post'])) { $post_id = $_GET['post']; } else if (isset($_POST['post_ID'])) { $post_id = $_POST['post_ID']; } else { return; } $template_file = get_post_meta($post_id, '_wp_page_template', TRUE); if ($template_file == 'page-your-template.php') { remove_post_type_support('page', 'editor'); } } </code>
|
Hide page visual editor if certain template is selected?
|
wordpress
|
I'm trying out the 2 comment reporting plugins that I know about in a multisite installation. AJAX Report Comments Safe Report Comments Both don't work - various javascript errors and (I assume) not taking into account the differences between single and multisite WP. Does anyone know of a working comment reporting plugin for Multisite, or has anyone run into issues with the above plugins before? [Update] Using Ajax Report Comments Clicking on the "Report comment" link correctly opens a textbox. Clicking on the "Report comment" button (which should fire off the report) raises the following error in chrome's javascript console <code> Uncaught SyntaxError: Unexpected token mysack.onCompletion runAJAX.xmlhttp.onreadystatechange </code> The inserted javascript is as follows: <code> <script type="text/javascript"> //<![CDATA[ function reportComment( commentID ) { var reporter_comment = document.getElementById( 'reportcomment_comment_textarea_' + commentID ).value; var mysack = new sack( 'http://test-staffblogs.nature.com/news/wp-content/plugins/report-comments/report.php?c='+commentID+'&r='+escape(reporter_comment) ); mysack.method = 'POST'; mysack.onError = function() { alert( "Error Error Error" ) }; mysack.onCompletion = function() { finishReport( commentID, eval( '(' + this.response + ')' )); } mysack.runAJAX(); } function reportComment_AddTextArea( commentID ) { document.getElementById( 'reportcomment_results_div_' + commentID ).innerHTML = "Why are you doing this?"; var textarea = "<textarea name=\"reportcomment_comment_textarea_" + commentID + "\" id=\"reportcomment_comment_textarea_" + commentID + "\" cols=\"55\" rows=\"4\" class=\"reportcomment_textarea\"></textarea><br /><input type=\"button\" name=\"Report Comment\" value=\"Report Comment\" onclick=\"reportComment( " + commentID + " );\" />"; document.getElementById( 'reportcomment_comment_div_' + commentID ).innerHTML = textarea; } function finishReport( commentID, response ) { var message = '<span class="reportedcomment_text">'+response.message+'</span>'; document.getElementById( 'reportcomment_results_div_' + commentID ).innerHTML = message; document.getElementById( 'reportcomment_comment_div_' + commentID ).innerHTML = ''; } //]]> </script> </code>
|
(Copy from comment to make the solution appear in our search results) Use the Report Comments Plugin from Dagon Design.
|
Comment reporting for Multisite
|
wordpress
|
Could you please suggest me good plugins (that you have used) for translating a WordPress website? It should be wonderful if you can add as well a pros and cons list with your suggestion. Thanks in advance!
|
I'll speak for qTranslate, I've used it a few times and been pretty happy with it. What it sets out to do - letting you offer translations of post content in multiple languages and switch between them - it does pretty well. It gets a bit dicey when you try to extend it beyond alternate language versions of posts, though. I had to hack a lot to use the language filters on category titles and descriptions, for instance, or products with different currencies, etc. For the most part, qtranslate's approach is pretty straightforward: you put the various languages within shortcodes so the title "My Title" would be entered like this: <code> [lang_en]My Title[/lang_en][lang_es]Mi Titulo[/lang_es] ... </code> The plugin hacks up the default post editor nicely to handle that bit transparently to you. But if you want to translate other parts of the site - widget content, etc. - you have to enter that markup yourself. Works well for basic blogs, but if you're trying to do more with internationalization, you might want to look at some of the other discussions that have happened about offering multi-lingual content. Here's a few: stackexchange-url ("What are options are there to implement a multi language site") stackexchange-url ("Best practices for localizing WordPress content?")
|
Suggestions for i18n plugin
|
wordpress
|
Here is what I want to have My category Structure in WP admin <code> Cat Parent -Cat Child 1 -Cat Child 2 -Cat Child 3 -Cat Child 1 </code> This what I want to have in one template: It show the list of post in Cat Parent Children Category <code> Cat Child 1 -Post1 Child 1 -Post2 Child 1 -Post3 Child 1 -So on... . Cat Child 2 -Post1 Child 2 -Post2 Child 2 -Post3 Child 2 -So on... . Cat Child 3 -Post1 Child 3 -Post2 Child 3 -Post3 Child 3 -So on... . </code> Does anyone have done it before or anyone have an idea on how to code this? Thanks
|
get the child categories, using get_categories() ; then loop through them with a foreach loop, using WP_Query() : <code> <?php $cats = get_categories('child_of='.get_query_var('cat')); foreach ($cats as $cat) : $args = array( 'posts_per_page' => 3, // max number of post per category 'category__in' => array($cat->term_id) ); $my_query = new WP_Query($args); if ($my_query->have_posts()) : echo '<h3>'.$cat->name.'</h3>'; while ($my_query->have_posts()) : $my_query->the_post(); ?> <?php /*general loop output; for instance: */ ?> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a> <br /> <?php endwhile; ?> <?php else : echo 'No Posts for '.$cat->name; endif; endforeach; ?> </code>
|
How to get child category list post in one template?
|
wordpress
|
My theme automatically assign before of <code> <!--more--> </code> tags, as excerpt.And showing excerpt on home page. Now i want to add Google Adsense after <code> <!-- more --> </code> code. I'm wrote this function and add it to functions.php <code> function google_adsense($content) { if(is_single()) { global $post; $thePostID = $post->ID; $more_span = '<span id="more-' .$thePostID.'"></span>' ; return str_replace($more_span, $more_span . " " . google_reklam_ekle(), $content); } } function google_reklam_ekle() { return "<!-- Google Adsense --> <script type=\"text/javascript\"><!-- google_ad_client = \"ca-pub-9792205570091420\"; /* teknoblogo-yazi-alaninda */ google_ad_slot = \"0917868905\"; google_ad_width = 468; google_ad_height = 60; //--> </script> <script type=\"text/javascript\" src=\"http://pagead2.googlesyndication.com/pagead/show_ads.js\"> </script> <!-- bit Google Adsense -->"; } add_filter('the_content', 'google_adsense'); </code> Now excerpts isn't disappering excerpts. When i remove this functions, they're appearing again. In single page, code is working very well. You can check my blog posts. http://www.teknoblogo.com . There is an Adsense Ads after tag. But before add this Adsense codes, my post's first part (i mean before of <code> <!--more--> </code> tag) appearing . Can you give an idea to me ?
|
you have forgotten to return the unaltered $content if this is not a single post: <code> function google_adsense($content) { if(is_single()) { global $post; $thePostID = $post->ID; $more_span = '<span id="more-' .$thePostID.'"></span>' ; return str_replace($more_span, $more_span . " " . google_reklam_ekle(), $content); } else { return $content; } } </code>
|
Excerpt Is Disappeared
|
wordpress
|
What is the best way to disable feeds per post type but keep has_archive enabled?
|
I ran into this issue today. I don't know if it's the best way, but here's how I solved it (with <code> has_archive </code> still set to true, of course): <code> // First we remove WP default feed actions // If we stop here, feeds would be disabled altogether remove_action('do_feed_rdf', 'do_feed_rdf', 10, 1); remove_action('do_feed_rss', 'do_feed_rss', 10, 1); remove_action('do_feed_rss2', 'do_feed_rss2', 10, 1); remove_action('do_feed_atom', 'do_feed_atom', 10, 1); // Now we add our own actions, which point to our own feed function add_action('do_feed_rdf', 'my_do_feed', 10, 1); add_action('do_feed_rss', 'my_do_feed', 10, 1); add_action('do_feed_rss2', 'my_do_feed', 10, 1); add_action('do_feed_atom', 'my_do_feed', 10, 1); // Finally, we do the post type check, and generate feeds conditionally function my_do_feed() { global $wp_query; $no_feed = array('cpt_1', 'cpt_2'); if(in_array($wp_query->query_vars['post_type'], $no_feed)) { wp_die(__('This is not a valid feed address.', 'textdomain')); } else { do_feed_rss2($wp_query->is_comment_feed); } } </code> Please note that this will cause all feeds to generate as RSS 2.0, when they do generate, but you get general idea.
|
How to use has_archive but disable feed per post type?
|
wordpress
|
I'm using this code: <code> $args = array( 'hide_empty' => FALSE, 'title_li'=> __( '' ), 'show_count'=> 1, ); wp_list_categories($args); </code> How can i wrap the post count in a span for further styling? Thanks
|
adding a filter to functions.php of your theme is one possibility: <code> add_filter('wp_list_categories', 'cat_count_span'); function cat_count_span($links) { $links = str_replace('</a> (', '</a> <span>(', $links); $links = str_replace(')', ')</span>', $links); return $links; } </code> this would add the spans to any occurrence of 'wp_list_categories()' site wide. or change your code into: <code> $args = array( 'hide_empty' => FALSE, 'title_li'=> __( '' ), 'show_count'=> 1, 'echo' => 0 ); $links = wp_list_categories($args); $links = str_replace('</a> (', '</a> <span>(', $links); $links = str_replace(')', ')</span>', $links); echo $links; </code>
|
Wrap Post count in a span
|
wordpress
|
I need to display comments starting from the second, omitting the first. With posts I did it using "offset" but I can't find anything similar for comments. Since I'm using threaded comments, must start from the second comment that is not a child (only parent comments). I'm using wp_list_comments with a callback. EDIT2: this is actual comments.php code, after replies: <code> <?php $i = 2; if ( have_comments() ) : if ( $i > 1 ) : ?> <div id="comments"> <h3 id="comments-title" class="color-<?php $category = get_the_category(); echo $category[0]->cat_name;?>"> </h3> <?php global $wp_query; $comments_arr = $wp_query->comments; $comments_arr = sort( $comments_arr); $comments_arr = array_pop( $comments_arr ); $comments_arr = usort($comment_arr, 'comment_comparator'); wp_list_comments('callback=gtcn_basic_callback', $comments_arr); ?> <?php $i++; // count up endif; // If $i > 1 else : if ( ! comments_open() ) : ?> <p><?php _e( 'Comments are closed.' ); ?></p> <?php endif; // end ! comments_open() endif; // end have_comments() ?> </div> <?php comment_form(); ?> </code> Result: comments are not anymore ordered by karma (comment_comparator function) and the first comment (comment with top karma that I want to hide) is still displayed.
|
<code> <?php global $wp_query, $post; $comments_arr = $wp_query->comments; $comments_arr = sort( $comments_arr); $comments_arr = array_pop( $comments_arr ); $comments_arr = usort($comment_arr, 'comment_comparator'); $comment_count = get_comment_count($post->ID); ?> <h3 id="comments-title"><?php printf( _n( 'One Response to %2$s', '%1$s Responses to %2$s', get_comments_number(), 'YOUR_THEMES_TEXTDOMAIN' ), number_format_i18n( get_comments_number() ), '<em>' . get_the_title() . '</em>' ); ?></h3> if ( have_comments() ) : ?><ul class="commentlist"><?php for ( $i = 0; $i < $comment_count; $i++ ) { // do stuff: // This shows you everything you got inside the comments array // Call it like this: echo $comments_arr[$i]['comment_author']; var_dump( $comments_arr[$i] ); // end do stuff } // endforeach; ?></ul><?php elseif ('open' == $post->comment_status) : // If there are no comments, but status = open ?><p class="nocomments"><?php _e( 'No Comments.', 'YOUR_THEMES_TEXTDOMAIN' ); ?></p><?php endif; // If $i > 1 else : // or, if comments are not allowed: if ( ! comments_open() ) : ?> <p class="nocomments"><?php _e( 'Comments are closed.', 'YOUR_THEMES_TEXTDOMAIN' ); ?></p> <?php endif; // end ! comments_open() endif; // end have_comments() ?> </code> Ad your current loop: No need for <code> $counter = 2; </code> (called nowhere). If you already got your <code> $comments_arr </code> , why not simply: <code> $comments_arr = sort( $comments_arr); $comments_arr = array_pop( $comments_arr ); $comments_arr = usort( $comments_arr ); </code> OR <code> $comments_arr = unset( $comments_arr[0] ); $comments_arr = usort( $comments_arr ); </code>
|
Comments offset
|
wordpress
|
If I create a custom post type and want to create custom capabilities for that, how do I do this? For example, I want to let my Editors to edit and create and delete posts and pages, but not the custom post type I've created? I also want to have the possibility to change the capabilities later with this plugin: http://wordpress.org/extend/plugins/user-role-editor/ (see the screens of the available capabilities: http://wordpress.org/extend/plugins/user-role-editor/screenshots/ ) I've done this by now this way: <code> global $wp_roles; if(!isset($wp_roles)) { $wp_roles = new WP_Roles(); } // add capability $cap to role $role $roles = $wp_roles->get_names(); $wp_roles->add_cap('administrator', 'organize_matches'); </code> But then even I as administrator am not able to save the custom post type (and yeah, I mentioned 'organize_matches' in the 'capabilities' argument when registering the custom post type). Really appreciate Your help!
|
Use <code> 'capability_type' </code> & <code> 'capabilities' </code> when you <code> register_post_type() </code> .
|
Define new user capability for custom post types?
|
wordpress
|
If you have a category called "term" and a subcategory called "subterm", your can access subterm posts at /cat/subcat. But this doesn't work out of the box with custom taxonomies. They are accessible at /taxonomy/subterm, but not /taxonomy/term/subterm. They've gone over this in the Wordpress Trac ( http://core.trac.wordpress.org/ticket/12659 ), and it kind of looks like they have a solution, but as I've never used the Trac and don't fully understand its language (diffs, etc), I need someone more experienced to actually tell me how to implement this. Is there code there that I have to paste into Wordpress core files? Is this already implemented and I can add something to my theme's functions.php? If possible I'd prefer not to modify any core files. Help!
|
This is implemented in WordPress now as of 3.1. When you register your taxonomy , make sure to set rewrite hierarchical to true as well as the taxonomy itself: <code> <?php register_taxonomy('genre',array('book'), array( 'hierarchical' => true, // this makes it hierarchical in the UI 'labels' => $labels, 'show_ui' => true, 'query_var' => true, 'rewrite' => array( 'hierarchical' => true ), // this makes hierarchical URLs )); </code>
|
How to enable hierarchical permalinks for hierarchical taxonomies
|
wordpress
|
I want to display a single random post out of the 5 latest posts in the category 'news'. The approach I'm using is this: <code> // Custom function to retrieve catgory ID by category name. $cat = $lib->getCatIDbyCatName('news'); // Retrieve the 5 latest posts $news = get_posts( array( 'numberposts' => 5,'category_name' => $cat ) ); foreach($news as $post) : setup_postdata($post); echo the_title(); echo the_intro(); // <- Custom function to retrieve custom field endforeach; </code> The above code works and I'm dispalying the title and the custom value of all 5 posts. Now I only want one random post out of these 5 posts. So I do this: <code> // Get a single random post from fetched posts $single_news = $news[rand(0, 4)]; foreach($single_news as $post) : setup_postdata($post); echo the_title(); echo the_intro(); // <- Custom function to retrieve custom field endforeach; </code> This however, is not working. Does anyone have any ideas of what I can do? OR maybe a better solution?
|
<code> // Get a single random post from fetched posts $post = $news[rand(0, 4)]; setup_postdata($post); echo the_title(); echo the_intro(); // <- Custom function to retrieve custom field </code>
|
Not able to get random post
|
wordpress
|
If I do a post or a page with no title, I'm left with an empty <code> h1 </code> tag at the top of the post/page. I'd like to either get rid of the <code> h1 </code> in these cases, or else be able to add an extra CSS class to the post/page so that I can specify how to display the post (and the <code> h1 </code> ) differently when the post/page is published with no title. Are either of these things possible? Thanks.
|
To add an extra class when there is no title <code> <h1<?php if(!get_the_title()){echo ' class="no-title"';}?>><?php the_title();?></h1> </code> Or to only display h1 tags when there is a title <code> <?php if(get_the_title()) { ?> <h1><?php the_title();?></h1> <?php }?> </code>
|
Is there a way to specify an extra class for a post or page with no title?
|
wordpress
|
I'm having trouble with the 'Remote Login' option of MultiSite domain mapping. I have a local dev install which allows me to swap between network blogs without needing to login to each blog individually (which is my understanding of what Remote Login allows?). But the live version of the Network forces all users to login to each network blog individually (which is frustrating). I have picked Otto's brain about it --as he mentioned some time ago that the Remote Login feature was "iffy at best"-- and he suggest he's not had any later success without custom scripting. @pwcc has had success with it though not whilst using Theme My Login plugin (which I'm using). Any suggestions anyone? I have tested in multiple browser, and cleared cookies I do not have any cache plugins installed
|
I wonder why there seem to be so few people having trouble with this. It's a major bug and thus I created the following ticket just now: https://core.trac.wordpress.org/ticket/18069 Not an answer, but just FYI.
|
'Remote Login' with MultiSite Domain Mapping still forcing users to login to all blogs individually?
|
wordpress
|
I have just started a programming blog and I am using the SyntaxHightlighter Evolved plugin to format my code. On most browsers this is working just fine. However if I attempt to view the site from either an iPhone or iPad the line numbers and code are no longer aligned. Basically the problem seems to be that the line numbers and code fonts are sized independently (see image below). I assumed somebody else must have seen the problem so I consulted The Mightly Oracle Google, but could not seem to find anything relevant. I have also searched this site to no avail. Being a programmer I looked at the source code, but realized that it would take me some time to understand how it works and fix the problem. I am using Wordpress version 3.1.2 with the Twenty Ten theme version 1.2 I have the following plugins active: Google Analytics for WordPress version 4.1 SyntaxHighlighter version 3.1.1 Has anybody else seen (an hopefully fixed) this problem? Or could some kind soul point me in the right direction? If you need to see the website there is a link in my profile to it. I don't want to link-spam ;-) Thanks in advance! UPDATE: 5/17/2011 I thought I had found a solution but, while it solved the problem on the iPad, it remained an issue on the iPhone. So the bounty is still up for grabs.
|
It turns out that the style sheet (style.css) for the Twenty Ten theme modifies the size of <code> pre </code> and <code> code </code> independently. This appears to be what is causing the problem. Moreover it increases the size of the fonts which causes them to be too big when compared to the rest of the text. These are the lines that cause the issue: <code> /* =Mobile Safari ( iPad, iPhone and iPod Touch ) -------------------------------------------------------------- */ pre { -webkit-text-size-adjust: 140%; } code { -webkit-text-size-adjust: 160%; } </code> I commented out these two sections: <code> /* =Mobile Safari ( iPad, iPhone and iPod Touch ) -------------------------------------------------------------- */ /* pre { -webkit-text-size-adjust: 140%; } code { -webkit-text-size-adjust: 160%; } */ </code> So I guess I am in the strange position of answering my own question. Thanks to all who took time to look at this. Especially @DaveKonopka who at the time of writing was the only one to come up with a possible solution.
|
Code Formatted with SyntaxHighlighter Evolved Appearing Incorrectly on iPad/iPhone
|
wordpress
|
I can't find any plugin or script to place a "report as spam" button in my comments section. The button could simply: - open a form to report a spammy or problematic comment to the admin - send an email or store in the db the problematic comment ID ready for being checked/deleted by admin. I have a lot of comments that are not really spam, but people trying to advertise products/services where they shouldn't (akismet of course doesn't work for them). It could add an extra layer of spam fighting with the direct help of users. Any ideas on how to achieve that?
|
There a a few plugins that allow visitors to report comments AJAX Report Comments Safe Report Comments
|
Report spam button
|
wordpress
|
I am actually displaying a number beside my comments putting <code> $counter = 0; </code> before wp_list_comments in comments.php and <code> global $counter; $counter++; </code> inside the comments callback function in functions.php Now this is working fine, but since I'm using threaded comments, my numbers are looking strange (1,4,10,14) because it's counting also the child comments. Is there a way to count only parent comments (1,2,3,4,5...)? Thanks
|
You can check if the comment has a parent and only count if not: <code> global $counter; if ($comment->parent == 0){ $counter++; } </code>
|
Numbering only parent comments
|
wordpress
|
What's the best practice for handling CSS on a theme with multiple page templates? For example: I will have a Full Width page template and a 2-column page template. Is it best to just call out the containers in a single CSS (#fullWidthContainer vs. #twoColumnContainer) Or is it better to have separate CSS files for each page template?
|
This isn't really WordPress specific, but from the server perspective it would add additional http requests for visitors to load additional css files, versus pulling the same site-wide css file from cache. From a css perspective, I prefer to keep it all in one file. Some people prefer to organize things differently, like all text styles in one file and then layout specific stuff in another. In that case, they may keep layouts specific to certain templates separate. For simple layout differences, I do something like: template a: <code> <div id="main-content" class="full-width"> </div> </code> template b: <code> <div id="main-content" class="narrow-width"> </div> </code> css: <code> #main-content { /* common to all content */ } .full-width { width:500px; } .narrow-width { width:300px; } </code> I keep IDs meaningful to the content, and use classes to define layout.
|
Multiple Page Templates & CSS
|
wordpress
|
I'm writing my own plugin. works like this: <code> function myfunc (){ $a = 'hello'; // the sentence what Am looking for: if ( user is logged and is the author of current post / page ){ $a= 'author'; } return $a; } </code> Wondering how I can do that sencence / function?
|
Just compare display names: <code> $currentuser = get_currentuserinfo(); if ( get_the_author() == $currentuser->displayname ) { // current user is the post author; do something } </code> The <code> get_the_author() </code> function returns <code> displayname </code> , which should be able to be compared against the <code> displayname </code> parameter that is a part of the <code> $currentuser </code> object.
|
Show info to author only
|
wordpress
|
Im not sure if you guys have encountered this problem, but WordPress appends empty <code> <p> </code> tags before and after the body of text from the <code> comment_text() </code> function. Strangely, when you <code> echo get_comment_text() </code> or <code> echo $comment->comment_content </code> (same thing) the empty <code> <p> </code> tags disappear before and after the body of text. This is entirely exclusive to a call to <code> comment_text() </code> . If you'd like to recreate it the problem, give your <code> <p> </code> tags top and bottom padding. Anyway to fix this?
|
If you look in <code> wp-includes/default-filters.php </code> you'll see all of the functions each comment is run through before it's output. I'd guess it's the last one, wpautop, which adds p tags in place of line breaks: <code> add_filter( 'comment_text', 'wptexturize' ); add_filter( 'comment_text', 'convert_chars' ); add_filter( 'comment_text', 'make_clickable', 9 ); add_filter( 'comment_text', 'force_balance_tags', 25 ); add_filter( 'comment_text', 'convert_smilies', 20 ); add_filter( 'comment_text', 'wpautop', 30 ); </code> You can <code> remove_filter( 'comment_text', 'wpautop', 30 ); </code> to confirm, but you'll lose paragraphs entirely.
|
How to disable empty tags in comment_text()
|
wordpress
|
Every time I edit a WordPress post or page that has a google map embedded in it - useing the "visual" edit mode - wordpress deletes part of the data. for example: this <code> <iframe width="425" height="350" frameborder="0" scrolling="no" marginheight="0" marginwidth="0" src="http://maps.google.com/maps/ms?ie=UTF8&amp;hl=en&amp;msa=0&amp;msid=212526618623367333770.00049b7dc074f6426719d&amp;t=h&amp;ll=34.926059,-81.964874&amp;spn=0.300106,0.458336&amp;output=embed"></iframe><br /><small>View <a href="http://maps.google.com/maps/ms?ie=UTF8&amp;hl=en&amp;msa=0&amp;msid=212526618623367333770.00049b7dc074f6426719d&amp;t=h&amp;ll=34.926059,-81.964874&amp;spn=0.300106,0.458336&amp;source=embed" style="color:#0000FF;text-align:left">1825 Spartanburgh Map</a> in a larger map</small> </code> turns into <code> <small>View <a style="color: #0000ff; text-align: left;" href="http://maps.google.com/maps/ms?ie=UTF8&amp;hl=en&amp;msa=0&amp;msid=212526618623367333770.00049b7dc074f6426719d&amp;ll=34.926059,-81.943846&amp;spn=0.300106,0.416279&amp;source=embed">1825</a> in a larger map</small> </code> Which does not render the map at all. This does not happen when I edit in "html" mode. How can I prevent Wordpress from altering this embed code?
|
The issue is WordPress' core configuration of TinyMCE, which strips IFRAME tags. You can modify this configuration, to allow IFRAME tags, by hooking into <code> tiny_mce_before_init </code> . For example, the following code will prevent TinyMCE from stripping IFRAME, PRE, and DIV tags: <code> function mytheme_tinymce_config( $init ) { // Change code cleanup/content filtering config // Don't remove line breaks $init['remove_linebreaks'] = false; // Convert newline characters to BR tags $init['convert_newlines_to_brs'] = true; // Preserve tab/space whitespace $init['preformatted'] = true; // Add to list of formats to remove with Remove Format button $init['removeformat_selector'] = 'b,strong,em,i,span,ins,del,h1,h2,h3,h4,h5,h6,pre'; // Do not remove redundant BR tags $init['remove_redundant_brs'] = false; // Add to list of valid HTML elements (so they don't get stripped) // IFRAME $valid_iframe = 'iframe[id|class|title|style|align|frameborder|height|longdesc|marginheight|marginwidth|name|scrolling|src|width]'; // PRE $valid_pre = 'pre[id|name|class|style]'; // DIV $valid_div = 'div[align<center?justify?left?right|class|dir<ltr?rtl|id|lang|onclick|ondblclick|onkeydown|onkeypress|onkeyup|onmousedown|onmousemove|onmouseout|onmouseover|onmouseup|style|title]'; // Concatenate $cbnet_valid_elements = $valid_iframe . ',' . $valid_pre . ',' . $valid_div; // Add to extended_valid_elements if it alreay exists if ( isset( $init['extended_valid_elements'] ) ) { $init['extended_valid_elements'] .= ',' . $cbnet_valid_elements; } else { $init['extended_valid_elements'] = $cbnet_valid_elements; } // Pass $init back to WordPress return $init; } add_filter('tiny_mce_before_init', 'mytheme_tinymce_config'); </code> See here for the full list of configurable options .
|
WordPress keeps altering my embed code
|
wordpress
|
How can I add a CSS Class to the <code> previous_post_link </code> output or just get the URL and create the HTML markup myself
|
You can use the more native function that is "below" the <code> previous_/next_post_link(); </code> : <code> # get_adjacent_post( $in_same_cat = false, $excluded_categories = '', $previous = true ) $next_post_obj = get_adjacent_post( '', '', false ); $next_post_ID = isset( $next_post_obj->ID ) ? $next_post_obj->ID : ''; $next_post_link = get_permalink( $next_post_ID ); $next_post_title = '&raquo;'; // equals "»" ?> <a href="<?php echo $next_post_link; ?>" rel="next" class="pagination pagination-link pagination-next"> <?php echo $next_post_title; ?> </a> </code>
|
How to add CSS Class to previous_post_link or get previous/next post link URL
|
wordpress
|
Is there a way to show a list of all categories available even if there are no posts associated with them. So if there is a post in that category then it echos a link and if not it just echos out the name of the category? I'm using wp_list_categories() to show them...
|
There's an argument called <code> hide_empty </code> which is true by default. <code> $args = array('hide_empty' => FALSE); wp_list_categories($args); </code> Codex: http://codex.wordpress.org/Template_Tags/wp_list_categories
|
Show list of categories even if they have no posts
|
wordpress
|
I created 1 custom post type with 2 custom taxonomy. Installed http://wordpress.org/extend/plugins/json-api/ and tried to reach result with: http://example.com/api/get_recent_posts?dev=1&post_type=myposttype well it gives me custom posts but not giving those post's custom taxonomies "categories": [], "tags": [], How can i query custom taxonomies with json api? Actually i am trying to create a simple iphone app with jquery mobile + phonegap. Maybe you know a better way then json api?
|
I would have done it as following, I am sure experts here will have a better way but following is what I could come up with in hurry. First create your controller file in your theme directory (or any other if you like) with the following content. For this example the file name is korkmaz.php UPDATE 1: Please replace the previous korkmaz.php because extending introspector was dangerous many unwanted functions were exposed via URI. Now we have a new JSON_API_Korkmaz_Controller class which does not extend any other class and We have removed the JSON_API_CustomPost class . UPDATE 2: Now supports querying custom taxonomies, see the example at the bottom. Includes new model class JSON_API_Term to represent term of any type of taxonomy. <code> // most of the functions here are rewrite of json-api functions class JSON_API_Korkmaz_Controller { public function get_recent_posts() { global $json_api; $posts = $json_api->introspector->get_posts(); foreach ($posts as $jpost) { $this->add_taxonomies( $jpost ); } return $this->posts_result($posts); } protected function posts_result($posts) { global $wp_query; return array( 'count' => count($posts), 'count_total' => (int) $wp_query->found_posts, 'pages' => $wp_query->max_num_pages, 'posts' => $posts ); } protected function add_taxonomies( $post ) { $taxonomies = get_object_taxonomies( $post->type ); foreach ($taxonomies as $tax) { $post->$tax = array(); $terms = wp_get_object_terms( $post->id, $tax ); foreach ( $terms as $term ) { $post->{$tax}[] = $term->name; } } return true; } public function get_taxonomy_posts() { global $json_api; $taxonomy = $this->get_current_taxonomy(); if (!$taxonomy) { $json_api->error("Not found."); } $term = $this->get_current_term( $taxonomy ); $posts = $json_api->introspector->get_posts(array( 'taxonomy' => $taxonomy, 'term' => $term->slug )); foreach ($posts as $jpost) { $this->add_taxonomies( $jpost ); } return $this->posts_object_result($posts, $taxonomy, $term); } protected function get_current_taxonomy() { global $json_api; $taxonomy = $json_api->query->get('taxonomy'); if ( $taxonomy ) { return $taxonomy; } else { $json_api->error("Include 'taxonomy' var in your request."); } return null; } protected function get_current_term( $taxonomy=null ) { global $json_api; extract($json_api->query->get(array('id', 'slug', 'term_id', 'term_slug'))); if ($id || $term_id) { if (!$id) { $id = $term_id; } return $this->get_term_by_id($id, $taxonomy); } else if ($slug || $term_slug) { if (!$slug) { $slug = $term_slug; } return $this->get_term_by_slug($slug, $taxonomy); } else { $json_api->error("Include 'id' or 'slug' var for specifying term in your request."); } return null; } protected function get_term_by_id($term_id, $taxonomy) { $term = get_term_by('id', $term_id, $taxonomy); if ( !$term ) return null; return new JSON_API_Term( $term ); } protected function get_term_by_slug($term_slug, $taxonomy) { $term = get_term_by('slug', $term_slug, $taxonomy); if ( !$term ) return null; return new JSON_API_Term( $term ); } protected function posts_object_result($posts, $taxonomy, $term) { global $wp_query; return array( 'count' => count($posts), 'pages' => (int) $wp_query->max_num_pages, 'taxonomy' => $taxonomy, 'term' => $term, 'posts' => $posts ); } } // Generic rewrite of JSON_API_Tag class to represent any term of any type of taxonomy in WP class JSON_API_Term { var $id; // Integer var $slug; // String var $title; // String var $description; // String function JSON_API_Term($term = null) { if ($term) { $this->import_wp_object($term); } } function import_wp_object($term) { $this->id = (int) $term->term_id; $this->slug = $term->slug; $this->title = $term->name; $this->description = $term->description; $this->post_count = (int) $term->count; } } </code> Now add following to your theme's functions.php <code> // Add a custom controller add_filter('json_api_controllers', 'add_my_controller'); function add_my_controller($controllers) { $controllers[] = 'Korkmaz'; return $controllers; } // Register the source file for our controller add_filter('json_api_korkmaz_controller_path', 'korkmaz_controller_path'); function korkmaz_controller_path($default_path) { return get_stylesheet_directory() . '/korkmaz.php'; } </code> Now goto Json API settings page and enable your korkmaz controller. Now you can access your custom post types with all of the associated taxonomies at the following url: http://example.com/api/korkmaz/get_recent_posts/?post_type=myposttype You can query any type of taxonomy (including custom taxonomies) using the following example: http://example.com/api/korkmaz/get_taxonomy_posts/?taxonomy=my_custom_taxonomy&slug=my_term_slug
|
wordpress json custom taxonomy problem
|
wordpress
|
i am using the Smart Youtube plugin for wordpress to show youtube videos. This works fine on my main site. But when i click on a view by a certain tags, none of the video show up in the blog entries. so when i view: http://mysite.com it works fine and when i view an individual post like: http://mysite.com/?p=3580 , it works fine but when i view http://mysite.com/?tag=video it only shows the blog entry heading (and not the video). if i click into the post it shows it fine on the individual page. Is there anyway to see videos on a page by tags?
|
edit tag.php (or archive.php if tag.php does not exist) and look for <code> the_excerpt(); </code> - exchange it with <code> the_content(); </code> codex the_excerpt() codex the_content()
|
videos not showing on my tag pages
|
wordpress
|
This is going to be tough to explain. I have created a custom theme and have a file called: categories.php, in this file i have: <code> <?php $args = array('hide_empty' => FALSE); wp_list_categories($args); ?> </code> This displays all my categories as links, even the ones without a post associated with them. My permalink structure is this /%category%/%postname%/ so when i click a category name i go to http://example.com/category/action/ . This is fine but what i'm struggling with is what file i have to create and what i have to put in said file so it displays all the posts from the clicked category? Thanks
|
if category.php does not exist, make a copy of archive.php or index.php and save it as category.php; then, before the start of the loop, add: <code> <?php global $query_string; query_posts( $query_string . '&posts_per_page=-1'); ?> </code>
|
Display all posts from selected category
|
wordpress
|
I am moving my site from olddomain.com to newdomain.com. I want to keep all of the content at olddomain.com but I want the canonical version in google to be recognized as newdomain.com/whatever-post/ instead of the same thing at olddomain.com. How can I modify the rel=canonical in the section of olddomain.com to make this change?
|
Unfortunately, there's no filter in the <code> rel_canonical() </code> function. But you can remove that function from wp_head altogether and write your own. Try adding this to the functions.php at your old domain: <code> remove_action( 'wp_head', 'rel_canonical' ); add_action( 'wp_head', 'new_rel_canonical' ); function new_rel_canonical() { if ( !is_singular() ) return; global $wp_the_query; if ( !$id = $wp_the_query->get_queried_object_id() ) return; $link = get_permalink( $id ); $link = str_replace( 'olddomain.com', 'newdomain.com', $link ); echo "<link rel='canonical' href='$link' />\n"; } </code> Obviously, just replace olddomain.com and newdomain.com in the second to last line with your actual domain names!
|
Custom Canonical URLs
|
wordpress
|
I'm in need of the ability to allow anyone (they don't have to login) to fill out a form with email and a textarea and submit it to my site. This form would be treated as a post and appear somewhere for me to moderate. If i hit publish, it would be published to my site like any other post i wrote. Is there a plugin that allows me to do this or do i need to code it myself, if the latter, how would i go about doing that? Thanks in advance!
|
This might work for you? http://perishablepress.com/user-submitted-posts/
|
Allow anonymous users to post to my site for moderation
|
wordpress
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.