question
stringlengths 0
34.8k
| answer
stringlengths 0
28.3k
| title
stringlengths 7
150
| forum_tag
stringclasses 12
values |
---|---|---|---|
I'm building a theme that is going to show excerpts on the homepage for potentially dozens of posts. I don't have manual excerpts on all of my posts, so <code> $post->post_excerpt </code> is empty for many posts. In the event that there isn't a manual excerpt, I would like to use the built-in get_the_excerpt() function, but it isn't available outside the loop. Tracking down the function, it looks like it uses wp_trim_excerpt from wp-includes/formatting.php to create excerpts on the fly. I am calling it in my code like <code> wp_trim_excerpt( $item->post_content ) </code> , but it is simply returning the full content. Am I doing something wrong? I know that I can create my own function to create an excerpt, but I like to use built-in functions where possible, keeping my code compatible with other potential plugins / filters. http://adambrown.info/p/wp_hooks/hook/wp_trim_excerpt?version=3.0&file=wp-includes/formatting.php
|
<code> wp_trim_excerpt() </code> has a little curious mechanics - if anything is passed to it then it does nothing. Here is basic logic behind it: <code> get_the_excerpt() </code> checks for manual excerpt; <code> wp_trim_excerpt() </code> chimes in if there is no manual excerpt and makes one from content or teaser. Both are tightly tied to global variables and so Loop. Outside the Loop you are better of taking code out of <code> wp_trim_excerpt() </code> and writing your own trim function.
|
Using wp_trim_excerpt to get the_excerpt() outside the loop
|
wordpress
|
I'm creating a theme that would need some settings on the client side. So I need a admin interface where they can set some values. (like, source of image, title, or numbers) so in my theme, I can just set some variables like <code> <img src="IMAGE_SOURCE" title="TITLE" size="NUMBER" /> </code> If you can point me to a tutorial that would be great. Thanks!
|
The newest and most complete tutorial to the settings API can be found here . I'd suggest to take a look there. I used a pretty similar way myself. Sidenote: You should really mark some answer a solution. "0% acceptance rate" will people hold back from answering your Qs anymore.
|
how do you create an admin interface in plugin for your theme
|
wordpress
|
I'm not sure if this is the right place to ask this but last night i made a post on my wordpress powered blog here: http://blog.twostepmedia.co.uk/css3-still-novelty-or-usable-in-everyday-web-development/ then this morning i see this: http://buzzgamesnews.blogspot.com/2011/01/css3-still-novelty-or-usable-in.html Is this right? Can someone completely clone a post of mine or am i overreacting?
|
Yes, they can. There is nothing strange or technically complex about that. And before you ask - no, it's pretty much unrealistic to protect public web page from being copied. My process to deal with such goes roughly like this: Contact blog owner and point out that your posts are not meant to be copied and that is not allowed under license/terms ( © in Two Step Media © 2010 ) of your blog. If not successful report to his hosting. Additional mean and pleasant step is to report to advertisement companies that are used on site. Most of the time scraping is done for profit so hitting profit is exactly what hurts and makes a point. Give up or get legal stuff involved. Since blog in question is hosted by Google and not self-hosted it's very likely 2 (if not 1 ) will get it done.
|
Wordpress blog post cloned and stolen?
|
wordpress
|
I'm writing a plugin called 'Featured Releases' for a client. The user fills out a short form in the admin area which inserts some text and an image id into the wordpress database via $wpdb-> insert. On my development machine it works fine, but on the production server (which has over 500 posts of all sorts, mostly images), the value of the image id is being changed to 127 no matter what I do. 127 is the id of a post, but its not an image and certainly not the id that was passed from the form. The image is uploaded via the native wordpress media uploader. The image's post id (from the wp_posts table) is passed to a hidden input in the form. On submit, this function handles the $_POST data: <code> function fr_add_album() { global $wpdb; if ( isset($_POST) && (count($_POST) > 0) ) { check_admin_referer('featured-releases-add_album'); $table_name = $wpdb->prefix . 'featured_releases'; $desired_keys = array('fr_band', 'fr_album', 'fr_album_description', 'fr_image_id', 'fr_shop_url'); $data = array(); foreach( $desired_keys as $key ) { // Define and sanatize data if ( isset($_POST["$key"]) ) { $accepted_html = array('a' => array('href' => array(), 'title' => array())); $data["$key"] = wp_kses($_POST["$key"], $accepted_html); unset($_POST["$key"]); } else { $data["$key"] = ''; } } // Sanitize the shop url if ( isset($data['fr_shop_url']) ) { $data['fr_shop_url'] = esc_url($data['fr_shop_url']); } $data['fr_modified'] = date('Y-m-d h:i:sa'); error_log($data['fr_image_id']); // This returns the correct value! $wpdb->insert($table_name, $data, array('%s','%s', '%s', '%d', '%s')); // After the insert, the fr_image_id column always reads "127" } } </code> The insane thing is that there are a few images which do post correctly . These were the first images I uploaded when I created the wordpress install. Every other image from any other date, including any new image I upload is saved as 127 in the database. All the images have the same owners and same permissions. I also can't see any difference in wp_posts between the new images and the old. Any ideas? I'm dyin' here. Thanks for your help!
|
Great advice Rarst! The output of $wpdb-> queries was exactly what it should be: <code> "INSERT INTO `wp_featured_releases` (`fr_band`,`fr_album`,`fr_album_description`,`fr_image_id`,`fr_shop_url`,`fr_modified`) VALUES ('','','','504','','2011-01-14 10:49:58pm')" </code> 504 is the correct id for the image, but the value in the table is still 127. My latest thought is that my mysql skills have failed me. Images with an ID below 127 work fine, but anything above 127 is changed to 127. The column type that holds fr_image_id is tinyint(9), which should be able to hold any value up to 9999999999 right? If not, I think I just found my answer. I'll try changing it and see.
|
$wpdb-> insert is changing a value
|
wordpress
|
How do I limit the query by two custom meta fields, a start date and an end date? This is what my data looks like: meta_key | meta_value | ------------------------| start_date | 20100131 | //Jan 15, 2010 end_date | 20100206 | //Feb 6, 2010 ------------------------' $today = date(YYYYMMDD); The post will show if <code> start_date = $today </code> and it will expires when <code> end_date = $today </code> . update Here is the structure on my single.php First Query I use here your answer <code> <?php query_posts( $query_string ); if (have_posts()) : while (have_posts()) : the_post(); ?><a href="<?php the_permalink() ?>"><?php the_title() ?></a><br /><?php endwhile; endif; wp_reset_query(); ?> </code> and Second Query with regular wordpress function but this second query doesnt work properly <code> <?php query_posts('showposts=5&meta_key=start_date&meta_compare=>&meta_value='.date("Ymd")); if (have_posts()) : while (have_posts()) : the_post(); ?><a href="<?php the_permalink() ?>"><?php the_title() ?></a><br /><?php endwhile; endif; wp_reset_query(); ?> </code>
|
Edited again to demonstrate adding and removing filters: Include these general functions in your functions.php . These are the filters you will invoke for the loops where you want to limit your query by these two meta values: <code> function date_check_join( $join ) { global $wpdb; $join .= " JOIN ".$wpdb->postmeta." AS startdate ON (".$wpdb->posts.".ID = startdate.post_id AND startdate.meta_key = 'start_date') JOIN ".$wpdb->postmeta." AS enddate ON (".$wpdb->posts.".ID = enddate.post_id AND enddate.meta_key = 'end_date')"; return $join; } function date_check_where( $where ) { $today = date('Ymd'); $where .= " AND startdate.meta_value <= $today AND enddate.meta_value >= $today"; return $where; } </code> Now, on the page(s) where you want to include these filters, add them before the loops you want to filter and remove them afterward. For example: <code> add_filter( 'posts_join', 'date_check_join' ); add_filter( 'posts_where', 'date_check_where' ); query_posts( "yourqueryhere" ); if (have_posts()) : while (have_posts()) : the_post(); // This loop will only includes where today is between start_date and end_date endwhile; endif; query_posts( "anotherqueryhere" ); if (have_posts()) : while (have_posts()) : the_post(); // This loop also only includes where today is between start_date and end_date endwhile; endif; remove_filter( 'posts_join', 'date_check_join' ); remove_filter( 'posts_where', 'date_check_where' ); query_posts( "thirdqueryhere" ); if (have_posts()) : while (have_posts()) : the_post(); // This loop is not affected by the filters, so you can query for posts // where start_date is in the future, or end_date in the past, etc. endwhile; endif; </code> You just need to add your conditions to the 'posts_join' and 'posts_where' filters before your search, and remove them afterwards (otherwise these conditions will be applied to everything on your site, including pages, menus, etc.) If you can simplify this by only comparing against one field, then you can use the <code> meta_compare </code> attribute built into the WP_Query object. You could schedule your posts for the start_date (so they don't show ahead of schedule), and then compare the date against the end_date custom field when you query.
|
Query between two meta values?
|
wordpress
|
Okay I posted a question yesterday, that can be found stackexchange-url ("here"). I've found some code on the wonderful internet that I think is really the ticket for me, but I don't know how to develop into what I really need. Here is the breakdown - I need three separate vote links. I need to change the word "Vote" on each to something else. IE: Good/Meh/Bad. (I think I can figure this one out) I'm hoping there is a simple and easy way to slap another two vote links into this code, because the code itself is really simple and easy. Just beg pardon my lack of PHP/Jquery knowledge. Header code: <code> <?php wp_enqueue_script( 'jquery' ) ?> <?php wp_head(); ?> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery(".vote a").click( function() { var some = jQuery(this); var thepost = jQuery(this).attr("post"); var theuser = jQuery(this).attr("user"); jQuery.post("<?php bloginfo('template_url'); ?>/vote.php", {user: theuser, post: thepost}, function(data) { var votebox = ".vote"+thepost+" span"; jQuery(votebox).text(data); jQuery(some).replaceWith('<span class="voted">Voted</span>'); }); }); }); </script> </code> vote.php file: <code> <?php $file = dirname(__FILE__); $file = substr($file, 0, stripos($file, "wp-content") ); require( $file . "/wp-load.php"); $currentvotes = get_post_meta($_POST['post'], 'votes', true); $currentvotes = $currentvotes + 1; $voters = get_post_meta($_POST['post'], 'thevoters', true); if(!$voters) $voters = $_POST['user']; else $voters = $voters.",".$_POST['user']; update_post_meta($_POST['post'], 'votes', $currentvotes); update_post_meta($_POST['post'], 'thevoters', $voters); echo $currentvotes; ?> </code> Functions.php reference: <code> function voting($id) { global $user_ID; $currentvotes = get_post_meta($id, 'votes', true); $voters = get_post_meta($id, 'thevoters', true); $voters = explode(",", $voters); foreach($voters as $voter) { if($voter == $user_ID) $alreadyVoted = true; } if(!$currentvotes) $currentvotes = 0; echo '<div class="vote vote'.$id.'"><span>'.$currentvotes.'</span>'; if($user_ID && !$alreadyVoted) echo '<br /><a post="'.$id.'" user="'.$user_ID.'">'.__("Vote").'</a>'; if($user_ID && $alreadyVoted) echo '<br /><span class="voted">'.__("Voted").'</span>'; echo '</div>'; if(!$user_ID) echo '<div class="signup"><p><a href="'.get_bloginfo('url').'/wp-login.php?action=register">'.__('Register').'</a> '.__('to vote').'.</p></div>'; } </code> Source has a demo. Any and all help with this would be really, really appreciated. Thanks in advance.
|
Here's a simple solution. Append the ratings to the end of the post content: <code> add_filter('the_content', 'add_ratings_to_content', 4); // remove ratings from excerpts add_filter('get_the_excerpt', create_function('', 'remove_filter("the_content", "add_ratings_to_content", 6); return;'), 5); function add_ratings_to_content($content){ global $post; if(is_single()) $content .= the_ratings($post->ID); return $content; } </code> Displays the current rating: <code> function get_current_rating($post_id){ $votes = get_option("votes_{$post_id}"); // handle your rating format here $output = ''; if(isset($_COOKIE["rated_{$post_id}"])) $output .= "Your rating: ".esc_attr($_COOKIE["rated_{$post_id}"]); if(is_array($votes)): $output .= isset($votes['bad']) ? "{$votes['bad']} people think this sucks." : null; $output .= isset($votes['meh']) ? "{$votes['meh']} people said meh." : null; $output .= isset($votes['good']) ? "{$votes['good']} people think this post was good." : null; else: $output = "no votes yet"; endif; return $output; } </code> The ajax request. Use <code> $_SERVER['REMOTE_ADDR'] </code> to do a IP check for multiple votes because cookies can be deleted easily (and store the IP+post id somewhere, like a transient ) <code> add_action('init', 'process_vote'); function process_vote() { if($_GET['vote']): $rating = esc_attr($_GET['vote']); $post_id = esc_attr($_GET['post_id']); $already_voted = isset($_COOKIE["rated_{$post_id}"]) ? true : false; $current_rating = get_current_rating($post_id); if ($post_id && in_array($rating, array('bad', 'meh', 'good')) && !$already_voted): // update db $votes = get_option("votes_{$post_id}"); $votes[$rating] = isset($votes[$rating]) ? ($votes[$rating]+1) : 1; update_option("votes_{$post_id}", $votes); setcookie("rated_{$post_id}", $rating, time() + (86400 * 30)); // 30 day cookie echo get_current_rating($post_id); else: echo "Already voted?"; endif; die(); endif; } </code> the HTML for the ratings, simple stuff, no css: <code> function the_ratings($post_id = false, $disabled = false){ $already_voted = isset($_COOKIE["rated_{$post_id}"]) ? true : false; ob_start(); ?> <?php if(!$already_voted && !$disabled): ?> <p>How would you rate this?</p> <ul class="vote-process"> <li><a rel="<?php echo $post_id; ?>">bad</a></li> <li><a rel="<?php echo $post_id; ?>">meh</a></li> <li><a rel="<?php echo $post_id; ?>">good</a></li> </ul> <?php endif; ?> <div class="vote-status"> <?php echo get_current_rating($post_id); ?> </div> <?php return ob_get_clean(); } </code> The JavaScript, included in the page footer. <code> add_action("wp_footer", "ratings_js"); function ratings_js(){ ?> <script type="text/javascript"> /* <![CDATA[ */ jQuery(document).ready(function($){ $(".vote-process a").click(function () { var id = $(this).attr('rel'); var post = $("#post-"+id); var link = $(this).html(); $.ajax({ type: "GET", url: "<?php echo home_url('/'); ?>", data: { post_id: id, vote: link }, beforeSend: function() { post.find(".vote-status").html("Please wait..."); }, success: function(response){ post.find(".vote-status").html(response); post.find(".vote-process").remove(); } }); }); }); /* ]]> */ </script> <?php } </code> Remove the votes_postid option when a post is deleted: <code> add_action('delete_post', 'remove_votes'); function remove_votes($post_id){ delete_option("votes_{$post_id}"); return $post_id; } </code> I'd still recommend using CDNvote, because the code is very simple and flexible, and uses it's own database table...
|
WP 3-way voting system: On to something! Please help!
|
wordpress
|
I've been looking into using the Wordpress Repository for one of my larger plugins, the problem is that it's using a lot of third party software. Video players/Slide scripts/Jquery includes, some of which are commercial in nature. My question is related to the content that differs from the GPL v2. Id like to include those into the plugin, since that would make it easier to use. If I get permission from the third party, is this possible? As an example flowplayer (GPL 3) and Longtail Video Player (Commercial). Also will this supporting software be exempt from the GPL 2 license restriction?
|
License Compatibility As a recent commenter pointed out on my site , it should be possible to distribute a plug-in that's not GPL so long as you don't distribute it with WordPress. However, the guys at WP.org have pointed out time and again that only GPL-compatible plug-ins must be compatible with version 2 of the GPL . So this puts you between a rock and a hard place. Strictly speaking, you can't distribute commercially licensed software under the terms of the GPL ... so Longtail would be out in this case. However, you might be able to get permission from Flowplayer to incorporate it in a GPLv2 plug-in. Just make sure you ask and point this out clearly in the documentation. Support But remember, including 3rd party libraries doesn't require you to support them if the end user is using them outside your plug-in. And "support" is ambiguous anyway. The only support-related requirement is that, if you distribute compiled software, you provide a written offer (valid for 2 years) to provide the source code to anyone you gave the compiled binaries to. Since your plug-in is written in PHP, it's interpreted not compiled ... so you already provide the source code. (Meaning you're not obligated to do anything further). Alternative A potential alternative would be to make your plug-in "pluggable." Meaning it can use whatever video library or player the end user has available. Then you can load and use something like Longtail if it's available without having to distribute it. This just adds an extra requirement for the user to find, download, and install a separate player of their choice (I'd recommend listing several possibilities in your documentation). Then you'd add a configuration section to your plug-in (somewhere in the admin screen) where the user enters the path of their video plug-in and tells you which one it is (so you can use the right API). This lifts the burden of licensing off your shoulders. In Summary Just remember these key points: Your plug-in must be compatible with version 2 of the GPL, even if it's using some other license Your only support requirement is to provide the source of your solution, which you do by default when you release it to the WP.org repository If you incorporate a (non-free) third-party solution, you're limiting the rights of your users to edit, re-publish, and re-distribute your system ... though this isn't in the spirit of the GPL, there are some ways to do it
|
Possibility of including third party software/plugins in the Wordpress repository
|
wordpress
|
(Please note I'm NOT asking about wordpress.org but about wordpress.com ) I just posted a new entry but my current theme has a fixed width which makes my post become buggy and surely myself and the readers won't like it very much! So, I'm looking for another theme that has the content width maximized. If you know ones, please share! Thank you!
|
.com had recently got much improved catalog of themes with search, filtering and other nifties. See all themes with flexible width template . If nothing fits there is paid option to allow CSS customization.
|
Need a theme that let the posted content stretched maximum width
|
wordpress
|
I download and configure Wordpress for a development environment and a production environment. After it's set up on one server we check it into a subversion repo and then go and check it out on the production server. Deployment complete. The trouble is when I have to update. I'm supposed to delete wp-includes and wp-admin but if I do that svn goes crazy. What are some strategies for dealing with Wordpress, subversion, and multiple deployment environments?
|
Externals, definitely. Set up your own SVN repo, then make WP as an external in the repo. I put it into a /wp directory. You can access the WP SVN as an external here: http://core.svn.wordpress.org/ I tend to use trunk. You can use a branch, if you really, really want. Branches get auto updated with minor releases (/branches/3.0 held 3.0, then 3.0.1, 3.0.2, etc), new branches get made for major releases. Alongside it, I make a /name-content directory, where I'll put my custom themes and such. "name" is whatever you want it to be. Then I can use a custom /wp-config.php to change the location of the wp-content directory into my custom one, like so: <code> define( 'WP_CONTENT_DIR', $_SERVER['DOCUMENT_ROOT'] . '/name-content' ); define( 'WP_CONTENT_URL', 'http://example.com/name-content'); </code> For the themes, they go directly into the repo (since they're probably custom to the site) under /name-content/themes. Any plugins I use I make a /name-content/plugins directory for, then set them to be externals from the http://plugins.svn.wordpress.org/pluginname/trunk repo. If you don't like running trunk (dangerous and that), then you can use the /tags/1.1 or whatever for them instead. With a little bit of custom .htaccess logic (with the .htaccess file in the root of the repo) to make /wp the "root" of my domain, then the whole thing is setup. Example .htaccess file to move the root: <code> Options -Indexes RewriteEngine on RewriteCond %{HTTP_HOST} ^(www.)?example.com$ RewriteCond %{REQUEST_URI} !^/wp/ RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule ^(.*)$ /wp/$1 RewriteCond %{HTTP_HOST} ^(www.)?example.com$ RewriteRule ^(/)?$ wp/index.php [L] </code> This allows WordPress in the /wp directory to be at the root of your site, with it pointing to the name-content directory for the content aspects. The .htaccess won't redirect those requests (since the files exist) and thus everything works perfectly. Advantage: When you want to update, a simple svn up updates the whole site, after you fiddle with the externals and such to point to the newer versions (if you're too chicken to run on trunk).
|
Managing updates when Wordpress is in your own svn repo
|
wordpress
|
I'm using a function to display all files attached to a post and listing them as links. The result is something like this: <code> echo '<a href="' . wp_get_attachment_url($attachmentImage->ID) . '" class="dir-attachment" />' . wp_get_attachment_url($attachmentImage->ID) . '</a>'; </code> As expected, this display a hyperlinked version of the hyperlink, but I'd like to clean it up. Is there some way to strip the http://mydomain/wp-content/uploads from the second instance display the file name only, rather than the full path?
|
Try this: <code> basename(get_post_meta( $attachmentImage->ID, '_wp_attached_file', true)); </code>
|
Strip the folder path away from wp_get_attachment_url to show filename only
|
wordpress
|
How can I make a similar posts section in my theme, but without using a plugin. I'm going to be giving my theme away for free, so I don't want to have to force people to install plugins to use my theme. How can it be done?
|
Put this in your single.php: <code> $tags = wp_get_post_tags($post-> ID); if ($tags) { $first_tag = $tags[0]-> term_id; $args=array( 'tag__in' => array($first_tag), 'post__not_in' => array($post-> ID), 'showposts'=> 4, 'caller_get_posts'=> 1 ); $my_query = new WP_Query($args); if( $my_query-> have_posts() ) { while ($my_query-> have_posts()) : $my_query-> the_post(); // post content stuff here endwhile; wp_reset_query(); } } </code>
|
Similar Posts - NO plugin
|
wordpress
|
I found a way to export my posts in text form so that I can move them to a blog with static pages. The only problem is that there are no paragraph tags, so every post is a huge block of text. I had been using line breaks and relying on wpauto to add paragraph tags automatically. Is there any way to add those tags into my posts without doing it by hand?
|
a quick and dirty way to do this is by running this ONCE: <code> global $post; $posts = new WP_Query(); $posts->query(array('posts_per_page' => -1, 'post_type' => 'post')); while ($posts->have_posts()): $posts->the_post(); $post->post_content = wpautop($post->post_content); // replaces new line chars with <p>'s wp_update_post($post); // updates the database endwhile; </code> (didn't test it) But how are you exporting your posts in text form? Maybe you could apply the autop filter in your export routine
|
How do I add paragraph tags to all of my posts after relying on wpauto?
|
wordpress
|
I had asked a question earlier, on stackexchange-url ("getting post-thumbnails from another WP-site"). There, the awesome stackexchange-url ("Mike") coded a SQL query whose results are then passes on to a PHP array. The piece of code from that answer that I want to modify is this. <code> $post_urls = $wpdb->get_col($sql); if (is_array($post_urls)) echo implode("\n",$post_urls); </code> Now the array holds values in the form of <code> <img src="/link/to/image.jpg"/> </code> . Now how do I.. Call the WP <code> image_resize </code> function on each image URL? Apply my own CSS class to each image? UPDATE: Thanks to stackexchange-url ("Jan") for the tips on optimizing the SQL query. Now the <code> $post_urls </code> array will hold only plain URLs to the images. Can someone show me how to loop through each URL in the array and add prefixes (like <code> <img src=" </code> ) and suffixes (like <code> " class="awesome-image"/> </code> ) to each of them?
|
Calling <code> image_resize() </code> would be difficult, since it would search for the image in your main blog's upload directory. If it is a fixed image size I would just add it to the configuration of your photoblog, so it is created there when you upload new images (you can then stackexchange-url ("rebuild your old image thumbnails")). In Mike's answer you see that he adds the <code> <img src=" </code> and <code> "/> </code> parts in the SQL query. That's nice, but you don't have to do that. If you leave that off you get just the URL of the image and you can add everything later in PHP. I wrote stackexchange-url ("an alternative version that will provide you with more raw information") to play with. <code> $attachment_data_list = $wpdb->get_results( $sql ); if ( $attachment_data_list ) { foreach ( $attachment_data_list as $attachment_data ) { echo '<img src="/mysubblog/wp-content/uploads/'; echo $attachment_data->upload_relative_path; echo '"/>'; } } </code>
|
Styling images coming from another blog
|
wordpress
|
I've basically done a full plugin and now just "prettifying" it sort-of. One thing I'm doing is re-doing the columns for listing the "posts" I made. This part is fine, and all columns are replaced as needed, however, there's one column that puzzles me.. the title field. :/ <code> add_action( 'manage_posts_custom_column', array( &$this, '_wp_filter_visitor_column_view' ) ); add_filter( 'manage_edit-visitor_columns', array( &$this, '_wp_filter_visitor_columns' ) ); public function _wp_filter_visitor_column_view( $column ) { global $post; if ( $column == "title" ) { $name = get_post_meta( $post->ID, 'v_f_name', true ); $name .= ' ' . get_post_meta( $post->ID, 'v_l_name', true ); echo $name; } elseif ( $column == "type" ) { echo "Not available right now..."; } elseif ( $column == "loggedin" OR $column == "workstation" ) { $workstation = get_post_meta( $post->ID, 'v_workstation', true ); if ( $column == "workstation" ) echo $workstation; elseif ( $column == "loggedin" ) echo ( !empty($workstation) OR !isset( $workstation ) ) ? 'No' : 'Yes'; } elseif ( $column == "id" ) { echo get_post_meta( $post->ID, 'v_id', true ); } } public function _wp_filter_visitor_columns( $columns ) { $columns = array( 'cb' => '<input type="checkbox" />', 'title' => 'Name', 'type' => 'Type', 'loggedin' => 'Logged In?', 'id' => 'Visitor ID', ); return $columns; } </code> The column header for "title" => "Name" appears properly, but the column data displays the default title of "Auto Draft" because I'm not using the post's title field. Do I need to the post's title field for custom post types or will auto-generated titles suffice? I have no need for the title field and would rather use the postmeta table for storing my data. -Zack P.S. I was following this tutorial for creating the columns.
|
I did a slight hack for this to work. I added a hidden field named "post_title" as if I'm enabling Title support, though without actually having the ugly title bar positioned. <code> <div id="titlewrap"> <input type="hidden" name="post_title" size="30" tabindex="1" value="" id="title" autocomplete="off" /> </div> <script type="text/javascript"> ( function ($) { $( '#v_l_name' ).blur( function () { $( '#title' ).attr( 'value', $( '#v_f_name' ).val() + ' ' + $( '#v_l_name' ).val() ); }); })(jQuery); </script> </code> All-in-all, It works. The title field is populated properly. Thanks Mike though! ;)
|
Custom Post Type, Custom Columns List
|
wordpress
|
I've done this with posts, but I can't find the proper way to reference the category table's columns. I'm trying to add a column titled "Image" to the table, so that when the table grid of categories is displayed, if there is a category image assigned to the category, it will appear in the grid. The first step for me is to determine the proper filter to address in order to insert the columb into the table. I've tried each of these to no avail... <code> add_filter('manage_categories_columns', 'myFunction', 10, 2); add_filter('manage_category_columns', 'myFunction', 10, 2); function myFunction($cat_columns) { $cat_columns['cat_image_thumb'] = 'Image'; return $cat_columns; } </code>
|
The filter is <code> manage_{$screen->id}_columns </code> , and <code> $screen->id </code> is <code> edit-category </code> , giving you <code> manage_edit-category_columns </code> . I found this by placing a <code> var_dump() </code> in <code> get_column_headers() </code> , which is called by <code> print_column_headers() </code> , which is called in <code> wp-admin/edit-tags.php </code> , the page where you edit the category items.
|
How can I add a custom column to the "Manage Categories" table?
|
wordpress
|
I'm questioning how i can get rid of the post-editor (visual + html). I tried to not register post type support, and it still appears (de-registering works fine with every other default meta box on post edit screen). I also tried to deregister it with remove_meta_box, which didn't work too (works for everything else except the title meta box). Maybe i'm missing something. Already searched the web and couldn't find anything. I hope someone can tell me. Thanks! Ps. I would be happy about a sollution for disabling the title field too, but that's 2nd (not registering it with the post type works). (Wordpress version is 3.0.4.)
|
Giving a blank array to 'supports' in the declaration of the post type should get rid of the editor and the title, along with every other default box in the edit post page. <code> $supports = array (''); $args = array( 'label' => 'people', 'supports' => $supports, 'hierarchical' => false, 'public' => true, 'rewrite' => true ); register_post_type( 'people', $args); </code> Result: Populate 'supports' with whichever elements you want to show up, such as trackbacks, comments, etc. Or just leave it blank to leave the page empty, except for the box that lets you save your posts. Make sure to visit stackexchange-url ("here") if you want to get rid of hierarchical taxonomy metaboxes as well.
|
Custom Post Types: How-to get rid of editor (-meta box)
|
wordpress
|
I've currently been creating my Git repositories at the root level for each of my WordPress installations. Git of course then notices any core updates, plugins, and uploads. I'm considering just tracking the theme I'm working on or perhaps the entire themes directory. I'd like to hear from other WordPress developers as to what are their preferred version control practices.
|
If I'm working on whole project for a client (WP install + custom theme + plugins), I put everything in one repository. My thinking is that I created one "solution" based on WP + some existing plugins + my added code, and thus I should track it as one solution. When WP or a plugin is updated I need to test it on a dev and/or staging environment anyway, so it's better to know the version control status of the whole project. If I'm working on one plugin, I put it outside the WP directory and use symlinks from multiple installations to simplify testing. The repository is then only the plugin. The only problem there is that <code> __FILE__ </code> won't work, so I work with a <code> define() </code> to simulate my path.
|
Is it better to create a Git repository at the root level or in the WordPress theme directory?
|
wordpress
|
I have an excel spreadsheet that needs to get on a WP site PDQ and IE is choking on it. I tried making an html table, but it's huge. I looked into some kind a database plugin that would let me import a cvs and then let users browse it, but I can't even figure out the right search terms. I would appreciate any input. Thanks. My question: Do you have any suggestions? update 1/15/2011 I ended up using these steps - Go to Google Docs open the spreadsheet click Share Publish as a web page select the sheet to publish click Start publishing click on All cells field insert the cells range, e.g. A2:A3 click Republish now copy the-link Close . Example - <code> <iframe src="The-Link" width="w" height="h" frameborder="0"></iframe> </code> <code> the-link </code> = url from google <code> w </code> = width in pixels <code> h </code> = height in pixels
|
If you're using Google Docs, then this plugin Google Spreadsheet Viewer might be helpful.
|
I have a 1300 line excel spreadsheet that needs to get into a wordpress site ASAP - Looking for ideas
|
wordpress
|
I am inserting an image in a post and I want it to point to the post detail page, not the attachment. What should I do? Thanks in advance.
|
I think I understand what you want, and the problem you are having. I don't have code, but can point you toward some useful resources. I'm not sure how you are inserting an image into your excerpts on the homepage. My guess is that you are using the More tag in the post editor, inserted after the first paragraph + picture. However, many templates use the Post Excerpts Function, which will retrieve text from a post, but not include an image. If your template can/does support this, it might be preferable. These 2 methods (The More Tag vs Post Excepts Function) are described here: http://www.problogdesign.com/how-to/the-2-methods-of-showing-excerpts/ To achive the result you desire, I think you might want to use a feature called Post Thumbnail (dating from WordPress 2.9 and which must be enabled in your template). If Post Thumbnail is enabled in your template, it is simple to designate a post thumbnail for each post (when you write/edit the post in the WordPress dashboard). To retrieve that designated Post Thumbnail, your template index page PHP could get the thumbnail image using the function the_post_thumbnail (search if it in the Codex; I don't have privileges to use links here) You can hyperlink that image using get_post_meta also as described in the Codex. In the Codex you will find a good example that will demo how to test for the presence of a thumbnail, then use the thumbnail with a hyperlink to the full post. Please search the Codex for get_post_meta look for "Simple Loop Example" I hope this helps!
|
Make insterted image point to post url instead of attachment page
|
wordpress
|
I have a Theme Options page where the user can add certain options like Facebook links, etc. One of the options is for some ad code and when saving it as an option it gets escaped over and over again. What's the best approach for saving code inserted in an admin page <code> <textarea> </code> using <code> update_option( 'sidebar_code', $_POST['sidebar_code'] ); </code> ?
|
<code> stripslashes(wp_filter_post_kses(addslashes($_POST['sidebar_code']))); </code> but you should know that the kses filter is not 100% safe.
|
How to prevent escaping when saving HTML code in an option value?
|
wordpress
|
I got some problems during my loading priority/order that i already discovered. Now i ran into the problem that i can't use any post_thumbnail functions (get_post_thumbnail_id, has_post_thumbnail, the_post_thumbnail): "Call to undefined function"... Does anyone know at which point these functions are loaded? I would be satisfied if i know after which hook they get loaded. Thanks! Edit: I traced down all files that get loaded on my edit custom post type edit screen. It's 64 file from core before my theme files start loading. Files starting from #26 are: /wp-includes/general-template.php /wp-includes/link-template.php /wp-includes/author-template.php /wp-includes/post.php /wp-includes/post-template.php /wp-includes/category.php /wp-includes/category-template.php ... but /wp-includes/post-thumbnail-template.php doesn't seem to load. Weired ... Edit 2: post thumbnail support is activated and i can upload images. Only when i try to view them then i get the error about the id function. My problem is that it worked an hour ago and i need to track down whatever is causing this behavior. Edit 3: Funny. I load my files at init.. right after the file should get included. Plus: I just downloaded wordpress again and replaced the file, so everything from this side should be fine.
|
These are included in <code> wp-settings.php </code> right after <code> after_setup_theme </code> hook and so should be available starting with <code> init </code> hook. Also check if you have <code> add_theme_support( 'post-thumbnails' ); </code> declared in your theme, otherwise these functions won't be included at all.
|
On what point (hook) does the_/has_post_thumbnail() load?
|
wordpress
|
I have this simple snippet to retrieve the categories (taxonomies) of my Custom Post Type 'portfolio' I need to display each taxonomy but it displays all the categories. I just saw this question stackexchange-url ("Filter get_categories() for taxonomy term in WordPress") and unfortunately I tried with no success. <code> <?php query_posts("post_type=portfolio"); if ( have_posts() ) : while ( have_posts() ) : the_post(); $catid = get_cat_id('Images'); ?> <?php $categories= get_categories('child_of='.$catid.'&orderby=name'); foreach ($categories as $cat) { $input = '<li><a href="#" data-value="category-'.$cat->category_nicename.'">'; $input .= $cat->cat_name; $input .= '</a></li>'; echo $input; } ?> </code> Can you please guide me or give me a hint? Thanks so much.
|
First, you are mixing up terminology a bit. Portfolio is <code> taxonomy </code> , but Work, Images, etc are <code> terms </code> (not <code> categories </code> ). So you need to adjust functions for your taxonomy. Try this: Replace: <code> $catid = get_cat_id('Images'); </code> Becomes: <code> $catid = get_term_by( 'name', 'Images', 'portfolio' ); $catid = $catid->term_id; </code> And: <code> $categories = get_categories('child_of='.$catid.'&orderby=name'); </code> Becomes: <code> $categories = get_categories('child_of='.$catid.'&orderby=name&taxonomy=portfolio'); </code>
|
Filter get_cat_id for Custom Post Type
|
wordpress
|
I'm writing a plugin for work (still) and having one more issue. I've added my meta boxes as needed. However, the problem I'm having occurs when saving the post. My snippets for saving pretty much come from stackexchange-url ("this post"). I've also recieved a similar answer stackexchange-url ("here"), but it's just not working for some reason. :/ <code> protected function __update_post_meta( $post_id, $field_name, $value = '' ) { if ( empty( $value ) OR ! $value ) { delete_post_meta( $post_id, $field_name ); } elseif ( ! get_post_meta( $post_id, $field_name ) ) { add_post_meta( $post_id, $field_name, $value ); } else { update_post_meta( $post_id, $field_name, $value ); } } </code> The above is called using the following. However, I'm not sure my problem lies with the actual saving now that I think of it. I'm thinking it might be the <code> nonce </code> which may be throwing it off. <code> public function _wp_save_post( $post_id, $post ) { if ( empty($_POST) OR !isset($_POST['argus_edit_visitor']) OR !wp_verify_nonce( $_POST['argus_edit_visitor'], 'argus_edit_visitor' ) ) { return $post->ID; } if ( ! current_user_can( 'edit_post', $post->ID ) ) return $post->ID; // v_f_name | v_l_name | v_workstation | v_id // Argh! $this->__update_post_meta( $post->ID, 'v_f_name', $_POST['v_f_name'] ); $this->__update_post_meta( $post->ID, 'v_l_name', $_POST['v_l_name'] ); $this->__update_post_meta( $post->ID, 'v_workstation', $_POST['v_workstation'] ); $this->__update_post_meta( $post->ID, 'v_id', $_POST['v_id'] ); } </code> The nonce is used like the following: <code> <input type="hidden" name="argus_edit_visitor" id="argus_edit_visitor" value="{$nonce}" /> </code> and created using <code> $nonce = wp_create_nonce( plugin_basename( __FILE__ ) ); </code> . The input field is inside block of html being stored in variable $html. Stackexchange was parsing my html otherwise I'd paste it here. -Zack EDIT: Just tested it, and it is the nonce's fault. EDIT2: Typo on my part, but still doesn't work.
|
I really like your clean class structure :-) But I have a suggestion that might fix things (based on my experience with nonces and meta boxes from a plug-in I built last weekend): Don't try to create the nonce field manually. You currently have: <code> $nonce = wp_create_nonce( plugin_basename( __FILE__ ) ); ... <input type="hidden" name="argus_edit_visitor" id="argus_edit_visitor" value="{$nonce}" /> </code> The standard way to create this field is using WordPress' <code> wp_nonce_field() </code> function. It will add the hidden field for you: <code> wp_nonce_field( __FILE__, 'argus_edit_visitor' ); </code> Verifying the nonce You're verifying against the wrong string. In your code, you created the nonce with <code> __FILE__ </code> but you verify with the string <code> argus_edit_vistor </code> . You have: <code> if ( empty($_POST) OR !isset($_POST['argus_edit_visitor']) OR !wp_verify_nonce( $_POST['argus_edit_visitor'], 'argus_edit_visitor' ) ) { echo "Erm. Why?"; return $post->ID; } </code> You should have: <code> if ( empty($_POST) OR !isset($_POST['argus_edit_visitor']) OR !wp_verify_nonce( $_POST['argus_edit_visitor'], __FILE__ ) ) { echo "Erm. Why?"; return $post->ID; } </code> I usually use <code> plugin_basename(__FILE__) </code> when creating nonces. But you shouldn't run into problems doing it your way so long as the nonce creation and nonce verification happens in the same file.
|
Updating post meta for custom post types
|
wordpress
|
In the code snippet below, I trying to get the_excerpt to be written out without tags. However, the source formatting shows that the_excerpt is always wrapped in P tags. How can I pull the excerpt without tags? <code> foreach($myrecentposts as $idxrecent=>$post) { ?> <li class="page_item"> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> <?php echo strip_tags(substr( the_excerpt(), 0, 75 ))."..." ?> </li><?php } echo "</ul> </div>";} </code>
|
in your code above use <code> get_the_excerpt() </code> instead of <code> the_excerpt() </code> , because the last one will output the excerpt to the screen, and not pass it to your other functions...
|
How to echo the_excerpt without the P tag wrapper?
|
wordpress
|
In the code below represents a link list of recent posts. I'm just trying to write out the post name, along with the post excerpt if one exists. So I'm using the get_link_excerpt($post) function in order to determine if the current post in the for loop has an excerpt. It works fine if the post has an excerpt, however, if it doesn't, the get_the_excerpt() function is returning its own excerpt crafted from the current page's content. In this case, I'm placing this function on the home page, so every post that does not explicitly have a snippet is getting a virtual excerpt from the home page's content. Apparently, I'm passing $post improperly, what's the correct way to do it here? <code> function show_footer_recent(){ $myquery = new WP_Query();$myquery->query(array('post__not_in' => get_option('sticky_posts'))); $myrecentpostscount = $myquery->found_posts; if ($myrecentpostscount > 0){ ?> <div> <ul><i>Latest News & Articles</i> <?php global $post;$myrecentposts = get_posts(array('post__not_in' => get_option('sticky_posts'),'numberposts' => get_option('cb2_recent_count'))); foreach($myrecentposts as $idxrecent=>$post) { ?> <li class="page_item"> <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a><?php echo get_link_excerpt(); ?> </li><?php } ?> </ul> </div> <?php }} function get_link_excerpt(){ $LinkExcerpt = strip_tags(substr(get_the_excerpt(), 0, 75 )); if($LinkExcerpt != '') { return ": ".$LinkExcerpt."..."; } return false; } </code>
|
I got it working. Here's what I had to do in my utility function... <code> function get_link_excerpt(){ if(has_excerpt()){ $LinkExcerpt = strip_tags(substr(get_the_excerpt(), 0, 75 )); return ": ".$LinkExcerpt."..."; } return false; } </code>
|
get_the_excerpt() is not returning an empty string when the_excerpt is blank?
|
wordpress
|
I have been coding a custom profile page for users in wordpress. its a hard coded file called "myprofile.php" I am unable to get the username to show up in the page title.. take a look : http://www.designzzz.com/user/ayazmalik/ k i tried a few filters to add title to this page but didn't helped me :( . lets say the username storing variable is $myusername . how can i do it.. im considering this title : <code> <title>user_name</title> </code> Help is appreciated :) cheers
|
<code> function my_doc_title($title, $separator){ if(is_author()) // <- replace this with your custom page; maybe is_page_template('myprofile.php') ? $title = get_the_author_meta('display_name', get_query_var('author')).$separator.get_bloginfo('name'); return $title; } add_filter('wp_title', 'my_doc_title', 10, 2); </code> (functions.php)
|
Adding page Title in a custom coded page
|
wordpress
|
I've got a custom php file that I want to call every time someone publishes a new post. How would I go about doing that? Can I write it into the functions.php of my theme?
|
<code> add_action('publish_post', 'call_my_php_file'); function call_my_php_file($post_id){ require_once("path/to/file.php"); } </code>
|
How would I got about calling a php file every time someone publishes a new post?
|
wordpress
|
In my WordPress plugin I have a php file that generates some stats about the blog and outputs it as a simple text file. To access WordPress functions I've included this at the top of the file: <code> define('WP_USE_THEMES', false); require(dirname(__FILE__) . '/../../../wp-blog-header.php'); </code> Now I'd like to hide the actual URL, since it's in the wp-content/plugins directory and replace it with something nice and short: <code> http://example.com/wp-content/plugin/data-fetcher/list-data.php -> rewrite to http://example.com/list-data </code> I added this to <code> .htaccess </code> : <code> <IfModule mod_rewrite.c> RewriteEngine on RewriteBase / RewriteRule ^list-data$ wp-content/plugins/data-fetcher/list-data.php [L] </IfModule> </code> The problem: when I access the short URL, I get a 301 Moved Permanently redirect before I end up on the page. This means that the wp-content/plugins/... URL is revealed in the browser. I suspect that WordPress is initiating this somehow. The rewrite rule works fine for images and plain php files (i.e. without WP includes/require). Is my assumption correct? How can I prevent WordPress from sending the redirect?
|
Mark, I hate to say it, but you're going about this the wrong way. PHP files in your plug-in should never be accessed directly in this way. Instead, they should be loaded from within WordPress just like everything else. Here are some alternative paths you could take: Create an admin page that displays your stats This is a page accessible from within WordPress by authenticated users only. If you use the correct API, this page will look very clean and will display your simple stats however you want. Since it's inside WordPress to begin with, you'll already have access to the entire WP API without needing to load <code> wp-blog-header.php </code> directly. Use your existing system, but register the rewrite with WordPress You should never modify your <code> .htaccess </code> file directly. This file can be changed when you add new plug-ins or change your permalink structure, meaning you'll lose your customizations. Instead, you can create a custom rewrite by making a function call within WordPress itself: <code> add_action( 'init', 'my_rewrite' ); function my_rewrite() { global $wp_rewrite; add_rewrite_rule('list-data/$', WP_PLUGIN_URL . '/data-fetcher/list-data.php', 'top'); $wp_rewrite->flush_rules(true); // This should really be done in a plugin activation } </code> This will add your custom rule to the top of the WordPress rewrite rules and should skip any other redirects WordPress matches against the regex. For a great example of how you can implement this kind of simple rewriting in a plug-in, check out Ozh's tutorial on redirecting a pretty login URL: Pretty Login URL: a Simple Rewrite API Plugin Example
|
Making a plugin file accessible via url rewrite?
|
wordpress
|
How can I add three menus to the Thesis theme ? I want a menu above the header image, one below the header image and one in the footer. A neat step by step instruction stackexchange-url ("like this for Twenty Ten") would be like the coolest answer.
|
A neat step by step instruction like this for Twenty Ten would be like the coolest answer. You can follow those instruction starting at Step 3 as your working with WordPress after all. I'm sure Themeatic has some sort of snazzy hook but you will have to ask them.
|
Creating Multiple Menus in the Thesis Theme?
|
wordpress
|
I have a custom post type created for a directory that will end up being sorted alphabetically. I will be sorting the posts in alphabetical order by title, so I want to make sure that the Title is entered as last name/first name. Is there a way to change that default help text -- "Enter Title Here" -- in my custom post to something else?
|
There is no way to customize that string explicitly. But it is passed through translation function and so is easy to filter. Try something like this (don't forget to change to your post type): <code> add_filter('gettext','custom_enter_title'); function custom_enter_title( $input ) { global $post_type; if( is_admin() && 'Enter title here' == $input && 'your_post_type' == $post_type ) return 'Enter Last Name, Followed by First Name'; return $input; } </code>
|
Change "Enter Title Here" help text on a custom post type
|
wordpress
|
Is it possible to make a meta box that attaches multiple images to a post?
|
That depends entirely on what you mean by "attach." Each WordPress post can already have multiple media attachments - photos, documents, etc. You upload these using the built-in uploader and they'll all be marked as "attached" to that specific post ID. You can refer to these later programatically elsewhere. For example, the following code will list out all attachments for a specific post (code from Snipplr ) : <code> $args = array( 'post_type' => 'attachment', 'numberposts' => null, 'post_status' => null, 'post_parent' => $post->ID ); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $attachment) { echo apply_filters('the_title', $attachment->post_title); the_attachment_link($attachment->ID, false); } } </code> All of this functionality is accessible via the default "Add Media" button to the far right of "Upload/Insert" on the new post screen. After you add one image, you can click "Select Files" again and upload a second image. Then a third. Then a fourth. As many as you want. Each of these images will be "attached" to the post ... even if they're not inserted into the content.
|
Creating a metabox to upload multiple images
|
wordpress
|
I believe I could do this with either get_categories() or wp_list_categories() and passing a 'child_of' parameter, for example, but that would return a much larger dataset than I need. Is there a direct call that returns the child ids for any category as a simple list (1,2,3,5, etc)?
|
Try this: <code> get_terms( 'category', "child_of=$parent&fields=ids" ); // should return an array containing the ID's of children of term $parent </code>
|
How to get a list of child ids for a named category?
|
wordpress
|
Is there any way at all to restrict direct access to files within a specific folder to only specific wordpress users that have that specific capability set?
|
The easiest php solution would be to make a download script. It checks if the user has the right permissions and serves the file to the webclient. Or my preference setup a folder outside your web root and put the files there. Set the file permissions with no anonymous access and let the webserver read them and output them in a php file like this. The below code reads the file and sents it to the browser. <code> header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header('Content-disposition: attachment; filename='. $file; header("Content-Transfer-Encoding: binary"); header("Content-Length: ". filesize(ABSPATH.$dir.$file); readfile($dir.$file); exit(); </code> edit 14-1: create a normal upload box and when the file gets uploaded move it to a folder outside of your webroot directory (this folder can not be accessed by users through http, only the webserver. <code> if (move_uploaded_file( $_FILES['Filedata']['tmp_name'] , $upload_dir.$filename ) ) { // code to do after the file has been copied succesfully. Update your database or something. } </code> $upload_dir.$filename is the full path to the directory outside the www folder. The file can now only be accessed by the webserver. Store the location in a database with uploader info. Or create subdirectories for each user. You need something to differentiate the files for each user. Now when you want to download a file create a script called download.php In that script you check if the user has rights to the file. <code> global $user; if ($user->id == $uploaded_user_id) { header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private",false); header('Content-disposition: attachment; filename='. $file; header("Content-Transfer-Encoding: binary"); header("Content-Length: ". filesize(ABSPATH.$upload_dir.$file); readfile($upload_dir.$file); exit(); } </code> now you want to pass a file_id or name to the download script. so craft the link like url/download.php?file=$file. You have to call this directly or at the early stages of your plugin or you will get the headers already sent message. The script will check if the user has rights and start to output binary data. It should be something like this, hope it helps. Its not the complete but should get you started.
|
Restricting access to files within a specific folder
|
wordpress
|
The built-in ability to restore revisions of posts and pages in Wordpress is great. Is there something that gives the same power to template files in the theme-editor? Perhaps a plugin?
|
Templates are only stored as files in the file system. They are not stored in the database so there is no core functionality for versioning template files. When you make changes, the file is overwritten with the changes. The easiest route would be to use an existing version control solution (SVN,CVS,Git,Hg, etc.) and maintain the versioning separate from WordPress.
|
Best way to version control WordPress template files?
|
wordpress
|
My category descriptions are extremely long, so I don't want the descriptions to be used in the title attribute of my category lists. However, WP does this automatically when it outputs the default category widget in the markup. Is it possible to add a filter in functions.php that assigns the default value for 'use_desc_for_title' to 0? (The default is 1)?
|
I was finally able to figure this out. Much easier than I thought... <code> function my_categories_filter($cat_args){ $cat_args['title_li'] = ''; $cat_args['exclude_tree'] = 1; $cat_args['exclude'] = 1; $cat_args['use_desc_for_title'] = 0; return $cat_args; } add_filter('widget_categories_args', 'my_categories_filter', 10, 2); </code>
|
How to add 'use_desc_for_title = 0' to all wp_list_categories calls?
|
wordpress
|
I'm using this plugin (http://wordpress.org/extend/plugins/wp-downloadmanager/) as my download manager. While it's very simplistic and does great for what i need, the statistics to output on the site lack a little. The only useful function really is: Display Most downloaded (of all time). While i do use this, it would be handy to have a Most downloaded this week or this month as new files get lost on the all time ranks. I've dug through the code and found this query for the most downloaded function: <code> $files = $wpdb->get_results("SELECT * FROM $wpdb->downloads WHERE file_permission != -2 ORDER BY file_hits DESC LIMIT $limit"); </code> I'm not sure if it's possible as i haven't a clue about mysql but can we simply add something to that line to query most downloaded files during this week or month? More info on the plugin here: http://lesterchan.net/wordpress/readme/wp-downloadmanager.html (Click on the usage tab) Thanks
|
Simple answer: No. Complex answer: After looking at the plugin's source code , the downloads table used to store the stats is not structured such that you could just edit this single query to give you that kind of information. It would take a much more extensive rewrite of the plugin to handle your request. Possible Workaround: The plugin has a function called <code> get_recent_downloads </code> which looks like it outputs a list of the newest files.
|
WP-DownloadManager - Query most download per week/month etc
|
wordpress
|
I'm successfully using the function below to trim the length of my category descriptions when viewing the manage category screen (thanks Rarst). Suppose I want to remove children of the "uncategorized" category from this listing. Would I simply insert a check in the for loop below to skip over those child items? UPDATE: With Rarst's tip on using unset(), I've amended the code below with the correct bits to remove specific categories from the manage categories listing... <code> //Clean up description summaries on Category manage edit table add_action( 'admin_head-edit-tags.php', 'admin_edit_tags' ); function admin_edit_tags() { add_filter( 'get_terms', 'admin_trim_category_description', 10, 2 ); } function admin_trim_category_description( $terms, $taxonomies ) { if( 'category' != $taxonomies[0] )return $terms; foreach( $terms as $key=>$term ) { $terms[$key]->description = strip_tags(substr( $term->description, 0, 75 ))."..."; //new bits here if($terms[$key]->term_id == 1){unset($terms[$key]);} } return $terms; } </code>
|
Yes, <code> $terms </code> contains all terms that are retrieved from database for display so whatever changes you make will cascade upwards to interface. One issue I am not sure about if that will affect pagination of results in this case.
|
How to filter manage categories listing
|
wordpress
|
The "manage categories" screen has two interfaces, one when you first click on "Categories" which is used to add a new category and another once you click on an existing category to edit it. I've added some custom fields to the Category editor, but I only want them to be present on the edit screen, not the "add" screen. However $pagenow in both cases, is the same (edit-tags.php). The only difference I can see is that when editing, the action=edit token appears on the querystring. Should I simply wrap my "edit_category_form" filter in a test for the existence of that token or is there a better way? PS: I'd be fine with leaving the fields on the add screen, however, it appears that the save is ajaxed, and none of my custom fields are being saved in that routine.
|
You can target <code> edit-tags.php </code> page and additionally check for that <code> edit </code> action. <code> add_action( 'admin_head-edit-tags.php', 'my_category_edit' ); function my_category_edit() { global $action, $taxonomy; if( 'edit' != $action || 'category' != $taxonomy ) return; // code goes here } </code>
|
How to conditionally include a custom field on category editor screen not category "add" screen
|
wordpress
|
I've added a "Custom Title" field to the Category editor in order to capture a keyword friendly title that can be used separately from the category name. It works great, but it appears as the last input element of the category screen. Ideally, I would like it to sit under the "Name" field (or at the very top). Is this possible? Here's the code I'm using to add my custom input field to the category edit screen... <code> if($pagenow == "edit-tags.php" && $_REQUEST['action'] == "edit") add_filter('edit_category_form', 'my_category_fields'); function my_category_fields($tag) { $tag_extra_fields = get_option(MY_CATEGORY_FIELDS);?> <table class="form-table"> <tr class="form-field"> <th scope="row" valign="top"><label for="categoryTitle">Full Category Title</label></th> <td><input name="categoryTitle" id="categoryTitle" type="text" size="40" aria-required="false" value="<?php echo $tag_extra_fields[$tag->term_id]['cat_title']; ?>" /> <p class="description">The title is optional but will be used in place of the name on the category landing page.</p></td> </tr> </table> <?php } </code>
|
Hi @Scott B: WordPress doesn't provide the hooks you want but it you are willing to use PHP's output buffering and <code> preg_replace() </code> you can get it to work without hacking core. Here's an answer that talks about the general technique required: <a href="stackexchange-url Removing Unnecessary Text from Admin Menu without CSS The hooks you'll want to use are <code> 'category_pre_add_form' </code> for <code> ob_start() </code> and <code> 'category_add_form' </code> for <code> ob_get_clean(). </code>
|
How to alter the order of custom form fields
|
wordpress
|
I have tried changing the template of the attached page and changing which page is attached as the home page, no effect for either. The front page remains the same. I am at my wits end with this one!!
|
What is your setup for front page in <code> Settings > Reading </code> ? Do you have <code> front-page.php </code> template in your theme? It will pretty much override anything, no matter what you choose in settings.
|
front page won't change templates
|
wordpress
|
Wordpress has a Text Widget (at least the theme I'm using does, and I think they all do?) In this widget I can add text or HTML. If I add HTML I can include JavaScript. This works fine (I'm hosting my own site). I want to add some text to the Widget using a script. However; document.write("Whatever") writes the text onto the actual web page. What command do I use to write text into the Text Widget only. Many thanks for any help!
|
Where are you using <code> document.write </code> ? Inside the text widget? If so, it should write text inside that widget, just like you want. <code> document.write </code> injects data where it's encountered. So if you're using it outside the document body it will produce unexpected results (like overwrite the document, in most cases). **Update, add this in your text widget: <code> <div id="textwidget-content"> YOUR INITIAL TEXT HERE </div> <script type="text/javascript"> var strings = new Array('Whatever', 'Bla blah', 'Boo', '....'); var t = setInterval(function(){ document.getElementById('textwidget-content').innerHTML = strings[Math.floor(Math.random()*(strings.length))];}, 1000); </script> </code>
|
Add text to Text Widget using Javascript
|
wordpress
|
I use the following function in order to retrieve tags of a post, remove an element from the array and then set the result to the post: <code> $post_tags = wp_get_post_terms( $post_id ); foreach ( $post_tags as $key => $tag) { $tag_string = http_build_query( $tag ); if( 0 != strpos( $tag_string , 'tag-to-be-deleted' ) ) { unset( $post_tags[$key] ); } } wp_set_post_terms ($post_id, $post_tags, 'post_tag'); </code> Then I get a bug inside the wp_set_post_terms function, that says the $post_tags parameter should be a string and not an array...what am I doing wrong here? Any help would be appreciated.
|
Your code looks little clunky, <code> http_build_query() </code> is definitely not meant for such. Also what you are fetching is not simple array, but array of tag objects. My take: <code> $post_tags = wp_get_post_terms( $post_id, 'post_tag', array( 'fields'=>'names' ) ); $pos = array_search( 'tag-to-be-deleted', $post_tags ); if( false !== $pos ) { unset( $post_tags[$pos] ); wp_set_post_terms ($post_id, $post_tags, 'post_tag'); } </code>
|
Problem with removing post tags programmatically
|
wordpress
|
This is a similar question to stackexchange-url ("Sorting for each custom taxonomy"), but I don't feel like it was clearly asked or responded to. I have a custom post type "player" and a custom taxonomy "player_details". The player details consists of things like Height, Weight, Country, Jersey #, etc. I want to add a custom filter / sorting mechanism to my player archives so that you could sort by height, weight, etc. The built-in query_posts function allows you to sort by date, title, etc, but I don't see how to sort by taxonomy. I realize that if the taxonomy details, were in custom fields, I could sort it that way, but that defeats the purpose of storing it in a custom taxonomy, which is where it should be stored. Is there a way to do this that I'm not aware of, or is it going to require some deep hacking into Custom Queries? http://codex.wordpress.org/Custom_Queries
|
This doesn't seems to be natively possible, even with upcoming improvements in WP 3.1. [...] That’s not what taxonomies are for. Taxonomies are for grouping, not for ordering by. If you want to order by something, it has to be something in the post itself, not a term in a taxo. Otto For this kind of data custom fields make much more sense. Instead of "group of people who weight 60kg", it should be "Player A (60kg), Player B (60kg), etc". Details are by definition individual. Taxonomies are broad generic groups.
|
Sorting the Loop by Taxonomy Value
|
wordpress
|
I am creating a post and would like to link to other post on my blog. What is the best way to do this? I don't want to hard link in case I update the post title. Is there a way to do this?
|
Use the ugly link instead of the pretty link. For example, if your post id is 123, you can link to http://www.yoursite.com/?p=123 . This will automatically get rewritten to your current pretty permalink. If you do it relative from the root, it also keeps the link intact if you change your domain name. (ex. href="/?p=123"). To find the post ID, hover over its "edit" link in the WordPress admin. Look at the target URL, and you'll see a "post=1234". The number is your post ID.
|
How to link to local post
|
wordpress
|
For a custom post type page I'd like to completely remove the slug so that the URL structure mirrors http://my-domain.com/CPT-title/ or http://my-domain.com/CPT-category/CPT-title . If I set the rewrite parameter to <code> 'rewrite' => array('slug' => '', 'with_front' => false) </code> Wordpress freaks out and I get 404 on all pages except for the CPT page. If I don't define slug at all, then it defaults to the CPT name.
|
You have to set 'slug' to false and not a blank string.
|
How do you remove slug altogether from custom post type?
|
wordpress
|
I'm running a multi-author wp site and I'm looking for a plugin that adds a "Follow me" button near the author name so the user can follow his favourite author. I need also to display the other users that are are following the author (i.e. "38 people are following Author_name -> click to view users). I know there is buddypress, but I'm looking for something lighter and stand-alone. Thanks
|
Hi @Andy: Are you up for developing something in PHP and jQuery? It should't be too hard to add a button that would do an AJAX submit to add How many total followers do you except anyone to have on your site. If the number is less than 1000 you might get away with just storing a comma separated list of <code> user_id </code> fields in a <code> wp_usermeta </code> value, or you could add one record in each <code> wp_usermeta </code> record per follower. All in all, not a super big project?
|
Twitter-like follow system, is there any plugin?
|
wordpress
|
I hope somebody would be kind enough to help. I currently have a page that orders all of the posts by comment count, but I want to change the loop to order the posts by view count. I have installed the 'wp-postviews.1.50' plugin and have got it to display the number of views on each post, so I know that side of it is working, now I just need the loop code changed to order by most views, is this possible? This is the how the number of views is called out: <code> <?php $views = get_post_meta($post->ID, 'views', true); ?><?php echo $views; ?> </code> And here is the loop I need changed: <code> <?php $posts_per_page = get_query_var('posts_per_page'); ?> <?php $paged = intval(get_query_var('paged')); ?> <?php $paged = ($paged) ? $paged : 1; ?> <?php $args = array( 'posts_per_page' => $posts_per_page, 'paged' => $paged, 'more' => $more = 0, 'orderby' => 'comment_count', 'order' => 'DESC', ); ?> <?php query_posts($args); ?> <?php if (have_posts()) : while (have_posts()) : the_post() ;?> <div <?php post_class() ?> id="post-<?php the_ID(); ?>"> </code> Thanks in advance for any help with this. I'm using WordPress 3.0.4.
|
Just wanted to give an update. Someone was kind enough to show me how to update the code I posted above. It turned out to be quite simple (if you know what you're doing!). So I have posted it below for anyone that wants to do something similar. <code> <?php $posts_per_page = get_query_var('posts_per_page'); ?> <?php $paged = intval(get_query_var('paged')); ?> <?php $paged = ($paged) ? $paged : 1; ?> <?php $args = array( 'posts_per_page' => $posts_per_page, 'paged' => $paged, 'more' => $more = 0, 'meta_key' => 'views', 'orderby' => 'meta_value_num', 'order' => 'DESC', ); ?> <?php query_posts($args); ?> <?php if (have_posts()) : while (have_posts()) : the_post() ;?> <div <?php post_class() ?> id="post-<?php the_ID(); ?>"> </code>
|
How to Change Loop to Order Posts by Views (using wp-postviews plugin)
|
wordpress
|
I've tried disabling WP's auto-paragraph thingy using <code> remove_filter ('the_content', 'wpautop'); </code> but I am still getting my stuff wrapped in automatic <code> <p> </code> tags... What am I doing wrong? Its at the bottom of a functions file. Its not in functions.php, but in a file that functions.php includes (and putting it in functions.php doesn't change the behaviour at all). Update: <code> var_dump( $wp_filter['the_content'] ); </code> outputs <code> NULL </code> . How can I test why this filter isn't being run?
|
http://wordpress.org/extend/plugins/noautop/ I made this a while back, you can just install it and use it, or dig into the code (its a super small plugin) and see how I do it. The plugin adds the tag the_content_noautop(); which you can use in your template specifically when you don't need a paragraph tag.
|
Remove_filter ('the_content', 'wpautop') is not working
|
wordpress
|
I'm not looking for a sitemap, I'm looking to create an xml file that I can have a flash menu access, but I don't want to generate the XML file each time someone visits a page, I want to have a static XML to refer to for speed. And I'd like to have wordpress update the file whenever new content is posted(not comments). Is there anything built into wordpress that would allow me to do this? Any plugins? Again, I don't want a sitemap. I want a specific list of items. Right now I've been using page templates with custom loops, but it takes to long to generate every time.
|
Hmm... not sure if there are any WordPress-specific functions for creating files. There's wp_handle_upload, but I'm not sure how you'd use it in this context. Depending on your server configuration, you can probably just use fopen and fwrite to do this. Keep the code you're currently using (with your custom loops...I'm assuming they contain the XML markup you want), but have it build the output as a string. Then save that string into a file. Something like: <code> // Build your file contents as a string $file_contents = '<?xml version="1.0" ?><yourroot><item>some content</item></yourroot></xml>'; // Open or create a file (this does it in the same dir as the script) $my_file = fopen("myfile.xml", "w"); // Write the string's contents into that file fwrite($my_file, $file_contents); // Close 'er up fclose($my_file); </code> Of course, this all depends on your server config and permissions. Maybe someone has a better solution that only requires native WP functions.
|
Make wordpress generate a custom XML file(not a sitemap) that is updated only when new content is posted?
|
wordpress
|
When a site gets to a certain scale, storing categories on a per-blog basis starts to get a little messy. Assuming someone would want all WPMU blogs to share a single set of categories, how might one go about that? My gut it so store a set of "cannonical" categories in the root blog. Is there a more elegant or standardized solution?
|
A more elegant solution would be to create a MU (must use) plug-in and drop it on the network. This plug-in would check (per-site) if the categories exist and, if not, add them as appropriate. Here's some untested example code: <code> <?php $default_categories = array( 'my_first_cat', 'my_second_cat', 'my_third_cat' ); foreach($default_categories as $cat) { if( get_cat_ID( $cat ) != 0 ) continue; wp_insert_term( $cat, 'category' ); } </code> This should loop through your list of categories and attempt to fetch the ID of each. If the category doesn't exist, <code> get_cat_ID() </code> will return "0" so you know to insert the category. This code won't set the slug, description, parent, etc ... I leave that as an exercise for you to complete.
|
Can you have a single set of "canonical" categories shared by all blogs?
|
wordpress
|
my self-made admin panel works just fine, but it doesn't save values of form inputs. When I type something into textbox and click "save" it is still there after refreshing, thanks to PHP: <code> <input type="text" name="header" value="<?php echo get_option('header'); ?>" /> </code> So the PHP echoes its own value to a input and everything is just fine. But what to do when I have list of 10 radio buttons or just a checkbox? For now I have a checkbox like this: <code> <input type="checkbox" name="showS" value="true"> </code> And after clicking on it and saving - it's still "unclicked". Any helping had?
|
This is really just an html question, not specific to WordPress. Look into <code> checked="checked" </code> (for check boxes) or <code> selected="selected" </code> (for selects, radio buttons, etc.) In your case, <code> <input type="checkbox" name="showS" value="true" <?php if (get_option('showS')==true) echo 'checked="checked" '; ?>> </code> Since this is WordPress, though, I should also be reminding you to use the Settings API where possible. Don't try to sanitize and validate all of the inputs yourself unless you really know what you're doing. Here's a link to a tutorial on the Settings API: http://ottopress.com/2009/wordpress-settings-api-tutorial/
|
Saving checkbox/option list status?
|
wordpress
|
i need to display under every article in the main page, the respective number of post views. I tried with a plugin called wp.postviews but I cant figure out how it's works...it allow only the widget component. What I have to do to get the postviews? I think I have to use the plugin above and add some extra php code on the index.php Thanks for help
|
<code> if(function_exists('the_views')) the_views(); </code>
|
get postviews under every posts in the main page
|
wordpress
|
I think this must be a simple question, despite the seemingly broad title. My wordpress theme by default displays several social icons. (You can see them here , in the upper right corner.) I'm trying to add a new icon to the existing ones. I've already generated and uploaded a new image, modified all the css and php files that (I think) required modification. However, I'm missing one key thing: somewhere, somehow the theme generates some source html that includes an unordered list that displays the icons: <code> <ul id="socialize-icons"> <li id="icon-rss"><a href="http://somelink.com">RSS Feed</a></li> <li id="icon-facebook"><a href="http://somelink">facebook</a></li> <li id="icon-twitter"><a href="http://somelink">twitter</a></li> </ul> </code> I cannot figure out where this code is generated so that I tweek it to include my new additional icon. If someone could point me in the right direction (a function, some wp documentation), I'd really appreciated it.
|
As @Ambitious Amoeba indicated above, what I was looking for was hardcoded in the footer template.
|
How does WP generate html?
|
wordpress
|
I have my permalink set to <code> %postname%/%location%/%course% </code> I want this permalink <code> %location%/%course%/%postname% </code> but due to this I get 404 on every page but not on posts, I decided to put this permalink <code> %postname%/%location%/%course%/%postname% </code> but I need to strip the starting postname, in such a way I ll get no 404 pages and google will also index my site with this permalink <code> /%location%/%course%/%postname% </code> without any 404 how to do this???? This is my code, for displaying custom taxonomies on permalinks <code> add_filter('post_link', 'location_permalink', 10, 3); add_filter('post_type_link', 'location_permalink', 10, 3); function location_permalink($permalink, $post_id, $leavename) { if (strpos($permalink, '%location%') === FALSE) return $permalink; // Get post $post = get_post($post_id); if (!$post) return $permalink; // Get taxonomy terms $terms = wp_get_object_terms($post->ID, 'location'); if (!is_wp_error($terms) && !empty($terms) && is_object($terms[0])) $taxonomy_slug = $terms[0]->slug; else $taxonomy_slug = 'location'; return str_replace('%location%', $taxonomy_slug, $permalink); } </code>
|
Apologies that this doesn't directly answer your question but If I were you I would use the following structure: <code> /%post_id%/%location%/%course%/%postname% </code> Using the id should help to speed up the page load as it reduces the amount of processing that WP needs to do to select the correct page and you still get a nice enough url.
|
htaccess strip url
|
wordpress
|
A custom shortcode i made is being forced to the top of the widget outside of the widget container. Any ideas why? This is my code... <code> function nktmediaplayer_func($atts) { extract(shortcode_atts(array( 'id' => rand(1, 900), 'language' => 'en', 'playlist' => 'no', 'media' => '3381', 'height' => '480', 'width' => '640', 'style' => 'single' ), $atts)); ?> <div id="player_<?php echo $id; ?>" class="video_player"><a href="http://www.adobe.com/products/flashplayer/">Get the Flash Player</a> to see this player.</div> <script type="text/javascript" src="http://kadampa.org/embed/apps/jwplayer.js"></script> <script type="text/javascript"> jwplayer("player_<?php echo $id; ?>").setup({ flashplayer: "http://kadampa.org/embed/apps/player.swf", playlistfile: "http://kadampa.org/<?php echo $language; ?>/api/video/<?php if ( 'playlist' == 'yes' ) echo 'playlist/'; ?><?php echo $media; ?>/desc", height: "<?php echo $height; ?>", width: "<?php echo $width; ?>", config: "http://kadampa.org/embed/config/<?php echo $style; ?>.xml" }); </script> <?php } add_shortcode('nkt_mediaplayer', 'nktmediaplayer_func', 10); </code>
|
For shortcodes you have to return the output for it to be written out where the shortcode appears. Either turn your HTML into a PHP string rather than breaking out of the PHP tags or you can use PHPs output buffering methods like so: <code> ob_start(); ?> <div id="player_<?php echo $id; ?>" class="video_player"><a href="http://www.adobe.com/products/flashplayer/">Get the Flash Player</a> to see this player.</div> <script type="text/javascript" src="http://kadampa.org/embed/apps/jwplayer.js"></script> <script type="text/javascript"> jwplayer("player_<?php echo $id; ?>").setup({ flashplayer: "http://kadampa.org/embed/apps/player.swf", playlistfile: "http://kadampa.org/<?php echo $language; ?>/api/video/<?php if ( 'playlist' == 'yes' ) echo 'playlist/'; ?><?php echo $media; ?>/desc", height: "<?php echo $height; ?>", width: "<?php echo $width; ?>", config: "http://kadampa.org/embed/config/<?php echo $style; ?>.xml" }); </script> <?php $output = ob_get_contents(); ob_end_clean(); return $output; </code>
|
Custom shortcode in widget forced to top of widget
|
wordpress
|
I am looking for a way to test if a post is a custom post type. For example, in say the sidebar I can put code like this: <code> if( is_single()) { //code here } </code> I want code were I could do this, only testing for a custom post type. Any help would be greatly appreciated!
|
Here you are: <code> get_post_type() </code> and then <code> if ( 'book' == get_post_type() ) ... </code> as per Conditional Tags > A Post Type in Codex.
|
If is custom post type
|
wordpress
|
I am using the PhotoSmash plugin to let users upload their own images and vote on them, and it works great. On one of my pages I use the following code to list the posts that have a certain category: <code> <?php if (is_page() ) { $category = get_post_meta($posts[0]->ID, 'category', true); } if ($category) { $cat = get_cat_ID($category); $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $post_per_page = -1; // -1 shows all posts $do_not_show_stickies = 1; // 0 to show stickies $args=array( 'category__in' => array($cat), 'orderby' => 'date', 'order' => 'ASC', 'paged' => $paged, 'posts_per_page' => $post_per_page, 'caller_get_posts' => $do_not_show_stickies ); $temp = $wp_query; // assign orginal query to temp variable for later use $wp_query = null; $wp_query = new WP_Query($args); if( have_posts() ) : while ($wp_query->have_posts()) : $wp_query->the_post(); ?> <section class="vote6" id="post-<?php the_ID(); ?>"> <?php the_content(); ?> <section class="voter"> <?php DisplayVotes(get_the_ID()); ?> </section> </section> <?php endwhile; ?> <?php else : ?> <h2 class="center">Not Found</h2> <p class="center">Sorry, but you are looking for something that isn't here.</p> <?php get_search_form(); ?> <?php endif; $wp_query = $temp; //reset back to original query } // if ($category) ?> </code> This works great as well, except when the PhotoSmash plugin is activated. I get the following error: Fatal error: Call to a member function get() on a non-object in \nas-001\winspace004\10-3mpromos.ca\www\carcrazy\wp-includes\query.php on line 27 Line 27 is <code> return $wp_query->get($var); </code> The issue is somewhere inside of bwb-photosmash.php in the plugin's main folder, but I cannot figure out where. Has anyone else come across this issue?
|
There is no need to juggle <code> $wp_query </code> object, store it in temp, etc. It is rarely good idea to directly mess with important global variables, unless you absolutely need to. You can just create your own arbitrary variable and init it with new <code> WP_query </code> <code> $some_variable = new WP_Query($args); </code> and so on. Also don't forget to cleanup after with <code> wp_reset_query() </code> .
|
Why doesn't PhotoSmash plugin play well with wp_query?
|
wordpress
|
I have Win7 32-bit Professional and I want to start learning to program and skin WordPress. My hosts will likely be LAMP, so I was going to run Win versions of those tools locally. Should I just get a linux VM, or will I be able to transfer what I do from the Win environment to the *nix hosting?
|
I'd recommend setting up XAMPP . It will allow you to run an Apache/PHP/MySQL environment on Windows. You shouldn't have any problem moving things over from your local XAMPP setup to a LAMP setup with your host.
|
Win7 Dev Environment
|
wordpress
|
I have a self-hosted Wordpress Blog (located at http://www.dougmolineux.com/wp if you're interesed :) I put a lot of Code Snippets on there, because I'm a programmer. How do I make these "snippets" code friendly? Right now, I am using a simple Blockquote around each one and it converts all single and double apostrophes into strange symbols that will not work when the code is actually copied and pasted. I am willing to convert to a new theme, or alter an existing one. Thanks!
|
Geshi In general the Geshi library is a popular library for formatting code ( http://qbnz.com/highlighter/ ) Geshi as a WordPress plugin For WordPress several authors "packaged" Geshi in a plugin. take your pick: http://wordpress.org/extend/plugins/search.php?q=geshi The one I use Personally I use this plugin: http://wordpress.org/extend/plugins/codecolorer/ . This one works by enclosing all pieces of codes with a [cc lang="bla"] code [/cc] tag where you can specify things like language, width, line numbering, etc… Example
|
Code Friendly Block Quotes
|
wordpress
|
I'm trying to add a new tab to my groups on BuddyPress. All the groups will have different content preferrably from the database. How can I accomplish this?
|
There's an example of this on the buddypress forums which is a good place to start looking for answers. http://buddypress.org/community/groups/creating-extending/forum/topic/can-someone-explain-how-to-add-tabs-to-the-profile-page/ For the sake of answering here though here goes: <code> bp_core_new_subnav_item( array( 'name' => 'My Group Page', 'slug' => 'my-group-page', 'parent_url' => $bp->loggedin_user->domain . $bp->groups->slug . '/', 'parent_slug' => $bp->groups->slug, 'screen_function' => 'my_groups_page_function_to_show_screen', 'position' => 40 ) ); </code> And the screen function to render the page: <code> function my_groups_page_function_to_show_screen() { //add title and content here - last is to call the members plugin.php template add_action( 'bp_template_title', 'my_groups_page_function_to_show_screen_title' ); add_action( 'bp_template_content', 'my_groups_page_function_to_show_screen_content' ); bp_core_load_template( apply_filters( 'bp_core_template_plugin', 'members/single/plugins' ) ); } function my_groups_page_function_to_show_screen_title() { echo 'My Page Title'; } function my_groups_page_function_to_show_screen_content() { // page content goes here } </code>
|
BuddyPress: Adding a new tab in groups
|
wordpress
|
I have a custom taxonomy "Portfolio Categories", and a few these categories say "Cloth", "Shoes", ... When open some category page, i want the title to be like 'Site Name | Cloth', but with wp_title(), it becomes 'Site Name | Portfolio Categories | Cloth' How do i remove the "Portfolio Categories" from the title?
|
Hi @Edward: This is not a generic solution but will probably solve your needs. If you want to get rid of the <code> '| Portfolio Categories' </code> from your site's title just hook the <code> 'wp_title' </code> filter in your theme's <code> functions.php </code> file and remove that from the title string. Copy this code to the bottom of that file and modify as need be: <code> add_filter('wp_title','your_wp_title'); function your_wp_title($title) { $title = str_replace('| Portfolio Categories','',$title); return $title; } </code>
|
How to remove parent taxonomy name from the title generated by wp_title()?
|
wordpress
|
hey hii everyone, i have a function to fetch the videos from the rss feed of youtube, so that i can display selected videos to my blog for that i am using this youtube-search-feed url <code> http://gdata.youtube.com/feeds/base/videos?q=eminem&client=ytapi-youtube-search&v=2 </code> in the url, eminem is included, so it will display me videos of eminem, now my problem is, instead of eminem it should take my posts title name, so if i write this code <code> $rss = fetch_rss('http://gdata.youtube.com/feeds/base/videos?q='.the_title().'&client=ytapi-youtube-search&v=2'); </code> then its returning me with a false video here is my entire code <code> <?php $newvar = str_replace(' ', '', the_title()); include_once(ABSPATH . WPINC . '/rss.php'); $rss = fetch_rss('http://gdata.youtube.com/feeds/base/videos?q='.$newvar.'&client=ytapi-youtube-search&v=2'); $maxitems = 1; $items = array_slice($rss->items, 0, $maxitems); ?> </code> here i am using <code> $newvar </code> to strip the spaces in between of the title of the posts @rarst i change the code but now i am not getting the video here is the code <code> <?php $newvar = str_replace(' ', '', the_title()); include_once(ABSPATH . WPINC . '/feed.php'); $feed = fetch_feed('http://gdata.youtube.com/feeds/base/videos?q='.$newvar.'&client=ytapi-youtube-search&v=2'); $maxitems = 1; $items = array_slice($feed->items, 0, $maxitems); ?> </code>
|
Don't know if this is your only issue, but you're using <code> the_title() </code> to build your URI. This ECHOS the title, which is not what you want. Instead, you should be using get_the_title() . I'd also urlencode the title, as Jan suggested. Your best bet is to print out the YouTube URI after you build it, then try to hit it in a browser. If the results aren't right, the problem is with your URI.
|
feed url problem
|
wordpress
|
Is it possible to set configuration options such as DEBUG mode only for specific sub blogs in a wordpress multisite installation? If so, how?
|
Hi @Raj Sekharan: If I understand your question lets say you have three (3) subdomains on your multisite and you only want to debug the first? http://foo.example.com http://bar.example.com http://baz.example.com If yes then it's a simply matter of adding the following to your <code> /wp-config.php </code> file: <code> if ($_SERVER['HTTP_HOST']=='foo.example.com') define('WP_DEBUG', true); else define('WP_DEBUG', false); </code> Or if you are a fan of terse coding you can just do it like this: <code> define('WP_DEBUG', $_SERVER['HTTP_HOST']=='foo.example.com'); </code>
|
How to set configuration options for particular sub blogs?
|
wordpress
|
I'd like this function to only return on certain pages. How might i do that? <code> // Retreats Accordion function retreats_accordion() { ?> <!-- accordion root --> <div id="accordion"> <?php global $post; $c = 0; $class = ''; $args = array( 'posts_per_page' => 6, 'post_type'=> 'slide', 'slideshow'=> 'retreats'); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); $c++; if( $c == 6 ) $class .= ' last'; ?> <a href="<?php echo get_post_meta($post->ID, "slide_url_value", true); ?>"> <?php the_post_thumbnail('quickfinder'); ?> </a> <div class="slide<?php echo $class;?>" style="width:200px;"> <h4><?php the_title(); ?></h4> <?php the_content(); ?> </div> <?php endforeach; ?> </div> <script> $(function() { $("#accordion").tabs("#accordion div", { tabs: 'img', effect: 'horizontal' }); }); </script> <?php } add_action('nktframework_abovecontent', 'retreats_accordion', 10); </code> I've tried adding this to the function but it doesn't seem to work. <code> if( is_page(107) ) return; </code>
|
Your code: <code> if( is_page(107) ) return; </code> checks for page and returns nothing on match, effectively it's exactly opposite of what you want. So if you reverse it and put this at start of function: <code> if( !is_page(107) ) return; </code> It will do nothing everywhere, but page 107 where it will proceed to run rest of the function.
|
Return function only on certain pages
|
wordpress
|
I'm trying to determine how to retrieve custom values from wp_options when the values are stored in a single options array. For example, I've got the following data in wp_options for option_value where option_name = "my_category_fields_option". The i:n value represents the category id of the category that holds the custom "my_title" data] a:2:{i:10;a:1:{s:8:"my_title";s:48:"Iced Tea: A Great Choice for Cooling Refreshment";}i:20;a:1:{s:8:"my_title";s:30:"Black Tea is Good for the Soul";}} How would I retrieve the value for "my_title" (which should be "Hello World") when I'm viewing the category archive page for this category?
|
<code> $term_id = get_query_var('cat'); // the current category ID $my_fields = get_option('my_category_fields_option'); echo $my_fields[$term_id]['my_title']; // the title corresponding to the current category </code> (assuming you're talking about stackexchange-url ("Any examples of adding custom fields to the category editor?"))
|
How to retrieve a value via get_option when the option_value is stored in a multi-dimensional array?
|
wordpress
|
I have a custom post type ( <code> 'Model' </code> ) for a sports modelling agency, and it requires the model to enter sports they are competent at, and also rank their ability from 1 to 5. For example, given the information: <code> Model: Joe Soap. Football: 4. Archery: 2 </code> I would store this in the custom_post_type <code> 'model' </code> with the fields: <code> Model Name: Joe Soap. Sports: Football, Archery (taxonomy). Rank: 4, 2. </code> How do I associate <code> 4 </code> with <code> Football </code> and <code> 2 </code> with <code> Archery </code> using a metabox, where different models may have different sports in their lists ?
|
Your question is focusing on the wrong thing. A metabox is just one way for a user to introduce some data. The more important question is how you should store that data in the database. You could make 'sport' a custom post type and connect it to models using the Posts 2 Posts plugin. Then, for each connection, you can associate a 'rank' custom field: https://github.com/scribu/wp-posts-to-posts/wiki/Connection-information The plugin takes care of creating a metabox and of storing the values in an efficient manner.
|
Is it possible to create relational metabox values in a custom post?
|
wordpress
|
I have a theme which includes some setup, using <code> after_setup_theme </code> but I'd like to write my own functions which also need to run <code> after_setup_theme </code> . I'd prefer to keep my stuff in a separate file. Can I call <code> after_setup_theme </code> multiple times?
|
WordPress hooks work like Hollywood: you don't call them, they call you. But unlike Hollywood, they keep calling everyone on the list. It's normal for an action or a filter to have multiple functions hooked to it, from different plugins, or even just different functions in the WordPress core that all do something specific. It is not only possible, but even good practice, as it means your code gets clearer (each function does only one thing) and it's easier to disable one specific piece of functionality by unhooking it. Remember that you can also play with the priorities of hooks: if you want to run both <code> functionA() </code> and <code> functionB() </code> in the <code> after_setup_theme </code> , but <code> functionA() </code> must run before <code> functionB() </code> , you can hook <code> functionA() </code> with the default priority <code> 10 </code> and <code> functionB() </code> with priority <code> 20 </code> (or any other number above 10). What won't work is hooking another function to an action while that action is executing . So you can't hook <code> functionB() </code> to <code> after_setup_theme </code> from <code> functionA() </code> , called on <code> after_setup_theme </code> . You could call it directly, but you would lose the benefit of separate hooks.
|
How many times can I hook into the same action?
|
wordpress
|
I recently asked a stackexchange-url ("question") the other day and got what I was looking for. Today I put that knowledge to practice, but I can't seem to figure how to remove the title and editor fields from the "edit" page. Below shows the arguments I'm using with <code> register_post_type </code> . Logically, I think providing an empty array for "supports" would make it not support anything by default. Am I missing something? <code> $v_args = array( 'labels' => array ( 'name' => 'Visitors', 'singular_name' => 'Visitor', 'add_new_item' => 'Register New Visitor', ), 'public' => true, 'publicly_queryable' => false, 'exclude_from_search' => true, 'show_ui' => true, 'hiearchical' => false, 'supports' => array( ), ); </code> Thanks, -Zack
|
You were close .) This works: <code> 'supports' => array( '' ), </code>
|
Custom post types - remove default post supports through empty array?
|
wordpress
|
Does anyone know of (or have) any scripts / processes they use for testing performance under load - especially of WordPress specific behaviours, like posting many comments nearly simultaneously, while under heavy simulated traffic. I typically use apachebench to test general performance (and to make sure caching is working), but I can't see a way of testing comment and posting performance without scripting it myself. Any ideas?
|
Just thought I'd throw in something I've been thinking about myself as a way of doing this: apachebench to simulate general viewing traffic a bit of PHP to add n comments per minute using WordPress (ie not directly inserting into the table). I'm also wondering if watir or selenium can't be put into action here instead. munin (or similar) to do monitoring / reporting (although I'm not sure how granular this would be)
|
Load testing for WordPress functionality
|
wordpress
|
A site I've built gets lots of comments in a short space of time - so perhaps 100 comments might be left in 5 or 10 minutes. This seems to cause a pretty heavy load on the database, especially when combined with recent comment widgets - I've seen server load rapidly spiral up to 40+, and using mtop I can see plenty of blocked queries. So, I'm using MyISAM as the storage engine, which locks the entire table for writing. Would switching to InnoDB which (I believe) uses row locking improve things? Looking at the MySQL docs, it seems perfectly possible to use both engines within the same database. So, the question: Does switching to InnoDB seem like it's a reasonable solution for what i described? Any WP specific experiences / benchmarks?
|
MyISAM locks the whole page for writes and is not ACID compliant, while InnoDB sticks to locking rows as you point out, and is ACID compliant. This makes it sturdier when you've a lot of writes, as in faster and less prone to data corruption. It's slower for reads in my experience, though it handles concurrent connections better. It also clutters the catalog. (I had a large DB one day which I switched to InnoDB from MyISAM, and the catalog ballooned by 2GB, or the size of my DB, for reasons I never understood, though I'm suspecting it had to do with temporary data such as index creation and the like, which didn't get flushed properly.) Anyway... With your current load, InnoDB is an option, as is memcached alongside an object cache.
|
Would switching to InnoDB from MyISAM improve performance of comments table?
|
wordpress
|
If you were to build a StackExchange clone site using WordPress, how would you do it?
|
Using WordPress as a CMS (content management system), this would be relatively straight-forward. Just remember, straight-forward does not mean "easy" ... Custom Post Types One of the newest and best features of WordPress is custom post types. Rather than using a traditional post or page, I would make two kinds of custom post types - one for questions and one for answers. Obviously the question will have titles, tags, and content. The answers will just have content. I'd also add a custom meta value to each answer to tie it to a specific question. Both questions and answers can have comments, which works well with the existing framework Voting There are several different voting plug-ins available, though none really handles the meritocracy system that SO has built up. Still, any plug-in that allows you to rate a question/answer will be a good place to start. With some minor tweaking you could get it working like the up/down voting system of SO. Meritocracy Each user account would have to have a custom field associated with the user's reputation. This would be modified directly by the up/down vote plug-in. Other features The rest of the UI would be entirely up to you - it could either mirror SO completely or take on its own format. Really, once you have questions and answers presented and persisted in the database correctly, the sky's the limit.
|
StackExchange clone using WordPress?
|
wordpress
|
I'd like to add code to my functions.php to intercept all calls to wp_list_categories() AND the_category() so that it excludes "uncategorized" and any children of "uncategorized" (OR cat_id 1). I'd also like to limit the number of words returned in the "title" attribute of each list item anchor. Currently the default is to set $cat_args['use_desc_for_title'] = 1; but It does not appear it's possible to insert that into the exclusions filter below. I'm using the code below which effectively removes the unwanted categories from the lists that use wp_list_categories, however, it does not remove them from lists derived from the_category... <code> function my_list_terms_exclusions($exclusions,$args) { $children = implode(',',get_term_children(1,'category')); $children = (empty($children) ? '' : ",$children"); return $exclusions . " AND (t.term_id NOT IN (1{$children}))"; } add_filter('list_terms_exclusions', 'my_list_terms_exclusions', 10, 2);?> </code>
|
I was finally able to figure this one out... Although I have to set the filter directly on the widget_categories_args method, so it does take two filter statements to do it. <code> function my_categories_filter($cat_args){ $cat_args['title_li'] = ''; $cat_args['exclude_tree'] = 1; $cat_args['exclude'] = 1; $cat_args['use_desc_for_title'] = 0; return $cat_args; } add_filter('widget_categories_args', 'my_categories_filter', 10, 2); </code>
|
filter out "uncategorized" from all category listings with one filter in functions.php?
|
wordpress
|
Can somebody tell me why this isn't working? I'm trying to get it to create a file in the plugins directory. After I get this working, I'll be trying to get this to create a file in the active theme's directory. Can somebody help me out here? EDIT I've changed my code, right now it creates the file but it does not input the text 'Testing' into the file even. Is there something I'm missing here? <code> $filename = __FILE__; register_activation_hook($filename, 'superActivation'); register_deactivation_hook($filename, 'superDeactivation'); global $myFile, $fh, $stringData, $filename, $pluginbase, $full_plugindir; $myFile = "../wp-content/themes/striking/testFile.php"; $stringData = "Testing\n"; $fh = fopen($myFile, 'w') or die("can't open file"); function superActivation() { global $myFile; global $fh; global $stringData; global $filename; fwrite($fh, 'test'); fclose($fh); } function superDeactivation() { global $myFile; if(is_file("$myFile")) { unlink("$myFile"); } } </code>
|
For unlinking, try: <code> function superDeactivation() { $myFile = "testFile.txt"; if(is_file("$myFile")) { unlink("$myFile"); } } </code> Or alternatively: <code> function superDeactivation() { $myFile = "testFile.txt"; unset($myFile); unlink("$myFile"); } </code>
|
Why is my plugins activation hook not working?
|
wordpress
|
Seems like a trivial problem but I can't get it to work. I need to add <code> class="last" </code> to every third post. Here is my code: <code> <?php $count = 0; $my_query = new WP_Query('cat=-18,-7&showposts=9'); while ($my_query->have_posts()) : $my_query->the_post(); ?> <article class="<?php if ($count % 3 == 0) { echo "last "; }" ?>> </article> <?php $count++; endwhile; ?> </code>
|
I think you just need to start the <code> $count </code> variable from 1 and not zero. You'll get the opposite effect otherwise because 0 modulo 3 is 0. The first item of every 3 will be getting the class name.
|
Grid layout "last" class to every third item
|
wordpress
|
I'm using the TinyMCE Advanced plugin so that I can add my own custom styles to the Style dropdown in the Visual Editor. However, I don't want some of the styles that are included in the style.css file to be listed there, as they are 'internal' classes (for aligning pictures etc). Is there a way to stop these classes being shown in the dropdown? Either by changing the TinyMCE Advanced configuration, or by editing the CSS file in a certain way?
|
This should be what you're looking for - put this code into your theme's <code> functions.php </code> file: <code> add_filter( 'tiny_mce_before_init', 'yourprefix_tiny_mce_before_init' ); function yourprefix_tiny_mce_before_init( $init_array ) { // filter styles: $init_array['theme_advanced_styles'] = "your_style=your_class"; // filter formats: $init_array['theme_advanced_blockformats'] = "p,h3,h4,h5"; return $init_array; } </code> This way the only style that will be displayed is <code> your_style </code> . The 3rd line is taking care of tinymce formats - might be useful too. See Plugin_API/Filter_Reference/tiny_mce_before_init for more informations and examples.
|
Stop certain classes showing up in TinyMCE Advanced Style dropdown
|
wordpress
|
I'm trying to figure out the best approach to add additional functionality that will only be utilized by admins via /wp-admin. What's the best way to implement so that resources aren't being wasted. I.E. if statement each page load or any other code execution on each page load for areas not even pertaining to the dashboard. Thanks.
|
There is number of dynamic hooks in admin-header.php that allows to precisely target on which pages to load your code. And naturally <code> current_user_can() </code> check so it only runs for admins.
|
What is the most efficient way of adding additional functionaliy for admin only
|
wordpress
|
Is there any way I can take a URL of an image and find the attachment or post id of that image in the database? Here is the situation: I'm in a loop going over all the 'img' tags that are surrounded by 'a' tags in my post content. if the src attribute of the 'img' tag does not match the href attribute of the outer 'a' tag, then i want to replace the 'img' tag. In doing this, if the 'img' that is to be removed is in the gallery, i want to delete that post, and then put my replacement 'img' in its place. I tried using a function like this: <code> function find_image_post_id($url) { global $wpdb; $postid = $wpdb->get_var($wpdb->prepare("SELECT DISTINCT ID FROM $wpdb->posts WHERE guid='$url'")); if ($postid) { return $postid; } return false; } </code> This apparently is not right because the guid is ironically not globally unique. I had (earlier in the same script) uploaded a file with the same name (why? because it was higher resolution and i am trying to replace low resolution versions of the same image) and although wordpress will save the image with a different name in the directory, the guid's were set to be the same. (possibly a bug). Is there another technique I can use?
|
Massively improved function developed for plugin heavy on images: <code> if ( ! function_exists( 'get_attachment_id' ) ) { /** * Get the Attachment ID for a given image URL. * * @link stackexchange-url * * @param string $url * * @return boolean|integer */ function get_attachment_id( $url ) { $dir = wp_upload_dir(); // baseurl never has a trailing slash if ( false === strpos( $url, $dir['baseurl'] . '/' ) ) { // URL points to a place outside of upload directory return false; } $file = basename( $url ); $query = array( 'post_type' => 'attachment', 'fields' => 'ids', 'meta_query' => array( array( 'value' => $file, 'compare' => 'LIKE', ), ) ); $query['meta_query'][0]['key'] = '_wp_attached_file'; // query attachments $ids = get_posts( $query ); if ( ! empty( $ids ) ) { foreach ( $ids as $id ) { // first entry of returned array is the URL if ( $url === array_shift( wp_get_attachment_image_src( $id, 'full' ) ) ) return $id; } } $query['meta_query'][0]['key'] = '_wp_attachment_metadata'; // query attachments again $ids = get_posts( $query ); if ( empty( $ids) ) return false; foreach ( $ids as $id ) { $meta = wp_get_attachment_metadata( $id ); foreach ( $meta['sizes'] as $size => $values ) { if ( $values['file'] === $file && $url === array_shift( wp_get_attachment_image_src( $id, $size ) ) ) return $id; } } return false; } } </code>
|
Turn a URL into an Attachment / Post ID
|
wordpress
|
i have been working on a custom system for my site where users can have a seperate account, setting and profile page to make my site a bit more interactive and community type. with some other additional stuff. I am new to coding, i have managed to make the profile pages etc. Right now i am stuck in adding a check box list of tags to user settings page. where a user can select multiple tags as interest.. so i can use those to show him recommended posts randomly on his account page . i was able to add two extra fields (Twitter/facebook) in the settings page with this code : <code> function add_bkmrks_contactmethod( $bcontactmethods ) { $bcontactmethods['Twitter'] = 'Twitter'; $bcontactmethods['Facebook'] = 'Facebook'; return $bcontactmethods; } add_filter('user_contactmethods','add_bkmrks_contactmethod',10,1); </code> and tehse can be easily called on pages as well by using <code> $userinfo->Twitter </code> etc. but i have no clue about the checkboxlist... and calling the array etc. If you guys came across any article or chunk of code which can help me get this resolved i wil be thankful :) cheers Ayaz
|
Justin Tadlock has a good tutorial to get you started: http://justintadlock.com/archives/2009/09/10/adding-and-using-custom-user-profile-fields There are some specifics to dealing with checkboxes however, and some custom code if you want to make checkboxes that correspond to tags/categories. To generate the form fields and save the data use the following snippet: <code> <?php function user_interests_fields( $user ) { // get product categories $tags = get_terms('post_tag', array('hide_empty' => false)); $user_tags = get_the_author_meta( 'user_interests', $user->ID ); ?> <table class="form-table"> <tr> <th>My interests:</th> <td> <?php if ( count( $tags ) ) { foreach( $tags as $tag ) { ?> <p><label for="user_interests_<?php echo esc_attr( $tag->slug); ?>"> <input id="user_interests_<?php echo esc_attr( $tag->slug); ?>" name="user_interests[<?php echo esc_attr( $tag->term_id ); ?>]" type="checkbox" value="<?php echo esc_attr( $tag->term_id ); ?>" <?php if ( in_array( $tag->term_id, $user_tags ) ) echo ' checked="checked"'; ?> /> <?php echo esc_html($tag->name); ?> </label></p><?php } } ?> </td> </tr> </table> <?php } add_action( 'show_user_profile', 'user_interests_fields' ); add_action( 'edit_user_profile', 'user_interests_fields' ); // store interests function user_interests_fields_save( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; update_user_meta( $user_id, 'user_interests', $_POST['user_interests'] ); } add_action( 'personal_options_update', 'user_interests_fields_save' ); add_action( 'edit_user_profile_update', 'user_interests_fields_save' ); ?> </code> You can then call the <code> get_the_author_meta() </code> function to get at your array of tag IDs which can then be used in a query eg: <code> query_posts( array( 'tag_id' => get_the_author_meta( 'user_interests', $user_id ) ) ); </code>
|
How to add/save Custom Field in user settings/profile "Checkbox list"
|
wordpress
|
I'm having a small issue with the custom post type entry screen. I'd like to bump up my metabox right under the content box, but I'm not sure if that's even possible (as the metaboxes in between are "defaults", i.e.; Excerpt, Discussion & Author). I'm applying the standard code: <code> function ctp_admin(){ add_meta_box('cpt_meta', 'Meta Box', 'cpt_meta', 'cpt_function', 'normal', 'high'); } </code> Thank you! Noel
|
Where you have the parameter 'normal' eg. the context parameter change that to read 'core'. <code> add_meta_box('cpt_meta', 'Meta Box', 'cpt_meta', 'cpt_function', 'core', 'high'); </code> The default meta boxes are registered as core and are listed first, followed by the 'normal' context. The docs don't actually say you can do it but I have done without any problems. EDIT: Make sure your function is registered on the 'add_meta_boxes' hook with a high priority eg: <code> function my_metabox() { ... } add_action( 'add_meta_boxes', 'my_metabox', 1 ); // priority 1 </code> The use of 'core' vs. 'normal' may not actually make a difference in the latest version.
|
Priority of Meta Box for Custom Post Type
|
wordpress
|
I’m still getting my head around buddypress, so far so good but I’ve hit a snag where I want certain users who are flagged as an ‘expert’ to automatically accept any friend requests people make. I’ve found a couple of functions related to this but I think I’m missing something that would make this simpler such as setting a constant or overriding part of the $bp global… What I have so far is the following: <code> function bp_auto_accept_friend_request( $friendship_id, $friendship_initiator_id, $friendship_friend_id ) { if ( is_user_expert( $friendship_friend_id ) ) { // force add friends_accept_friendship( $friendship_id ); friends_add_friend( $friendship_initiator_id, $friendship_friend_id, true ); } } add_action('friends_friendship_requested', 'bp_auto_accept_friend_request', 200, 3); </code> Can anyone tell me where I should be looking to make this nice and seamless just as if the main settings were set to bypass the request process please?
|
UPDATE try this <code> function bp_auto_accept_friend_request( $friendship_id, $friendship_initiator_id, $friendship_friend_id ) { $friendship_status = BP_Friends_Friendship::check_is_friend( $friendship_initiator_id, $friendship_friend_id ); if ( 'not_friends' == $friendship_status ) { if ( is_user_expert( $friendship_friend_id ) ) { // force add friends_add_friend( $friendship_initiator_id, $friendship_friend_id, true ); friends_accept_friendship( $friendship_id ); } } } add_action('friends_friendship_requested', 'bp_auto_accept_friend_request', 200, 3); </code> this way we only call friends_add_friend function with $force = true if they are not friends yet.
|
How to auto-accept a friend-request in buddypress based on user meta
|
wordpress
|
This question got me thinking stackexchange-url ("Transient RSS feeds in wp_options not removed automatically?") Transients are supposed to expire and be deleted. However the only way I see this handled is when transient is expired and requested, then it is deleted during request. What if transient is expired but never requested after that? From description in Codex I thought that some kind of garbage collection is implied. Now I am not so sure and can't find any code that performs such. So will it just be stuck in database forever?
|
They now are Starting with WordPress 3.7 expired transients are deleted on database upgrades, see #20316 Old answer If someone can't show me otherwise it seems that transients are not garbage collected after all. What makes it worse is that unlike options they are not guaranteed to be stored in database. So there is no reliable way to fetch list of all transients to check them for expiration. Some makeshift code to do garbage collection if database is used for storage: <code> add_action( 'wp_scheduled_delete', 'delete_expired_db_transients' ); function delete_expired_db_transients() { global $wpdb, $_wp_using_ext_object_cache; if( $_wp_using_ext_object_cache ) return; $time = isset ( $_SERVER['REQUEST_TIME'] ) ? (int)$_SERVER['REQUEST_TIME'] : time() ; $expired = $wpdb->get_col( "SELECT option_name FROM {$wpdb->options} WHERE option_name LIKE '_transient_timeout%' AND option_value < {$time};" ); foreach( $expired as $transient ) { $key = str_replace('_transient_timeout_', '', $transient); delete_transient($key); } } </code>
|
Are transients garbage collected?
|
wordpress
|
Is it possible to fetch videos and images of a particular website and put it into post? i mean i am thinking of writing a function, where i will just write the website name, and then with the help of website url, all or latest images and videos are posted to my post. Is this possible?
|
The problem with this is that each sites content is formated differently. If there was only one site you were wanting to pull from you maybe able to use curl() and then sort though the content. A better idea may be to grab content from the sites RSS feed and sort though and grab what you need. You could probably write a quick plugin that would either grab the feedurl of the site and display images or you enter the feed url and it displays content. This is also just a friendly reminder about copyright and being mindful of the content you're pulling ;)
|
fetch images and videos
|
wordpress
|
I just wrote a little plugin that detects if the user is on a mobile browser and if so detects them away from the WordPress site to a mobile (simple) version of part of the site. As I got to thinking I'm redirecting user who may want to see the full site. I can easily add a check by creating a URL such as <code> http://example.org?force_web=true </code> The only problem is my plugin checks the top of each page to see if it's mobile so I would need to set <code> force_web=true </code> on all pages. The other idea would be to use sessions but it seems WordPress doesn't support sessions unless you add <code> session_start(); </code> to your <code> wp_config.php </code> file which I don't want to ask the plugin users to do. Is this something others have experienced? Is the best way to re-write all permalinks with the addition of my variable? Open to ideas and suggestions
|
As Ambitious Amoeba said, just do the check on each page load; it shouldn't be that expensive. Otherwise, another possibility to store a single bit of information would be to use browser cookies.
|
Append varible to url or set session
|
wordpress
|
I want to add a custom button to the tinyMCE toolbar in the 'Add New Post' screen which when clicked, will insert text into the new post. I have tried using this code (from http://tinymce.moxiecode.com/tryit/custom_toolbar_button.php ): <code> wp_admin_css('thickbox'); wp_print_scripts('jquery-ui-core'); wp_print_scripts('jquery-ui-tabs'); wp_print_scripts('post'); wp_print_scripts('editor'); add_thickbox(); wp_print_scripts('media-upload'); setup : function(ed) { // Add a custom button ed.addButton('mybutton', { title : 'My button', image : 'img/example.gif', onclick : function() { // Add you own code to execute something on click ed.focus(); ed.selection.setContent('Hello world!'); } }); } </code> but it fails to compile. It error's at the line with ' setup : function(ed) ' Is it failing because I need to reference tinyMCE.js? I couldn't find that file under my WordPress installation on the server. is there a better way of creating the button?
|
Your problem i believe are the lines that follow the enqueues and print scripts, you're mixing Javascript with PHP.. Javascript goes inside the HTML section of a PHP file or inside an echo statement. This page of the codex gives an example for adding a button to TinyMCE inside WordPress. However that codex entry might be a bit dated, so in the event of problems with the code here are some alternative code samples to work from. http://brettterpstra.com/adding-a-tinymce-button/ stackexchange-url ("stackexchange-url RE: Code problems Inside a PHP file, HTML goes between the ending and starting PHP blocks, like so.. <code> ?> <div>example</div> <?php </code> Or alternatively inside an echo statement. <code> echo '<div>example</div>'; </code> Javascript should be treated in the same manner as HTML, so you above code(the JS part) should look either like this.. <code> ?> <script type="text/javascript"> setup : function(ed) { // Add a custom button ed.addButton('mybutton', { title : 'My button', image : 'img/example.gif', onclick : function() { // Add you own code to execute something on click ed.focus(); ed.selection.setContent('Hello world!'); } }); </script> <?php </code> Or.. <code> echo " <script type=\"text/javascript\"> setup : function(ed) { // Add a custom button ed.addButton('mybutton', { title : 'My button', image : 'img/example.gif', onclick : function() { // Add you own code to execute something on click ed.focus(); ed.selection.setContent('Hello world!'); } }); </script> "; </code> The former being the easier approach in my opinion. I hope that answers your question, and if you need help understanding something let me know..
|
How to add a custom button to the tinyMCE toolbar?
|
wordpress
|
I have created a form within a Meta Box on the 'Add New Page' screen. I want the data from this form to be sent to an OData service on a central server. I can see that OData is supported on PHP ( http://odataphp.codeplex.com/ ) but it requires the OData for PHP SDK to be installed on the server. Because the server could be Windows/UNIX/LINUX/other I don't know if I can create a generic installation file to make it transparent for the user to install my plugin. What would be the best method of doing this?
|
So basically what you're asking is how to create a php-based installer for the OData SDK, right? Or how to somehow package it with your plugin? First I thought you could just include the whole framework in your plugin folder, and include it directly from there. But it turns out (from reading the install docs) that installation of the SDK requires some actual changes to the php ini outside of just adding the include path, and the SDK itself has several dependencies (php-xml, php-xsml, curl modules). In short, I don't think you can do this effectively with a php-based installer. And I don't know of any WordPress-specific bundling techniques that help. My best advice is: find another way to do the remote logging that doesn't rely on OData. For example, build a simple REST service on your centralized server that can be hit using wp_http. If you NEED to use OData for some reason, simply make it a prerequisite for your plugin. Find a way to test for its existence, and spit out a warning that says "you need the OData SDK" if it isn't installed. If none of that helps, try contacting folks who work on the OData SDK ( http://odataphp.codeplex.com/team/view ). Distributing this software isn't really an issue that's specific to WordPress... they may have better general advice for making a portable php-based installer.
|
How to send form data from WordPress (Meta Box) to an OData service?
|
wordpress
|
i try to build a form that users posts from frontend, everything works fine but i need to know if it's possible, if i play with the <code> 'post_date' => date('Y-m-d H:i:s') </code> ? if i add a hidden field that generates the expiration day (+30 days from the post day) and then add it to the post with <code> add_post_meta($post_id, 'expiration', $expDate, true); </code> anyone have any ideas how i can build something like this? thanks a lot, Philip
|
The post by itself is only data, it cannot perform such action as expiring itself. So you need some form of external control to act on it. You can use WP Cron (see <code> wp_schedule_event() </code> and related) to run periodic task that will query for posts by your custom field and perform wanted action on them (trashing, cancelling published status, etc).
|
Set Expiration Date of a Post from the Frontend with wp_insert_post
|
wordpress
|
I have to set up a small website, it's a porfolio for a design company with just the standard sections: home, about us, services, portfolio and contact. That's it, no blog, no dynamic sections, no big deal. I thought I could do it using WordPress, but I think it maybe an overkill. On the one hand, WP maybe useful for a couple of interesting plugins that could save me some time, like sitemap generator and better SEO results, and also for in-browser editing of the posts. But on the other hand, it's harder to do the things "the wordpress way", like using wp_enqueue_script to load the scripts and things like that. Also, sections are not like posts, each one is different, not to mention the homepage, so the "generality" that WordPress could bring me is somehow useless. What do you think?
|
I don't think it's overkill. IMHO even a small site can benefit from running WordPress. World wide web is a very dynamic environment and your site should stick to this flow. You can keep your site up to date when it comes to terms of usability, security and other standarts just by keeping your WordPress core updated. I'd expect no troubles with speed/performance with such a small project. And of course it is very scalable for any future client needs like Wyck has mentioned. home, about us, services, portfolio and contact ... no dynamic sections In my experience often portfolio is a dynamic type of content. Your use case can be different of course. One more thing: time spent learning how to make WP fit your needs is an investment that will come back to you ( probably during your next project :)
|
Using wordpress for a four-page website may be an overkill?
|
wordpress
|
I'd like to decrease the default RSS cache time for a widget plugin i've made that outputs RSS feeds. I'm no php expert, I just copy and paste and understand little bits. I'm using this code to output the RSS <code> function widget($args, $instance) { // outputs the content of the widget extract( $args ); $title = apply_filters('widget_title', $instance['title']); $tip_language = apply_filters('widget_title', $instance['tip_language']); echo $before_widget; echo "<h3 class=\"widgettitle\">" . $title . "</h3>"; include_once(ABSPATH . WPINC . '/rss.php'); $rss_feed = "http://mysite.org/feed"; $rss = fetch_rss($rss_feed); $rss->items = array_slice($rss->items, 0, 1); $channel = $rss->channel; foreach ($rss->items as $item ) { $parsed_url = parse_url(wp_filter_kses($item['link'])); echo wptexturize($item['description']); echo "<p><a href=" . wp_filter_kses($item['link']) . ">" . wptexturize(wp_specialchars($item['author'])) . "</a></p>"; } echo $before_after; } </code>
|
Why not just use native RSS widget? Also while Chris_O is absolutely right on filter to use, it is better practice to change cache time for specific feed URL rather than globally: <code> add_filter( 'wp_feed_cache_transient_lifetime', 'speed_up_feed', 10, 2 ); function speed_up_feed( $interval, $url ) { if( 'http://mysite.org/feed' == $url ) return 3600; return $interval; } </code>
|
Decrease RSS cache time in plugin?
|
wordpress
|
I'm in archive.php and attempting to write out the current category's description with full html. However, category_description() prints without the html markup. How can I force it to retrieve the full description complete with the html tags?
|
Found the answer here > http://www.laptoptips.ca/projects/category-description-editor/ <code> echo get_term_field( 'description', get_query_var( 'cat' ), 'category', 'raw' ); </code>
|
How to echo category_description() without stripping out html tags?
|
wordpress
|
My category descriptions consist of whole pages of content. When I view the manage categories screen, the grid does not truncate the text but rather, shows all of it. I realize I could turn off the description field in "screen options", however, I'd like to be able to truncate the amount of text that shows up there. How can I execute a filter that limits the amount of text used in this description field?
|
That field is not filtered in template. One way would be to filter <code> get_terms() </code> on that page (but I am not entirely sure that won't break something): <code> add_action( 'admin_head-edit-tags.php', 'admin_edit_tags' ); function admin_edit_tags() { add_filter( 'get_terms', 'admin_trim_category_description', 10, 2 ); } function admin_trim_category_description( $terms, $taxonomies ) { if( 'category' != $taxonomies[0] ) return $terms; foreach( $terms as $key=>$term ) $terms[$key]->description = substr( $term->description, 0, 50 ); return $terms; } </code>
|
How can I limit the amount of characters used for description in the manage categories grid?
|
wordpress
|
I am completely noob with WordPress so I apologize in advance if my questions sounds completely stupid. Background I have a small business catalog site that I wrote long ago in plain HTML. Now I want to add some SEO and improve the design therefore I am looking to use a CMS for easy content management. Questions Is WordPress a right choice for my requirements? Is it only for blogging or can be used for any kind of site? (corporate, portfolio, catalog, personal info etc.) Will I need some kind of plugins for SEO and displaying product catalog? How can I remove the blog look (posts/dates/comments etc.) from the site? Any hints/links/insights will be much appreciated.
|
Is WordPress a right choice for my requirements? Is it only for blogging or can be used for any kind of site? (corporate, portfolio, catalog, personal info etc.) WordPress can absolutely be used for any kind of site. But note that while things like post and pages are ready out of the box and simple to use, it takes some additional development if you want to implement your own types of content with more complex data ( Custom Post Types ). Will I need some kind of plugins for SEO and displaying product catalog? How can I remove the blog look (posts/dates/comments etc.) from the site? There is number of highly functional and free SEO plugins available. WordPress SEO by Yoast gets a lot of traction lately. Displaying content mostly depends on theme. There is an insane amount of themes available (starting with official repository and beyond), but as above - it may take some development if you need to implement something more complex.
|
WordPress for a business catalog site
|
wordpress
|
I couldn't seem to find a plugin with both functionality so I created mine(not a plugin) thru the help of my old friend google. My code works but there's a small glitch, the title of the posts are the same for all recent comments. <code> $comments = get_comments('status=approve&number=5'); ?> <ul> <?php foreach ($comments as $comment) { $post_obj = get_post($comment->post_id); $title = $post_obj->post_title; ?> <li><?php echo get_avatar( $comment, '42' ); echo strip_tags($comment->comment_author); ?>&nbsp;<?php echo wp_html_excerpt( $comment->comment_content, 35 ); ?><br /> <a href="<?php echo get_permalink($comment->post_id); ?>" rel="external nofollow" title="<?php echo $title; ?>"> <?php echo $title; ?> </a> </li> <?php } ?> </ul> </code> Any help would be appreciated. Thanks! UPDATE: Here's the current code. Edited according to Ambitious Amoeba. <code> $comments = get_comments('status=approve&number=5'); ?> <ul> <?php foreach ($comments as $comment) { ?> <li><?php $title = get_the_title($comment->post_ID); echo get_avatar( $comment, '42' ); echo strip_tags($comment->comment_author); ?>&nbsp;<?php echo wp_html_excerpt( $comment->comment_content, 35 ); ?> <br /><a href="<?php echo get_permalink($comment->post_ID); ?>" rel="external nofollow" title="<?php echo $title; ?>"> <?php echo $title; ?> </a> </li> <?php } ?> </code> Still getting the same result. All with the same title. Though it changes the post title according what is currently viewed.
|
Use <code> $comment->comment_post_ID </code> instead of <code> $comment->post_id </code> . Also you don't need get_post(...). Just use get_the_title instead of your <code> $post_obj </code> and related code...
|
Display recent comments with gravatar and excerpts?
|
wordpress
|
When writing out the category description in my theme (on archives and special category listings) for example, there are times I need the description in full html mode and others when I need it returned stripped of any html. In the code below, I actually need the stripped version of the description, however $category-> description returns the full description with all tags, which is rendering my strlen snippet function inoperable depending on where it breaks. How can I obtain an html stripped version of the description in the loop below? <code> foreach($categories as $category) { echo '<li style="clear:both;">'.get_category_thumbnail($category->term_id, 'thumbnail').'<a style="display:block;margin-top:20px;" href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'; if(strlen($category->description) > 300 ) echo SUBSTR( $category->description,0,STRPOS( $category->description,".",300)+1); else echo $category->description; </code>
|
Have you tried something like this? <code> strip_tags($category->description) </code> Here the reference page for the strip_tags function
|
How to obtain the html stripped version of $category-> description?
|
wordpress
|
I'm using this autocomplete script https://github.com/agarzola/jQueryAutocompletePlugin within my wordpress theme. I have a form in a page where the user could specify some tags. Actually, this is the code I'm using and it's working good. <code> <script> jQuery(function() { var data = '<?php global $wpdb; $search_tags = $wpdb-> get_results("SELECT name FROM $wpdb->terms"); foreach ($search_tags as $mytag){ echo $mytag->name. " "; } ?>'.split(" "); $("#tags").autocomplete(data,{multiple: true}); }); </script> </code> Now, the problem is, this kind of query puts all the tags inside an array when I load the page. This could work if you have 100 tags, but we have a lot more. The script has also an autocomplete from remote script option as shown below: <code> <script type="text/javascript"> jQuery().ready(function() { $("#tags").autocomplete("<?php bloginfo('template_url'); ?>/get-tags.php", { width: 260, matchContains: true, selectFirst: false, multiple: true }); }); </script> </code> This must activate autocomplete as the user types. This is the code for get-tags.php (I put the file in my theme root) <code> <?php include_once(‘../../../wp-config.php’); include_once(‘../../../wp-load.php’); include_once(‘../../../wp-includes/wp-db.php’); global $wpdb; $search_tags = $wpdb->get_results("SELECT name FROM $wpdb->terms"); foreach ($search_tags as $mytag) { echo $mytag->name. " "; } ?> </code> I have tried everything and searched online for hours but I didn't find a solution on how to call the get-tags.php, it gives me an internal 500 error and the autocomplete doesn't work anymore. thanks
|
don't include WP like that. use <code> $_GET </code> instead: <code> ... $("#tags").autocomplete("<?php echo add_query_arg('get_my', 'terms', home_url()); ?>", ... </code> theme's functions.php: <code> add_action('template_redirect', 'terms_for_autocomplete'); function terms_for_autocomplete(){ if(isset($_GET['get_my']) && $_GET['get_my'] == 'terms'): $terms = &get_terms(get_taxonomies()); foreach ($terms as $term) echo "{$term->name}|{$term->name} ({$term->count} results)\n"; die(); endif; } </code>
|
jQuery Autocomplete in Wordpress
|
wordpress
|
I want to use dd belatedpng so the PNG's on my website appear properly on IE. The script I've always used on non-wordpress websites was <code> <!--[if lt IE 7 ]> <script src="js/dd_belatedpng.js"></script> <script> DD_belatedPNG.fix('img, .ir'); </script> <![endif]--> </code> Now that I need to use it on a Wordpress website, I'm trying to find a way of adding script using enqueue script, although I don't like it at all. At the end of the day, the theme is only going to be used on a single website, I'd prefer to hardcode the scripts path. Anyway, is there a way of adding IE conditionals to enqueue script and or register script?
|
WordPress has a <code> $is_IE </code> global variable: <code> global $is_IE; if($is_IE) enqueue_script(...); </code> Personally I prefer the IE conditional comments. Other browsers ignore them anyway, so there's no reason to use PHP for browser detection. You might also want to consider using 8 bit alpha PNG images instead of 24 bit PNGs, which don't need any javascript fix in IE, and in most cases they will look the same as a 24 bit PNG.
|
Enqueue script only for IE
|
wordpress
|
Where should I put an administration page that should only be used once? I am creating a plugin that will index all used HTML tags in your posts, so you can cleanup posts if you change themes and want to replace old incorrect <code> <font> </code> tags with headers or other semantic markup. When you install this plugin it should scan your old posts once to fill up the index (custom taxonomy). I don't want to do this on plugin installation because it might take a long time if you have many posts, and thus a separate page with an AJAX-approach to transform batches of posts might be better. It's probably nitpicking, but should I put this extra page in the menu (under Tools ?) and just leave it there, or should a use a trick to only display it when needed? Via a link in the plugin actions, or maybe a DB setting that you can use to hide the menu item? The plugin should remain installed (because it updates on post inserts and edits), and maybe sometimes you want a rescan (if you did a bulk change via the database). As plugin users, does it bother you to have menu options that you almost never use?
|
Putting it under Tools seems reasonable to me. Hiding it after a certain action might cause confusion.
|
Where should I put "run once" plugin pages?
|
wordpress
|
I'm attempting to move some code from a plugin over to my theme's functions.php file, but when I attempt to wrap it in the is_single() wrapper inside of functions.php, it never fires. What am I missing? <code> if (is_single()) { echo "hello world"; } </code> I can't get the echo to fire from any inside post page. This has to be something insanely simple I'm overlooking.
|
All that I can think of is to verify that you are in fact on a single post page ( echo out an else conditional, make sure that you are actually hitting your block of code ). <code> if ( is_single() ) { echo 'Hello World, Is Single'; } else { echo 'Not Single'; } </code> Where exactly are you placing the code (Header, Body, Footer, which template file)? Are you using any frameworks like Carrington ?
|
is_single() works in plugin, not in theme?
|
wordpress
|
I am in the process of moving a site made up of asp pages to a completely redesigned Wordpress site. It has come time to create the 301 redirects for those old pages, so I don't break any links that are out there. I do have the redirection plugin installed as well. I've tried using it to do these types of redirects. I've also tried using htaccess, but everything I've tried results in getting this error. 404 - File or directory not found. The resource you are looking for might have been removed, had its name changed, or is temporarily unavailable. It's my guess that the server is trying to process the page before applying the redirect. I'm sure others have done this before, so any thoughts/ideas would be greatly appreciated. Thanks, Jeremy <code> My htaccess currently looks like this: FileETag None Header unset ETag Options +FollowSymLinks Redirect 301 /customers/default.asp http://twostep2.com/customers/testimonials <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / # BEGIN WordPress RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress </code>
|
In case anyone else stumbles upon this, the issue had to do with a setting in my provider. All of the comments above were correct on how to do redirects, but the problem was on the server side. I am using Rackspace cloud sites to host the wordpress site. In order to have ASP or ASPX pages redirect to PHP, you have to enable IIS on the apache server. they provide instructions here: http://cloudsites.rackspacecloud.com/index.php/How_do_I_enable_a_secondary_technology%3F You then have to have a web.config file to do the redirect from ASP to PHP. Jeremy
|
Moving an ASP Site to Wordpress - Looking for Help on Redirects
|
wordpress
|
Hi I am writing a small plug-in which I get some content from outside of WordPress and I want a small script to trigger whenever a new post, page or comment is added. Also if any Widgets, themes and Plug-ins are Activated or De-Activated. My guess is that I should be using the action hooks for this but since there are multiple actions so how to get all those actions in some array or so. <code> class getStatic { var $_renderTasksOn = array( <!-- How do I call those actions in an array here --> ) function gerStatic() { <!-- Here goes the script to get external data --> } } </code> I am very new to programming hence kindly help with the code. How do I use those action hooks? Kindly help.
|
If you want to hook into multiple actions, you have to call <code> add_action </code> multiple times. However, this is not so hard. Let's take your plugin class as an example: <code> class WPSE6526_getStatic // Always prefix your plugin with something unique, like your name. Here I used the question number { var $_renderTasksOn = array( 'wp_insert_post', 'wp_insert_comment', ... ); function WPSE6526_getStatic() { // The constructor of this class, which will hook up everything // This is the 'trick' to this question: a loop on your list and `add_action` for each item foreach ( $this->_renderTasksOn as $hookname ) { add_action( $hookname, array( &$this, 'getStatic' ) ); } } function getStatic() { // Your code } } add_action( 'plugins_loaded', 'wpse6526_getStatic_init' ); function wpse6526_getStatic_init() { $GLOBALS['wpse6526_getStatic_instance'] = new WPSE6526_getStatic(); } </code>
|
How to get multiple Action Hooks in an Array
|
wordpress
|
In the code below, rather than writing out the entire description field ($category-> description), how can I call the equivalent of the_excerpt? I'm placing the "more" tag after the first paragraph of the category description and using a visual editor to edit my category descriptions. <code> function show_category_index($content){ $categories=get_categories('exclude=1&exclude_tree=1'); echo $content; echo '<ul style="list-style-type:none;margin:0;padding:0">'; foreach($categories as $category) { echo '<li style="clear:both;">'.get_category_thumbnail($category->term_id, 'thumbnail').'<a style="display:block;margin-top:20px;" href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a>'; echo $category->description . '</li>'; } echo '</ul>'; } </code>
|
<code> wp_html_excerpt($category->description, 25) </code> . Or you can create your own function. I'm using this: <code> /** * Filters content based on specific parameters, and appends a "read more" link if needed. * Based on the "Advanced Excerpt" plugin by Bas van Doren - http://sparepencil.com/code/advanced-excerpt/ * * @since 1.0 * * @param string $content What to filter, defaults to get_the_content(); should be left empty if we're filtering post content * @param array $args Optional arguments (limit, allowed tags, enable/disable shortcodes, read more link) * @return string Filtered content */ function atom_filter_content($content = NULL, $args = array()){ $args = wp_parse_args($args, array( 'limit' => 40, 'allowed_tags' => array('a', 'abbr', 'acronym', 'address', 'b', 'big', 'blockquote', 'cite', 'code', 'dd', 'del', 'dfn', 'div', 'dl', 'dt', 'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'i', 'ins', 'li', 'ol', 'p', 'pre', 'q', 'small', 'span', 'strong', 'sub', 'sup', 'tt', 'ul'), 'shortcodes' => false, 'more' => '<a href="'.get_permalink().'" class="more-link">'.__('More &gt;').'</a>', )); extract(apply_filters('atom_content_filter_args', $args, $content), EXTR_SKIP); if(!isset($content)) $text = get_the_content(); else $text = $content; if(!$shortcodes) $text = strip_shortcodes($text); if(!isset($content)) $text = apply_filters('the_content', $text); // From the default wp_trim_excerpt(): // Some kind of precaution against malformed CDATA in RSS feeds I suppose $text = str_replace(']]>', ']]&gt;', $text); // Strip HTML if allow-all is not set if(!in_array('ALL', $allowed_tags)): if(count($allowed_tags) > 0) $tag_string = '<'.implode('><', $allowed_tags).'>'; else $tag_string = ''; $text = strip_tags($text, $tag_string); // @todo: find a way to use the function above (strip certain tags with the content between them) endif; // Skip if text is already within limit if($limit >= count(preg_split('/[\s]+/', strip_tags($text)))) return $text; // Split on whitespace and start counting (for real) $text_bits = preg_split('/([\s]+)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY); $in_tag = false; $n_words = 0; $text = ''; foreach($text_bits as $chunk): if(!$in_tag || strpos($chunk, '>') !== false) $in_tag = (strrpos($chunk, '>') < strrpos($chunk, '<')); // Whitespace outside tags is word separator if(!$in_tag && '' == trim($chunk)) $n_words++; if($n_words >= $limit && !$in_tag) break; $text .= $chunk; endforeach; $text = trim(force_balance_tags($text)); if($more): $more = " {$more}"; if(($pos = strpos($text, '</p>', strlen($text) - 7)) !== false): // Stay inside the last paragraph (if it's in the last 6 characters) $text = substr_replace($text, $more, $pos, 0); else: // If <p> is an allowed tag, wrap read more link for consistency with excerpt markup if(in_array('ALL', $allowed_tags) || in_array('p', $allowed_tags)) $more = "<p>{$more}</p>"; $text = $text.$more; endif; endif; return $text; } </code>
|
How can the_excerpt (or equivalent) be called on a category description?
|
wordpress
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.