question
stringlengths 0
34.8k
| answer
stringlengths 0
28.3k
| title
stringlengths 7
150
| forum_tag
stringclasses 12
values |
---|---|---|---|
I have been following goldenapples front end file uploads tutorial, however i do have that working for my frontend posting page, but what i am wanting to accomplish now is to add an image from edit profile page (again this is a frontend file upload scenario. In theme functions.php i have: <code> function insert_complogo($file_handler,$user_id,$setthumb='false') { // check to make sure its a successful upload if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false(); require_once(ABSPATH . "wp-admin" . '/includes/image.php'); require_once(ABSPATH . "wp-admin" . '/includes/file.php'); require_once(ABSPATH . "wp-admin" . '/includes/media.php'); $attach_id = media_handle_upload( $file_handler, $user_id ); if ($setthumb) update_usermeta($user_id,'_thumbnail_id',$attach_id); return $attach_id; } </code> In my profile-edit.php at the top i have: <code> if ($_FILES) { foreach ($_FILES as $file => $array) { $newupload = insert_complogo($file,$user_id); } } </code> also this: <code> if ( !empty( $_POST['authorphoto'] ) ) update_usermeta( $current_user->id, 'comp_logo', esc_attr($_POST['comp_logo'] ) ); </code> and my input type is: <code> <p> <label><?php _e('Add Company Logo', 'comp_logo') ?></label><br /> <input type="file" name="comp_logo" id="comp_logo" value="Upload Logo" size="50" /> </p> </code> As you can tell from the first three blocks of code above i have changed post_id references to user_id, Now the upload of the company logo does work, however even using user_id and update_usermeta the info is being saved into wp_postmeta table which is not where i want it to be as i need to pull the info from wp_usermeta to populate the author.php page. So my question (got there eventualy) is why when im using update_usermeta is the attachment info going into wp_postmeta, im guessing its because codex says that image attachments are a type of post so no matter what that is where they go, but how can i get that image from wp_postmeta and associate it with the correct author?
|
Actually got around it by making a plugin that can either shortcode a hook into a user edit page from frontend or by using a seperate shortcode in a sidebar. Below is the crux of it, just need to do some bits and bobs with the error reporting. <code> require(ABSPATH . WPINC . '/pluggable.php'); define('WP-AUTHOR-LOGO_VERSION', '0.3.0'); define('WP-AUTHOR-LOGO_PLUGIN_URL', plugin_dir_url( __FILE__ )); register_activation_hook(__FILE__, 'wpal_createfolder'); function wpal_createfolder() { $target = ABSPATH . 'wp-content/uploads/wpal_logos'; wp_mkdir_p( $target ); } // Directory for uploaded images $uploaddir = ABSPATH . 'wp-content/uploads/wpal_logos'; // Allowed mimes $allowed_ext = "jpg, gif, png"; // Default is 50kb $max_size = get_option(wpal_size); // height in pixels, default is 175px $max_height = get_option(wpal_height); // width in pixels, default is 450px $max_width = get_option(wpal_width); // Check mime types are allowed $extension = pathinfo($_FILES['wpaluploader']['name']); $extension = $extension[extension]; $allowed_paths = explode(", ", $allowed_ext); for($i = 0; $i < count($allowed_paths); $i++) { if ($allowed_paths[$i] == "$extension") { $ok = "1"; } } // Check File Size if ($ok == "1") { if($_FILES['wpaluploader']['size'] > $max_size) { print "Image size is too big!"; exit; } // Check Height & Width if ($max_width && $max_height) { list($width, $height, $type, $w) = getimagesize($_FILES['wpaluploader']['tmp_name']); if($width > $max_width || $height > $max_height) { print "Image is too big! max allowable width is&nbsp;" . get_option(wpal_width) ."px and max allowable height is&nbsp;" . get_option(wpal_width) ."px"; exit; } } global $user_id; get_currentuserinfo(); $image_name=$current_user->id.'.'.$extension; //the new name will be containing the full path where will be stored (images folder) // Rename file and move to folder $newname="$uploaddir./".$image_name; if(is_uploaded_file($_FILES['wpaluploader']['tmp_name'])) { move_uploaded_file($_FILES['wpaluploader']['tmp_name'], $newname); } print "Your image has been uploaded successfully!"; } // Create shortcode for adding to edit user page add_shortcode("wp-author-logo", "wpaluploader_input"); function wpaluploader_input() { $wpaluploader_output = wpaluploader_showform(); return $wpaluploader_output; } function wpaluploader_showform() { $wpaluploader_output = '<p><label for="wpauploader">Upload Company Logo:</label><br /> <input type="file" name="wpaluploader" id="wpaluploader" /> <br /> <small style="color:#ff0000; font-size:0.7em;">Allowed image types are .jpg, .gif, .png.<br /> Max image width = ' . get_option(wpal_width) . 'px, Max image height = ' . get_option(wpal_height) . 'px </small>'; return $wpaluploader_output; } // Create other Shortcode for full form add_shortcode("wp-author-logofull", "wpaluploader_inputfull"); function wpaluploader_inputfull() { $wpaluploader_outputfull = wpaluploader_showformfull(); return $wpaluploader_outputfull; } function wpaluploader_showformfull() { $wpaluploader_outputfull = '<form method="post" id="adduser" action="' . str_replace( '%7E', '~', $_SERVER['REQUEST_URI']) .'" enctype="multipart/form-data"> <p><label for="wpauploader">Upload Company Logo:</label><br /> <input type="file" name="wpaluploader" id="wpaluploader" /> <br /> <input name="updateuser" type="submit" id="updateuser" class="submit button" value="Upload" /> ' . wp_nonce_field( 'update-user' ) . ' <input name="action" type="hidden" id="action" value="update-user" /> <small style="color:#ff0000; font-size:0.7em;">Allowed image types are .jpg, .gif, .png.<br /> Max image width = ' . get_option(wpal_width) . 'px, Max image height = ' . get_option(wpal_height) . 'px </small>'; return $wpaluploader_outputfull; } add_action('admin_menu', 'wpal_menu'); function wpal_menu() { add_options_page('WP Author Logo', 'WP Author Logo', 'manage_options', 'wpal_wp-author-logo', 'wpal'); } function wpal() { if (!current_user_can('manage_options')) { wp_die( __('You do not have sufficient permissions to access this page.') ); } ?> <div class="wrap"> <div class="leftwrap"> <?php echo "<h2>" . __( 'Wordpress Author Logo Plugin', 'wpal_lang' ) . "</h2>"; ?> <?php if($_POST['wpal_author_logo_success'] == 'Y') { //Form data sent $wpal_width = $_POST['wpal_width']; update_option('wpal_width', $wpal_width); $wpal_height = $_POST['wpal_height']; update_option('wpal_height', $wpal_height); $wpal_size = $_POST['wpal_size']; update_option('wpal_size', $wpal_size); $wpal_logos = $_POST['wpal_logos']; update_option('wpal_logos', $wpal_logos); ?> <div class="updated"><p><strong><?php _e('WP Author Logo Plugin Options Saved.' ); ?></strong></p></div> <?php } else { //Normal page display $wpal_width = get_option('wpal_width'); $wpal_height = get_option('wpal_height'); $wpal_size = get_option('wpal_size'); $wpal_logos = get_option('wpal_logos'); } ?> <form name="wpal_settingsform" method="post" action="<?php echo str_replace( '%7E', '~', $_SERVER['REQUEST_URI']); ?>"> <input type="hidden" name="wpal_author_logo_success" value="Y"> <?php echo "<h4>" . __( 'Wordpress Author Logo Settings', 'wpal_lang' ) . "</h4>"; ?> <p><label for="wpal_width"><?php _e("Maximum Width: " ); ?></label><br /><input type="text" name="wpal_width" value="<?php echo $wpal_width; ?>" size="20"><?php _e("px"); ?></p> <p><label for="wpal_height"><?php _e("Maximum Height: " ); ?></label><br /><input type="text" name="wpal_height" value="<?php echo $wpal_height; ?>" size="20"><?php _e("px" ); ?></p> <p><label for="wpal_size"><?php _e("Maximum Size: " ); ?></label><br /><input type="text" name="wpal_size" value="<?php echo $wpal_size; ?>" size="20"><?php _e("Bytes: hint 50000 bytes = 50Kbs" ); ?></p> <p><label for="wpal_logos"><?php _e("Logo Images Folder: " ); ?></label><br /><input type="text" name="wpal_logos" value="<?php echo $wpal_logos; ?>" size="20"><?php _e(" ex: /wpal_logo_images/" ); ?></p> <p class="submit"> <input type="submit" name="Submit" value="<?php _e('Update Options', 'wpal_lang' ) ?>" /> </p> </form> </div><!-- / leftwrap --> </div><!-- / wrap --> <?php } ?> </code>
|
Frontend image uploading from edit profile page. (goldenapples)
|
wordpress
|
Here's the code I'm using to try and query a single taxonomy for one term, but exclude returned posts for that term that also belong to another. In English, this is what I want: query 'resource-type' for 'testimonies', but not 'testimonies' that are also 'audio'. Tips to tweak this code to get it to work? <code> <?php $testimonials_args = array( 'post_type' => 'resource', 'posts_per_page' => 1, 'tax_query' => array( 'relation' => 'AND', array( 'taxonomy' => 'resource-type', 'field' => 'slug', 'terms' => array( 'testimonies' ) ), array( 'taxonomy' => 'resource-type', 'field' => 'slug', 'terms' => array( 'audio' ), 'operator' => 'NOT IN' ) ) ); ?> </code>
|
I guess its because you are trying two conditions on one taxonomy, you can allways create a custom sql query, something like this: <code> $querystr = " SELECT * FROM $wpdb->posts LEFT JOIN $wpdb->term_relationships ON($wpdb->posts.ID = $wpdb->term_relationships.object_id) LEFT JOIN $wpdb->term_taxonomy ON($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id) LEFT JOIN $wpdb->terms ON($wpdb->term_taxonomy.term_id = $wpdb->terms.term_id) WHERE $wpdb->posts.post_type = 'resource' AND $wpdb->posts.post_status = 'publish' AND $wpdb->term_taxonomy.taxonomy = 'resource-type' AND $wpdb->terms.slug = 'testimonies' AND $wpdb->terms.slug NOT IN ('audio') ORDER BY $wpdb->posts.post_date DESC "; $pageposts = $wpdb->get_results($querystr, OBJECT); </code> or you can query just by one term and exclude by <code> has_term() </code> inside the loop something like this: <code> if (!has_term('audio','resource-type',$post->ID)){ //post without audio }else{ //post with audio (skip or whatever) } </code>
|
Query 1 taxonomy term, exclude another
|
wordpress
|
How can I remove the li from wp_nav_menu? I know I can remove ul but is it also possible to remove the li? I would want to do this on just one menu not all the menus on my site.
|
You could use a stackexchange-url ("custom walker").
|
Remove li from wp_nav_menu
|
wordpress
|
I'm currently using the WordPress Beta Tester plugin on a site. Is there a "best" way to transition the site to a "normal" WordPress install? The plugin includes this notice: Please note: Once you have switched your blog to one of these beta versions of software it will not always be possible to downgrade as the database structure maybe updated during the development of a major release.
|
It seems that one way is to simply manually upload the wp-admin and wp-includes directories, as the normal upgrade instructions state. I did this, and it worked. I'm still curious if there's a better way, to avoid any database issues.
|
How can I transition a site from using the Beta Tester plugin to a "normal" install?
|
wordpress
|
Is there a way to have Wordpress email me whenever a Page or Post is Published?
|
There's a few plugins that handle email notifications, but they all seem to act like a subscription service for (all) WordPress users. To notify just you when a post or page is published, it's literally a few lines of code. <code> function __notify_admin_on_publish( $new_status, $old_status, $post ) { if ( $new_status != 'publish' || $old_status == 'publish' ) return; $message = 'View it: ' . get_permalink( $post->ID ) . "\nEdit it: " . get_edit_post_link( $post->ID ); if ( $post_type = get_post_type_object( $post->post_type ) ) wp_mail( get_option( 'admin_email' ), 'New ' . $post_type->labels->singular_name, $message ); } add_action( 'transition_post_status', '__notify_admin_on_publish', 10, 3 ); </code> You can either drop this in your theme's <code> functions.php </code> , or save it as a plugin (which might be more appropriate, as it's not exactly 'theme' related).
|
Alert Email when any Post or Page is Changed
|
wordpress
|
I'm using this query to return attachments of a page. <code> $args = array( 'post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment' ); </code> Is there a way to adapt this in order to return attachments for the current page and the attachments of all child pages ?
|
The posts query is not recursive by nature. And I don't think that <code> post_parent </code> accepts multiple IDs, so you will likely need to loop and run this for multiple pages or play with query filters to do this in less requests (if performance becomes an issue).
|
How can I build a query that returns all attachments of a page and it's children pages?
|
wordpress
|
I'm attempting to remove the title attribute for post thumbnails (on certain posts), and I assume the get_image_tag filter is the way to do this. However, what I've got so far isn't working. What do I need to change to make this work? My code: <code> add_filter('get_image_tag', 'image_no_title'); function image_no_title($title) { $title = ''; return $title; } </code> And the relevant function (from wp-includes/media.php): <code> function get_image_tag($id, $alt, $title, $align, $size='medium') { list( $img_src, $width, $height ) = image_downsize($id, $size); $hwstring = image_hwstring($width, $height); $class = 'align' . esc_attr($align) .' size-' . esc_attr($size) . ' wp-image-' . $id; $class = apply_filters('get_image_tag_class', $class, $id, $align, $size); $html = '<img src="' . esc_attr($img_src) . '" alt="' . esc_attr($alt) . '" title="' . esc_attr($title).'" '.$hwstring.'class="'.$class.'" />'; $html = apply_filters( 'get_image_tag', $html, $id, $alt, $title, $align, $size ); return $html; } </code>
|
Thanks to Rarst pointing out that I was in the wrong place, I did some more digging and ended up with this: <code> add_filter('wp_get_attachment_image_attributes', 'wpse_19029_no_image_title'); function wpse_19029_no_image_title ($attr) { unset($attr['title']); return $attr; } </code>
|
What's the proper way to use the get_image_tag filter?
|
wordpress
|
I have several thousand users subrscribed to a WP website. Everyday I need to send an email to each user. The emails are custom generated depending on the data of several custom user profile fields. For each user a custom query based on this data returns a list of posts, which constitute the message of the email. As you can imagine that can get pretty heavy on the server, for that reason, when I launch the function to parse the users, generate the email and send it, Wordpress crashes. It works fine with a couple of dozen users, but several thousand is too much. What I'd like to do to avoid this, is to only handle ten users at a time, every two minutes for example. I can do that with a CRON function. I'm looking for the best way to do that. It would be something like "parse the first ten users and send their email, then parse the next ten, etc." How can I implement this ten by ten rule ? How is my function going to know on which user to start each time I call it ?
|
See <code> wp_schedule_single_event() </code> function. The general idea would be each time after you are done with a batch of users schedule next run few minutes ahead and pass info (such as offset from which user to continue) in arguments. On larger scale I'd consider looking into alternate more specialized solutions or simplifying your process. Mass emailing is not easy to get right and WP is not developed with such tasks in mind.
|
How to parse a huge list of users using a CRON function?
|
wordpress
|
I have a need to exclude posts based on a custom field type. It will probably be a field such as "legacy" or "depricated". I searched for an example on how this would be done but I haven't found anything worth while. Any help would be appreciated. <code> <?php $software = array('post_type' => 'software', 'category_name' => $model); query_posts( $software ); get_template_part( 'loop', 'software' ); wp_reset_query(); ?> </code>
|
I met the same problem before. I tried to use <code> meta_query </code> parameter in the query argument, but didn't succeed. The code I tried to use looks like this: <code> $software = array( 'post_type' => 'software', 'meta_query' => array('key' => 'legacy', 'value' => 1, 'compare' => '!=') ); query_posts($software); </code> But the problem is this query also excludes posts that don't have that meta key. So I had to use a custom query, that gets all posts with <code> legacy </code> meta key, and then excludes them: <code> global $wpdb; $legacy = $wpdb->get_col("SELECT ID FROM $wpdb->postmeta WHERE meta_key='legacy'"); $software = array( 'post_type' => 'software', 'post__not_in' => $legacy ); query_posts($software); </code> Hope this can help you.
|
Is there a way to exclude posts based on meta_values?
|
wordpress
|
I disabled the posts revision feature according to this codex by placing this code in the wp-config.php: <code> define('WP_POST_REVISIONS', false ); </code> But revions are still being saved by the WP. Why? I am using wp3.1.3 and Twenty Ten theme. I have couple of plugins, and disabling them does not resolve the issue.
|
<code> wp-config.php </code> is suggested place for such definitions, because at any point later they might get replaced by default values during loading. See Editing wp-config.php in Codex for thorough instructions. Also worth noting that it's commonly said like add to the end , but really definitions should go above this line: <code> /* That's all, stop editing! Happy blogging. */ </code> Or, if it was removed for some reason, above: <code> require_once(ABSPATH . 'wp-settings.php'); </code>
|
WP disobeys disabling of the posts revision feature
|
wordpress
|
I'm using the advanced custom field plugin and having a bit of trouble when using the image field type. (I'm not sure if this relates to the plugin that much actually!). When inserting an image instead of the option to select it I only have the option to insert it into post, which tries to insert the image into a wysiwyg. I only get the option to select image if I first insert it into post then delete it from the wysiwyg, then click choose image again and find it in the media gallery. Is there any workarounds/plugins to allow me to select the image straight away?
|
Try Verve Meta Boxes plugin of if you are up to coding yourself a metabox then you can use this class which does most of the work for you.
|
Unable to select image using custom image field type
|
wordpress
|
Imagine this basic shortcode in your functions.php file: <code> function div_shortcode( $atts ) { return '<div class="div"></div>'; } add_shortcode('div', 'div_shortcode'); </code> So every <code> [div] </code> in Wordpress editor gives <code> <div class="div"></div> </code> . Everything looks and works fine, right? Now here comes the trouble. I need to use my shortcode in PHP file (not putting it via WP Text Editor). Luckily there's a function for that: <code> <?php do_shortcode('[div]'); ?> </code> But, wait, it shows... nothing? <code> <?php do_shortcode('[gallery]'); ?> </code> Even this one doesn't work. Why is that happening? Any ideas?
|
The shortcode functions just return a value, you need to echo or assign it to something. <code> <?php echo do_shortcode('[div]'); ?> </code>
|
do_shortcode() doesn't do shortcodes ;)
|
wordpress
|
I began adding new users to my site tonight, all as authors. Is there a limitation to the number of users or how quickly they are added, after adding the 50th user there seems to be a minute or two delay before wordpress will allow me to add the next user.
|
Wordpress doesn't have any real limitation to that although your <code> wp_users </code> table may not be optimized and the queries to it become slow. Try doing this: Repair and optimize your tables Add Indexes to frequently used columns such as <code> user_login </code> or <code> user_nicename </code> and play around until it speeds everything up a bit You may also try disabling plugins one by one just in case there is a badly coded WP hook/action. As a final solution, I would add a huge list of users directly through a SQL query , that way you can add thousands of them in less than a second.
|
Limitations when adding new users
|
wordpress
|
We have the stackexchange-url ("Best Collection of Code for your functions.php file") thread, so I thought that it might be useful to create a thread for our .htaccess files. AND PLEASE REMEMBER TO ADD ANY OF YOUR OWN SNIPPETS TO THIS LIST
|
These are 3 snippet for better performance, regarding Yahoo! rules: Disable Etags: <code> Header unset ETag FileETag None </code> Add expire headers: <code> <FilesMatch "\.(ico|jpg|jpeg|png|gif|js|css|swf)$"> Header set Expires "Tue, 16 Jun 2020 20:00:00 GMT" </FilesMatch> </code> Or <code> ExpiresActive On ExpiresByType text/html "access plus 1 day" ExpiresByType image/gif "access plus 10 years" ExpiresByType image/jpeg "access plus 10 years" ExpiresByType image/png "access plus 10 years" ExpiresByType text/css "access plus 10 years" ExpiresByType text/javascript "access plus 10 years" ExpiresByType application/x-javascript "access plus 10 years" </code> Compress plain text file: <code> <FilesMatch "\.(js|css|html|htm|php|xml)$"> SetOutputFilter DEFLATE </FilesMatch> </code> Read more about them here. Updated: Redirect requests to www domain <code> RewriteCond %{HTTP_HOST} !^www\.domain\.tld [NC] RewriteRule ^(.*)$ http://www.domain.tld/$1 [R=301,L] </code> Block request to xmlrpc.php Use this only when you don't use remote publishing as it can prevent your blog from hacks. <code> RewriteRule ^(.*)xmlrpc\.php$ http://www.domain.tld [R=301,L] </code> Redirect all feeds to feedburner <code> RewriteCond %{HTTP_USER_AGENT} !^.*(FeedBurner|FeedValidator) [NC] RewriteRule ^feed/?.*$ http://feeds.feedburner.com/feed_uri [R=301,NC,L] </code>
|
Best collection of code for your .htaccess file
|
wordpress
|
I'm a bit confused now. I've installed Wordpress for my Polish friend from here: http://pl.wordpress.org/ On my local machine everything works fine and is in Polish, but installing it on the web server looks like default English Wordpress ("Recent posts", "Archives" etc.). Why? Every language file I found is polish (in themes/twentyten/languages AND wp-content/languages), also wp-config is set to <code> define('WPLANG', 'pl_PL'); </code> . Thanks.
|
Woah, default Polish WordPress package is corrupted. Change <code> define('WPLANG', 'pl_PL'); </code> to <code> define('WPLANG', 'pl_pl'); </code> or download older version.
|
Wrong WordPress language?
|
wordpress
|
I want to build a very simple toggle for taking my site down into a maintenance mode. To do that, I want to add a admin area to define a template that is the maintenance page, and allow that page to override the database defined template when maintenance mode is switched on. How can I change the theme template called for each page, WITHOUT affecting the database?
|
you can use <code> template_redirect </code> action hook to php include your maintenance mode template file using a simple option in options database. When you turn maintenance mode on add an option for example: <code> add_option('maintenance_mode_on'); </code> then with this code you check if that option is set and if so you redirect to your desired template file: <code> function custom_maintenance_mode_template_redirect() { global $wp; if(get_option('maintenance_mode_on')){ status_header(200); // a 404 code will not be returned in the HTTP headers if the page does not exists include(TEMPLATEPATH . "/Custom_template.php"); // include the corresponding template die(); } } add_action( 'template_redirect', 'custom_maintenance_mode_template_redirect' ); </code> Then when you turn maintenance mode off delete that option : <code> delete_option('maintenance_mode_on'); </code> Update If you want to effect the <code> body_class() </code> you can use <code> body_class </code> filter hook: <code> function custom_body_class($classes){ if(get_option('maintenance_mode_on')){ $n_classes[] = "maintenance"; return $n_classes; } else { return $classes; } } add_filter('body_class', 'custom_body_class'); </code> This will change the body_class() to output <code> maintenance </code> when maintenance mode is turned on.
|
Programatically switch page template?
|
wordpress
|
Currently for every category there is a separate template ( category-1.php, category-2.php , etc..), in my case there is over a hundred of them. I want refactor it to 4, so for instance if $cat is in range 1..20, render "first_category.php", if in range 21..50, render "second_category.php" and so on. Thanks!
|
if you can use <code> template_redirect </code> hook and a simple function to set the template to use <code> add_action( 'template_redirect', 'category_set_redirect' ); function category_set_redirect(){ //create the sets of categories $first_set= array("1","2","3","4","5","6"); $second_set= array("7","8","9","10","11","12"); if (is_category()){ if (in_array(get_query_var('cat'),$first_set)){ include(TEMPLATEPATH . "/first_category.php"); // include the corresponding template die(); } if (in_array(get_query_var('cat'),$second_set)){ include(TEMPLATEPATH . "/second_category.php"); // include the corresponding template die(); } } } </code>
|
How to override Category rendering mechanism
|
wordpress
|
I'm looking for a way to display a plain-text list of tags to use as classes on my post elements, I've been trying <code> $tags = get_tags(); $tag_list = ""; foreach($tags as $tag){ $tag_list .= $tag->name . " "; } echo "<li class=\"$tag_list\">"; </code> in the loop but it seems to output all the tags instead of just the current post's tags, so if I have tags <code> x </code> , <code> y </code> , and <code> z </code> , and I'm viewing a post with tag <code> x </code> I still get <code> <li class="x y z"> </code> anybody have any ideas as to how to show a plain-text list of tags or what I'm doing wrong?
|
You can play with arguments to only fetch what you need and get rid of loop: <code> $classes = implode(' ', wp_get_post_tags( get_the_ID(), array('fields' => 'names') ) ); </code>
|
Plain-text tag list?
|
wordpress
|
I found that I can do <code> <?php wp_tag_cloud( array( 'taxonomy' => 'name', 'format' => 'list' ) ); ?> </code> But I want the list to be seperated by the letter. Alphabeticaly is what I want. So it would display the letter A then all names with that letter and the letter B with all of the b's and so on. Any ideas?
|
What exactly do you mean by separated? If you want multiple tags clouds you will probably need to: fetch full list of terms; split it into groups by your criteria; call <code> wp_tag_cloud() </code> for each group, using <code> include </code> argument to use specific subset of terms.
|
Custom Taxonomy Tag Cloud?
|
wordpress
|
Pippin and Jean-Baptiste Jung have very good tutorials on how to programmatically create content when a new post is published using these four actions hooks... publish{post_type} add_action('new_to_publish_{post_type}, add_action('draft_to_publish_{post_type}, add_action('pending_to_publish_{post_type} ... to run this script... <code> global $user_ID; $new_post = array( 'post_title' => 'My New Post', 'post_content' => 'Lorem ipsum dolor sit amet...', 'post_status' => 'publish', 'post_date' => date('Y-m-d H:i:s'), 'post_author' => $user_ID, 'post_type' => 'post', 'post_category' => array(0) ); $post_id = wp_insert_post($new_post); </code> What hook should I be using to do this function only when a post is updated? Thank you!
|
you can use <code> pre_post_update </code> action hook like so: <code> add_action('pre_post_update','post_updating_callback'); function post_updating_callback($post_id){ global $post; // verify if this is an auto save routine. // If it is our form has not been submitted, so we dont want to do anything if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; if ($post->post_status == "publish"){ //do update stuff here. } } </code> Update: instead of <code> wp_insert_post() </code> use <code> wp_update_post </code> like this: <code> //first get the original post $postarr = get_post($post_id,'ARRAY_A'); //then set the fields you want to update $postarr['post_title'] = "new title"; $postarr['post_content'] = "new edited content"; $post_id = wp_update_post($postarr); </code> this way you only need to specify the fields that were updated and never worry about stuff like what was the original post type.
|
What hook should be used to programmatically create a post only when master post is updated?
|
wordpress
|
I'd like to create a front page video feature that embeds a vimeo video of the users choosing. I'd like the user to only have to input the video code. For instance, for http://vimeo.com/24474320 - I'd like them only to have to input "24474320". Should I use custom post types for this? If so, how do I set this up so that it limits the field size? I'm just getting started, and I'm relatively new at wordpress, so I don't need to get into specific code necessarily - it's more of a strategic question. How would you tackle this? Thanks, Tim -----------------------EDIT (Monday, June 6) It would be awesome if all the user (backend) saw was this: FRONT PAGE VIDEO FEATURE Vimeo URL: [ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ __ _ ] [Save] [Cancel] Then I would call that video into the front page feature.
|
With oEmbed support in both WordPress and on Vimeo's end, why not just use the <code> [embed] </code> shortcode? <code> [embed]http://vimeo.com/24474320[/embed] </code> This is easy to explain, and users are generally pretty comfortable with just copy-and-pasting a URL directly, rather than having to extract just the ID out of it. You can also turn on the option to just use the URL on a line by itself in a post, without the <code> [embed] </code> shortcode. Personally, I prefer the explicit shortcode, because it always works, and there's less chance of other plugins interfering.
|
Should I use custom post types for a front page video feature (vimeo)?
|
wordpress
|
When you're upgrading a plugin you can quickly check if the plugin version you are about to upgrade to works with your current version of Wordpress. Is there a way of checking that your current plugins will work with the version of Wordpress you are about it upgrade to without searching for each one in the directory?
|
Have a glance at Better Plugin Compatibility Control . I just found this out this morning. I think this does what you're after.
|
How to check plugin compatibility before upgrading Wordpress
|
wordpress
|
I have the following lines of code that add the settings link and setup for my plugin: <code> add_action('admin_menu', array(&$this, 'admin_settings_menu')); // Add menu to options add_action('admin_init', array(&$this, 'admin_settings_init')); // Add admin init functions </code> Now because of the nature of my plugin if the plugin is Network Installed then the settings should only be available to the network admin not the individual site admins. Is there a way to check if the plugin is Network Installed so I can wrap an if statement round it?
|
You can use <code> is_plugin_active_for_network( $plugin ) </code>
|
How to tell if plugin has been network activated
|
wordpress
|
I'm trying to build a query in order to sort some posts by a date custom field, where the dates are formatted dd/mm/yyyy. It works by querying the database directly with <code> get_results </code> like in this example : <code> $querystr = " SELECT * FROM wp_posts, wp_postmeta WHERE wp_posts.ID = wp_postmeta.post_id AND wp_postmeta.meta_key = 'my_cutom_date' AND wp_posts.post_status = 'publish' AND wp_posts.post_type = 'post' ORDER BY STR_TO_DATE(wp_postmeta.meta_value, '%d/%m/%Y') ASC "; </code> But, I would like to transpose this behavior to a <code> WP_Query </code> , using a <code> posts_where </code> filter. I got as far as this : <code> $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 10, 'meta_key' => 'my_custom_date' ); function filter_orderby( $orderby = '' ) { global $wpdb; $orderby .= " ORDER BY STR_TO_DATE($wpdb->postmeta.meta_value, '%d/%m/%Y') ASC "; return $orderby; } add_filter( 'posts_orderby', 'filter_orderby' ); </code> But it doesn't seem to return anything. what am I missing ?
|
The filter on <code> posts_orderby </code> should return a string that does not begin with <code> ORDER BY </code> , WordPress will add that itself . By default WordPress will filter by <code> post_date </code> . If you don't want that, you should overwrite the order clause, not append to it. So your filter should look like this: <code> function filter_orderby( $orderby ) { global $wpdb; return " STR_TO_DATE({$wpdb->postmeta}.meta_value, '%d/%m/%Y') ASC "; } </code>
|
How to filter a dd/mm/yyyy date from a custom field in a query
|
wordpress
|
I've got the "Widget Logic" plugin installed. I have created my own widget called "Buzz". I have a sidebar with multiple instances of my custom widget "Buzz". Now, on the Widgets admin page when a sidebar is toggled open and all of the widgets in that sidebar are closed up, you can see a widget name and widget instance title (if one is specified). For example, if I have 2 instances of my "Buzz" widget with different titles, on the Widget admin page it looks something like: <code> Buzz: Title 1 Buzz: Title 2 </code> What I would like to do is to display "Widget Logic" value specified for a widget instance under the "widget name: widget instance title" line on the Widget admin page. So, for example: <code> Buzz: Title 1 Displayed on: is_front_page() Buzz: Title 2 Displayed on: is_page("page_slug") </code> Hope that makes sense. Would really appreciate if any one could help me out with this: how to get the value specified in the "Widget Logic" input box and display it under the widget instance title on the Widget admin page. Many thanks, Dasha
|
I'm almost sure there is no way to do that (server side) without hacking core files, bu luckly i know a little jQuery and i've come up with this hackish function that does the job just fine: <code> function widget_logic_hack(){ global $pagenow; if ($pagenow == 'widgets.php'){ ?> <script> function hack_logic(){ jQuery('input[id$="widget_logic"]').each(function() { if (jQuery(this).val().length === 0){}else{ var id = this.id; var value = jQuery(this).val(); //alert(value); id = id.replace('-widget_logic',''); var currenttitle = jQuery("[id$='"+ id +"']").find('h4').html(); if (currenttitle.indexOf('Displayed on:') !=-1 ){ var ncurrenttitle = currenttitle.substring(0,(currenttitle.indexOf('Displayed on:'))); //alert(ncurrenttitle); jQuery("[id$='"+ id +"']").find('h4').html(ncurrenttitle + 'Displayed on: <span class="in-widget-title">' + value + '</span>'); }else{ jQuery("[id$='"+ id +"']").find('h4').html(currenttitle + '<br /> Displayed on: <span class="in-widget-title">' + value + '</span>'); } } }); } jQuery(document).ready(function(){ setTimeout("hack_logic()",500); jQuery('#savewidget').live('click', function() { setTimeout("hack_logic()",5500); return true; }); }); </script> <style>.widget .widget-top {height: 40px !important;}</style> <?php } } add_action('admin_footer','widget_logic_hack'); </code>
|
How to get "Widget Logic" plugin's input value in a custom widget code (to display on the Widget admin page)
|
wordpress
|
I have a script that's called from my functions.php file (via an ajax .get) that needs to have access to WP's get_option() method in order to retrieve some values it needs to process. However, although the file works great in the majority of sites where it resides, on just a few installations, I'm having problems with the script operating (chrome's javascript console reports a 404 (not found) on color.php. <code> //jQuery calls the file color.php $('#my_theme_switcher').change ( function() { $.get ('<?php echo get_bloginfo('template_directory') ?>/color.php', {theme: 'test', spot: '1'}, function(data) { doColor('#theme_header_color', data); } ); } ); Here is the file color.php <?php require_once('../../../wp-blog-header.php'); echo 'all good'; ?> </code> In this case, I never get the echo since it appears that the require statement has failed to load the wp-blog-header.php Is there an alternative way of including the header file in order to be able to call get_option()?
|
You shouldn't need to make direct calls to your theme files - use the AJAX API, and make all requests to <code> admin-ajax.php </code> (that way, WordPress'll be loaded for you, and you won't need to assume the file hierarchy in order to load it manually). <code> $.get( '<?php echo admin_url( 'admin-ajax.php' ) ?>', { "color_theme" : "test", "color_spot" : "1", "action" : "change_color" }, function( data ) { doColor( '#theme_header_color', data ); } ); </code> And in <code> functions.php </code> ; <code> function __do_color_ajax() { $theme = $_GET['color_theme']; $spot = $_GET['color_spot']; // do something die( 'AJAX output' ); } add_action( 'wp_ajax_nopriv_change_color', '__do_color_ajax' ); </code> See how the suffix of the hook, <code> wp_ajax_nopriv_change_color </code> , matches the action variable in the AJAX request? stackexchange-url ("See this SE answer for more info"). Note I've also prefixed the other AJAX request variables, as you should $_GET </code> and <code> $_POST </code> variables in the same way you do PHP variables and functions. Also check out the codex on the AJAX API .
|
Including wp-blog-header.php from functions.php remote call?
|
wordpress
|
Update The end result is that I did not account for Apache memory limits. There were limits placed on the Apache process which caused PHP to be limited regardless of the settings placed on it. Changing these values in httpd.conf, helped. Hello, I am encountering an error with a recently launched site that although the pages display, I am severely limited by the number of plugin's that I can enable. We started to see an error occur: <code> Fatal error: Out of memory (allocated 24903680) (tried to allocate 1802297 bytes) in /home/normal/public_html/normalpl.org/wp-includes/wp-db.php on line 791 </code> Now we have tried the usual fixes of increasing PHP and Wordpress memory allocations (have a VPS, with full root) all the way up to 256MB but with no affect on the error. The following are the plugins enabled: CMS Tree Page View WP-DBManager Login Lockdown Contact Form 7 Now enabling any other plugins will start to cause these memory errors to occur. Almost always on Post/Page save operations. Notably, All in One SEO or Yoast SEO or W3 Total Cache, but others will also cause this to occur. I noticed that in the database there were some strange Unicode Code Points that had been brought in by a cut/paste from Word and so I went through all of the Posts/Pages and escaped all of the entities so that they were not unicode but HTML Entities. Unfortunately, the error was still occurring upon enabling one of the above plugins and saving a post/page. I wiped out all files/configurations and started with a fresh install of Wordpress and re-imported the existing database to make sure there wasn't something strange in the files and I still encountered the issue. I feel that I am stuck on thinking that there is some strange escaping bug going on when it hits that mysql_real_escape_string function as removing that and just dumping the plain string into the database works (but is horrible for XSS and proper MySQL escaping). In addition, the error happens when using the older method of Add_Slashes, and I also noticed that Magic_Quotes_GPC is on if that helps. Thanks for all of the assistance, this is a baffling one for me. -Adam
|
If you suspect content-specific issue, I'd first try to start with clean site and set of test content instead ( official Theme Unit Test data for example). If processing content is indeed at fault this is quite unusual issue. If you can narrow it down to specific function it might be possible to build some kind of test case, by getting content directly from database and running it through that function, while measuring resource consumption.
|
Out of Memory - Line 791 of WP-DB.php (mysql_real_escape_string)
|
wordpress
|
Any Short code Availble for Get Post List With Thumbnail Plugin? or else how to Create Short code for this Particular plugin? Thank u in Advance.
|
here is a quick crack at making it a shortcode paste this code in your theme's functions.php file: <code> add_shortcode('gplt','getPostListThumbs_shortcode'); function getPostListThumbs_shortcode($atts, $content = null){ extract(shortcode_atts(array( 'orient' => 'v', 'imgo' => false, 'ttgo' => false, 'dtgo' => false, 'dtfrm' => 1, 'categ' => '', 'postnr' => 20, 'linn' => 3, 'tbwid' => 40, 'tbhig' => 40 ), $atts)); $orient = gtpartrat($orient,'v'); $imgo = gtpartrat($imgo,false); $ttgo = gtpartrat($ttgo,false); $dtgo = gtpartrat($dtgo,false); $dtfrm = gtpartrat($dtfrm,1); $categ = gtpartrat($categ,''); $postnr = gtpartrat($postnr,20); $linn = gtpartrat($linn,3); $tbwid = gtpartrat($tbwid,40); $tbhig = gtpartrat($tbhig,40); $htmlcod = "<table id='div_postlist' width='".$divwid."' cellpadding='4' cellspacing='4'>"."\n"; $htmlcod .= "<tr>"."\n"; // if (have_posts()) : global $post; if($categ!=''){ $strquery = "numberposts=".$postnr."&category_name=". $categ; } else{ $strquery = "numberposts=".$postnr; } $myposts=get_posts($strquery); $ctxtr = 0; switch($dtfrm){ case 1: $dtdis = 'd/m/y'; break; case 2: $dtdis = 'm/d/y'; break; } if($myposts): foreach($myposts as $post) : $args = array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID ); $attachments = get_posts($args); $imgsrc = ""; if ($attachments): foreach ($attachments as $attachment) { $imgsrc = wp_get_attachment_image($attachment->ID, array($tbwid,$tbhig), $icon = false); break; } endif; if($orient=="v"){ if($ctxtr == 0){ $htmlcod .= "<tr>"."\n"; } $ctxtr = $ctxtr + 1; $htmlcod .= "<td valign='top'>"."\n"; if($imgsrc!=""): $htmlcod .= "<a href='". get_permalink() ."' title='". get_the_title() ."'>"."\n"; $htmlcod .= $imgsrc; $htmlcod .= "</a>"."\n"; endif; $htmlcod .= "</td>"."\n"; if(!$imgo){ $htmlcod .= "<td valign='top'>"."\n"; if($dtgo): $htmlcod .= "<p>".get_the_time($dtdis)."</p>"; endif; if($ttgo): $htmlcod .= "<a href='". get_permalink()."' title='". get_the_title() ."'>"; $htmlcod .= get_the_title(); $htmlcod .= "</a>"."\n"; endif; $htmlcod .= "</td>"."\n"; } $htmlcod .= "</tr><tr>"."\n"; } else{ if($ctxtr == 0){ $htmlcod .= "<tr>"."\n"; } $ctxtr = $ctxtr + 1; $htmlcod .= "<td valign='top'>"."\n"; $htmlcod .= "<table cellpadding='3' cellspacing='3' border='0' width='100%'>"."\n"; $htmlcod .= "<tr>"."\n"; $htmlcod .= "<td valign='top'>"."\n"; if($imgsrc!=""): $htmlcod .= "<a href='". get_permalink() ."' title='". get_the_title() ."'>"."\n"; $htmlcod .= $imgsrc; $htmlcod .= "</a>"."\n"; $htmlcod .= "</td>"."\n"; endif; if(!$imgo){ $htmlcod .= "<td valign='top'>"."\n"; if($dtgo): $htmlcod .= "<p>".get_the_time($dtdis)."</p>"; endif; if($ttgo): $htmlcod .= "<a href='". get_permalink()."' title='". get_the_title() ."'>"; $htmlcod .= get_the_title(); $htmlcod .= "</a>"."\n"; endif; $htmlcod .= "</td>"."\n"; } $htmlcod .= "</td>"."\n"; $htmlcod .= "</tr>"."\n"; $htmlcod .= "</table>"."\n"; $htmlcod .= "</td>"."\n"; if($ctxtr == $linn){ $htmlcod .= "</tr>"."\n"; $ctxtr = 0; } } endforeach; else: $htmlcod = "<tr>"."\n"; $htmlcod = "<td>"."\n"; $htmlcod .= "No registers found."."\n"; $htmlcod .= "</td>"."\n"; $htmlcod .= "</tr>"."\n"; endif; endif; $htmlcod .= "</table>"; return $htmlcod; } </code> Usage: simply call the shortcode <code> [gplt parametes] </code> from any post or a page parameters: Orientation: orient="v" // v = Vertical , h = Horizontal default 'v' Display only images: imgo="false" // true, false default 'false' Display post title: ttgo="false" // true, false default 'false' Display post date: dtgo="false" // true, false default 'false' Date Format: dtfrm="1" // 1 - d/m/y , 2 - m/d/y default '1' Category Name: categ='' // leave out or blank for all categories default '' Number of Posts: postnr="20" //default=20 Number of registers per line: linn="3" //default=3 only for horizontal orientation Thumbnails Width: tbwid="40" //default = 40 Thumbnails Height: tbhig="40" //default = 40
|
Any Short code Availble for Get Post List With Thumbnail Plugin?
|
wordpress
|
A client of mine has a WP multisite network of sites which all use the same template. This template uses wp_page_menu. I just added a mobile version of the template by using a certain plugin. It will use the same pages as the desktop version of the website, but the client has requested a different landing page. The problem is that if I create a new page to facilitate this landing page, it will show up in the code generated by wp_page_menu. Since all sites in this network uses the same template and the page will have different page IDs on different sites, I cannot exclude it manually in the wp_page_menu function. I was thinking that if I could exclude the post by title or category name instead of by ID, this might work. But I don't know how to do that. Please help?
|
How about using <code> get_page_by_path() </code> , then using the ID from the returned object in an exclude filter? <code> add_filter('wp_page_menu_args','my_nav_exclude_pages'); function my_nav_exclude_pages( $args = array() ) { $homepage = get_page_by_path('my-page-slug'); $args['exclude'] = join( ',', array( $args['exclude'], $homepage->ID ) ); return $args; } </code>
|
Excluding a page with a certain name from wp_page_menu
|
wordpress
|
I have a simple custom widget that asks for its width (that is used later in the front end). The width field is a select dropdown, so a user have predefined options. I will have many instances of my widget, each will have its own width setup. Now, in my widget code I have the following code: <code> echo $before_widget; </code> which results in: <code> <div class="widget my" id="my-widget-1"></div> </code> What I'd like to do is somehow hook into <code> $before_widget </code> and add my own class (the specified width from the select dropdown). So, I want the following markup: <code> <div class="widget my col480" id="my-widget-3"></div> </code> And if there is no class specified then I want to add <code> class="col480" </code> . How do I achieve this? Thanks for help! Dasha
|
Aha, so the <code> $before_widget </code> variable is a string representing div element: <code> <div class="widget my" id="my-widget-1"> </code> . So I checked the <code> $before_widget </code> for the "class" sub-string and added my <code> $widget_width </code> value to it. The code is from my custom widget file: <code> function widget( $args, $instance ) { extract( $args ); ... //other code $widget_width = !empty($instance['widget_width']) ? $instance['widget_width'] : "col300"; /* Add the width from $widget_width to the class from the $before widget */ // no 'class' attribute - add one with the value of width if( strpos($before_widget, 'class') === false ) { $before_widget = str_replace('>', 'class="'. $widget_width . '"', $before_widget); } // there is 'class' attribute - append width value to it else { $before_widget = str_replace('class="', 'class="'. $widget_width . ' ', $before_widget); } /* Before widget */ echo $before_widget; ... //other code } </code> I wanted to add my <code> $widget_width </code> variable to the widget div element within my own widget code (while I had an easy access to the <code> $widget_width </code> variable). Hope that makes sense and will help someone. Thanks, Dasha
|
Add class to before_widget from within a custom widget
|
wordpress
|
There's a specific category on my website that should be restricted to teachers only using login. However, I don't want to hassle the teachers with the not so welcoming admin Wordpress offers. I would like to offer a "lightbox" that's basically a login that doesn't automatically forward to the admin, but only makes the teachers category content available. Do you know any plugin that allows that? Thanks, Sarit
|
Don't know about a plugin that does that for you but you can use the WordPress native Thickbox: First include the Thickbox script and style in your category only if the user is not logged in (simply copy/paste in your theme's functions.php file) <code> function add_thickbox_script_and_style(){ if(is_category('YOUR_CATEGORY') && !is_user_logged_in()){ wp_enqueue_script('jquery'); wp_enqueue_script('thickbox',null,array('jquery')); wp_enqueue_style('thickbox.css', '/'.WPINC.'/js/thickbox/thickbox.css', null, '1.0'); } } add_action('init','add_thickbox_script_and_style'); </code> Then open up your category.php (or archive.php depending on your theme , or even better is a custom file for that category <code> category-id.php </code> ) and add this code before the loop: <code> if (is_category('YOUR_CATEGORY') && !is_user_logged_in()){ echo '<div id="lform" style="display:none;">'; wp_login_form(); echo '</div>'; echo 'Please <a class="thickbox" href="#TB_inline?height=200&width=200&inlineId=lform">Login</a> to see the content'; }else{ //your loop goes here } </code>
|
Login "Lightbox" for specific category content
|
wordpress
|
I have a Linode VPS running a single Wordpress blog. It has been running just fine until today. The admin panel is snappy, but the site is very slow. I am still finishing the site, so there shouldn't be any traffic. When I go to mydomain.com it takes 45+ seconds to load, then each click on the link takes about the same amount of time. I didn't update any WP plugins (or WP), but I did add a google analytics plugin a week ago, but seemed fine. I disabled that and no difference either. I tried rebooting nginx, and then rebooted the whole machine... still slow. My "free -m" output is: <code> user@myserver~ $ free -m total used free shared buffers cached Mem: 469 147 321 0 3 45 -/+ buffers/cache: 98 370 Swap: 511 0 511 </code> The weird part is nothing has changed in the last few days....Any ideas?
|
Not much information to go on... Start with elimination - disable the plugins, switch to default (or better - blank) theme. If it gets better - just find code at fault. If you are down to the bare and clean WP core and still having the issue - likely you have some server configuration issue. Since you have considerable control over server you can also hook up some PHP profiler and try to make a dump of what is going on.
|
Wordpress site is sloooow, but admin is fast....any ideas?
|
wordpress
|
Ok so i have my mu setup with subdomains and need a subdomian to point to a different path. My issue is when i add the vhost file it loads before wordpress and loads it path for everything that does not have an assigned path in my vhosts config. But if i load after wordpress domain install then it trys to create a site for the subdomain entered. What i need is this: sub2.mydomain.com - points to /path/to/sub/directory *.mydomain.com - points to /path/to/wordpress/install UPDATE: I am using a domain mapping plugin which i think is causing my issue. All sub sites load fine but when i load a mapped domain to a sub site it does not work. I can not add my mapped domain each time to my vhost config since i plan on allowing others to map domains
|
Since my domain mapping plugin does not do cname (wpmudev domain mapping) i could not use the cname suggestion. As for the ip address this is untested as i do not want to add more to my hosting bill at this time maybe in the feature ill give it a shot. ordering the vhosts and assigning alias works but like i said in a previous comment i plan on allowing other users to map a domain name and that means i would have to add it manually every time one was registered. My solution is this: I created a wp site with a sub-domain of my choice and then created a sym link in the wp root folder (i know that i can access from any site but not many people will not that) so when i type in subdomain1.mydomain.com/analytics it will load the analytics same goes for my issue tracking script. By creating the site i can create a page that shows a list of services that can be accessed. Thanks John P Bloch for your help i know this was not a WordPress issue completely but since it was my domain mapping plugin that to me made it enough as well thank you EAMann this would work but like i said above i would need to create a s-alias every-time.
|
Wordpress MU subdomain vhost
|
wordpress
|
The way I'm set up currently, I create a post for each user of the site, custom-post-type, Agent, then assign it to a user, and they can edit it however they like. What I want to remove or disable is in the admin side, Agents/Add New. Currently all users are set to Author, so if I could make it so if the user is an Author they can't create new posts of custom-post-type, Agent. I'd also like to remove the ability of the author to create standard wordpress posts. The caveat to all this is I need to allow authors to create as many posts as they like as custom-post-type, Property. Here is a pic of what I want to remove (in red) for agents custom-post-type, if the user is an author.
|
try my plugin Posts Creation Limits which was made for that same reason.
|
Prevent authors from creating new posts of specific custom-post-type
|
wordpress
|
Can anyone recommend a simple plugin that allows me to add/edit meta tags for keywords and description on each page of my wordpress site? Just something that adds the fields to the page editor would be ideal. Not looking for SEO megapack or whatever. Thanks, John.
|
the simple solution would be to paste this snippet of code in your theme's functions.php file : <code> add_action('wp_head','keywords_and_desc'); function keywords_and_desc(){ global $post; if (is_single()||is_page()){ if(get_post_meta($post->ID,'my_keywords',true) != '') echo '<meta content="'.get_post_meta($post->ID,'my_keywords',true).'" name="keywords">'; if(get_post_meta($post->ID,'my_description',true) != '') echo '<meta content="'.get_post_meta($post->ID,'my_description',true).'" name="description">'; } } </code> And the just add keywords and description using the built in custom fields on a new/edit post/page screen, name the keywords field <code> my_keywords </code> and the description field <code> my_description </code> . or you can use a very lightweight and simple plugin called Simple Meta Tags
|
Meta keywords and descriptions plugin for manually editing meta for each page/post
|
wordpress
|
I've set up my loop-attachment.php to show the gallery of thumbnails above the main, selected image using this code from the WordPress Codex: <code> <?php $gallery_shortcode = '[gallery id="' . intval( $post->post_parent ) . '" size="mini-thumbnail" columns="10"]'; print apply_filters( 'the_content', $gallery_shortcode ); ?> </code> However, if the image has a caption, it shows up underneath its image, throwing off my neat little grid of images. I don't want to turn captions completely off or not use them at all, because after the grid and below the main 960x540 image, I want to do an "Image Summary" kind of section, with the filename, original size, caption, description, etc. Is there a way to turn off captions in the above code? The gallery shortcode section of the WordPress Codex doesn't have anything on it.
|
you can always just set a css tag <code> display:none </code> to the caption element
|
Turn off image captions in gallery view?
|
wordpress
|
I have a Category that I would like to hide in the WP Admin so the author can never check it when adding or editing a post. Is there anyway I can prevent it from showing up by modifying my function.php file?
|
a simple way to hide it would be to find the ID of the category <code> li </code> and use css to set it to display:none. <code> function hide_the_category(){ ?> <style type="text/css"> li#category-4{ display:none; } </style> <?php } add_action( "admin_head", "hide_the_category" ); </code>
|
Anyway to hide a Category in the Categories section when adding/editing a post in WP Admin?
|
wordpress
|
Is it possible to create an account & ordering system with online payment (via paypal) for WP? Are there any kind of plugins for this? We'd require some basket functionality so products can be added, an account area that could include order history and online payment to pay via paypal.
|
Most of the new and updated Cart/E-commerce plugins offer that functionality for ex: TheCartPress, E-Commerce for WordPress Stores (long name for a plugin) wpStoreCart DukaPress
|
Creating an online account & ordering system
|
wordpress
|
I'm in the process of making my own widget but I don't like it to fully generate the content each time since the process is quite lenghty. I can easily create my own caching mechanism but I'm wondering if there is something that already exists in the wordpress core when it come to caching widgets. Ideas? Thanks! Dennis
|
take a look at WordPress Transients API which offers a simple and standardized way of storing cached data in the database temporarily by giving it a custom name and a timeframe after which it will expire and be deleted. The transients API is very similar to the Options API but with the added feature of an expiration time, which simplifies the process of using the wp_options database table to store cached information.
|
Creating your own widgets: using cache?
|
wordpress
|
I have products in my store sorted by categories. (Braslets; Rings; Earrings) It was not difficult to adapt my theme for listing products by categories. But now I need to organize my products by collections. I have collections for example 'Spring surprise', 'Smoky winter' etc. First time I thought to assign tags to products, but I also need to show collections description, this means to show tag's description. How can you advice me to organize products by collections? Does wp-e-commerce allow to set up a tag description? PS. I'm newbie in wp-e-commerce and it seems to be hard for understanding.
|
There's a description field available for the <code> product_tag </code> taxonomy that can be used in your template . You could also add an additional "collections" custom taxonomy for use with the <code> wpsc-product </code> custom post type.
|
How to organize products by collections with collections description?
|
wordpress
|
Pligg sucks, Hotaru CMS is dead and I'm not sure if the Nominate theme is what I want. Basically I'm trying to create a link submission website like Reddit with WordPress, this would basically mean: Voting Easy link submission Member creation and restriction of groups oEmbed support (optional) I looked at BuddyPress but it appears it's trying to be more of a social networking site (Facebook) instead of a social link submission site (Reddit).
|
These can be nicely done with WordPress using custom post type for link submission, so then the rest becomes very easy using a few plugins: Voting - CMS Vote Up Social CMS News will handle the voting. Easy link submission - simple custom front end post form would do the job (ex: stackexchange-url ("here") or you can use plugins like Mini TDO, Gravity forms... Member creation and restriction of groups - this is build in with WordPress, users and roles oEmbed support - here is the only part i can think of that you would have a lot of work with unless you mean giving users ability to oEmbed there links like youtube in which case you can use the built in oEmbed support.
|
Link submission website (ala Reddit)?
|
wordpress
|
I installed the all in one seo pack plugin and after enabling it my post titles get "stuck" with my blog title without a space in the title. As you can see the post title is: <code> ******.blogg.no </code> And my blog title is: <code> Sp**set Blogg </code> The title is now <code> *******.blogg.noSp**set Blogg, </code> I can't figure out how I can get these to separated. My all in one seo pack settings is <code> %post_title% </code> on the posts.
|
Its documented.. heres a fix
|
My post titles is getting mashed up with my blog title
|
wordpress
|
need to send an email from a page when a form is submitted. Thought i'd use jquery post but not really sure where to start. Would i use wp_mail? And if so how could it be called ? Sorry if that seems vague. Just trying to send an email to the client before a form posts its data to another site; <code> $('#donationForm').submit(function() { // send email to client before moving onto worldpay payment form // send data to worldpay.... this.submit(); }); </code> best, Dc
|
Basically, you can use JavaScript to post to a WordPress function, then the WordPress function can invoke <code> wp_mail() </code> to send the message. A great place to start would be the useful AJAX in Plugins article on the Codex. It walks you through all the steps required to add your JavaScript on the front-end, your PHP on the back-end, and everything you need to do to tie the two together.
|
wp_mail script with jquery post
|
wordpress
|
I use custom fields for lots of my content on both Posts and Pages, so that half of the text will be in the main post body and the other half in a custom field. Unfortunately, when doing this only the text in the post body is searchable. I want to have all the custom fields included in the search (just joined together as one). Preferably without installing a plugin, as all the plugins I have seen do not seem to be able to do this or they add loads of options I don't need. I just would like one search box, that uses WordPress's default search but finds words in custom fields as well as those in the main body. Is this possible?
|
In the end I used the Relevanssi plugin which lets you include custom fields in the search quite easily, you can either include all the fields or choose which fields to include.
|
Including custom fields in search?
|
wordpress
|
How can I instruct NextGen Gallery to use different thumbnail sizes for different galleries. I have different gallery templates for use in different parts of the site, and the sizes of the thumbnails are not the same. At the moment I have to stay generating the thumbnails through the gallery management page, it would be much better if I could set the thumbnail size for each gallery once and for all. Thanks.
|
Templates The most important feature improvement in Version 1.00 is the template engine. Custom templates are PHP files that can be stored in the folder nggallery, inside your theme directory. NextGEN gallery look up always first into this folder if there are the vaild template file. For example, if you are using the default WordPress theme then you can store a template file at : <code> /wp-content/themes/default/nggallery/gallery-sample1.php </code> To use now this template in a post or page you insert the tag: <code> [nggallery id=1 template=sample1] </code> This tells NextGEN Gallery to use ‘gallery-sample1.php’ to show the gallery output. Without this template tag, NextGEN takes the default template (gallery.php) from the plugin folder (unless you copy it to your theme folder), normally located at : <code> /wp-content/plugins/nextgen-gallery/view/gallery.php </code> The same you can use for album, singlepic or imagebrowser, all of them are template driver so that you can easily modify the output without having problems during a upgrade. Resource: http://nextgen-gallery.com/templates/
|
NextGen Gallery different thumbnail size per gallery
|
wordpress
|
How can one differentiate between posts and pages in search results? What I need to do is show a <code> the_time </code> div for posts but not show it for pages, as it's irrelevant. With a function? <code> <?php if (!is_page()) } </code> in the loop below doesn't help. <code> <?php if (have_posts()) : ?><?php while (have_posts()) : the_post(); ?> <a href="<?php the_permalink() ?>"><?php the_title(); ?></a> //prevent this div from displaying for pages: <div class="searchdate"><?php the_time('F jS, Y') ?></div> <?php the_excerpt(); ?> <?php endwhile; ?><?php else : ?><?php endif; ?> </code>
|
Try this... <code> <?php //prevent this div from displaying for pages: if ( get_post_type() != 'page' ) : ?> <div class="searchdate"><?php the_time('F jS, Y') ?></div> <?php endif; ?> </code> The <code> is_page() </code> conditional tag only checks if currently displayed content is a single page view. Nothing for you at this point. See http://codex.wordpress.org/Function_Reference/is_page
|
Differentiate between posts and pages in search results
|
wordpress
|
I really like https://github.com/devinsays/options-framework-plugin Does anyone know any other good implementations of an options panel from a Framework or from another premium Theme? I think its a major factor in deciding whether to use a theme. I'd like to get a good list of whats being done out there. Wordpress StackExchange Community, what are your thoughts in general this?
|
Of the few I've seen, I think that most "premium" Themes way over-complicate Theme Settings pages. I generally prefer Theme Settings pages that maintain the style/layout of the rest of the WP-Admin UI. So, these would be my rules of thumb: Incorporate meaningful settings, and not necessarily every possible setting under the sun. Organize settings logically. Maintain consistent layout/style with the rest of the WP-Admin UI, including Settings fields, sections, and page tabs. Note: use of the Settings API makes this dead-simple.
|
Theme Options Panels, What are some good examples from Frameworks or Premium Themes?
|
wordpress
|
it might be the simplest question but i can't find why my javascript files and images are not recognized by wordpress : i put all my JS files and images in my theme's folder, so i created a folder "word" inside "theme", with all the content and then i added my files. But the website doesn't recognize the path to the javascript or the images. Could you please tell me what i'm doing wrong? i used it like that in the header page : < script src="jquery.js" type="text/javascript"> Thanks ;)
|
You need to give the full path to your theme files. To get the URL of your theme, use the WordPress function <code> bloginfo( 'template_directory' ); </code> so at a minimum you would need: <code> <script src="<?php bloginfo( 'template_directory' ) ?>/jquery.js" type="text/javascript"></script> </code> However, scripts / styles should really be "enqueued" using <code> wp_enqueue_script(); </code> (see http://codex.wordpress.org/Function_Reference/wp_enqueue_script ) I would recommend taking a look at some other themes to see how they include thetheme files like this. Also the Codex page on Theme Development is a good place to start: http://codex.wordpress.org/Theme_Development
|
js and images files are not recognized - beginner
|
wordpress
|
I'm creating my own form based on stackexchange-url ("this") and I'd like to have a tag selector which is similar to the one on StackExchange. I can roll my own but I was wondering if something similar already exists. Thanks!
|
you can do that using JQuery autocomplete plugin and once you have included all of the needed JS files just add this code after your new post form <code> $terms = get_terms("post_tag"); $tags = ''; $count = count($terms); if ( $count > 0 ){ foreach ( $terms as $term ) { $tags .= '"'.$term->name.'", '; } $tags = substr($tags,0,-2); } echo ' <script> JQuery("#post_tags").autocomplete(['.$tags.'], { width: 320, max: 4, highlight: true, multiple: true, multipleSeparator: ", ", scroll: true, scrollHeight: 300 }); </script>'; </code> note: Now this is good if you only have a small number of tags, but if you have hundreds or thousands of tags then using an ajax solution is a must.
|
Tag selector like stackexchange?
|
wordpress
|
A followup to stackexchange-url ("my previous question") about my theme that was rejected for the WordPress.org theme directory : RECOMMENDED: No reference to the_post_thumbnail() was found in the theme. It is recommended that the theme implement this functionality instead of using custom fields for thumbnails. RECOMMENDED: No reference to add_custom_image_header was found in the theme. It is recommended that the theme implement this functionality if using an image for the header. How do I correct it? This is my function: <code> // thumbnail list function retImage($content){ $pattern="/<img.*?src=['|\"](.*?(?:[\.gif|\.jpg]))['|\"].*?[\/]?>/"; preg_match_all($pattern,$content,$match); if(empty($match[0][0])){ echo "<img src=\""; bloginfo('template_url'); echo "/images/thumbnail.png\" />"; }else{ echo $match[0][0]; } } </code> I used an image for the header by css, why do they say this: RECOMMENDED: No reference to add_custom_image_header was found in the theme. Embedded videos overlap sidebar. Please set the content_width variable In my the <code> functions.php </code> of my theme I did this: <code> if ( ! isset( $content_width ) ) $content_width = 992; </code> Why do they still give me that tip?
|
RECOMMENDED: No reference to the_post_thumbnail() was found in the theme. It is recommended that the theme implement this functionality instead of using custom fields for thumbnails. This is because you are not using <code> the_post_thumbnail() </code> in your theme, you are trying to get an image from the post content. This means there is no way for a user to explicitly set which image is shown wherever you are using <code> retImage() </code> . I would include the ability for <code> retImage() </code> to try use the thumbnail, something like: <code> // thumbnail list function retImage($content) { if( has_post_thumbnail() ) return the_post_thumbnail( 'thumbnail' ); $pattern="/<img.*?src=['|\"](.*?(?:[\.gif|\.jpg]))['|\"].*?[\/]?>/"; preg_match_all($pattern,$content,$match); if(empty($match[0][0])){ echo "<img src=\""; bloginfo('template_url'); echo "/images/thumbnail.png\" />"; } else { echo $match[0][0]; } } </code> You may also need to include <code> add_theme_support( 'post-thumbnails' ) </code> in your <code> functions.php </code> RECOMMENDED: No reference to add_custom_image_header was found in the theme. It is recommended that the theme implement this functionality if using an image for the header. If you theme has a header image, it is recommended to use the WordPress header image API, you can find out more about it here: http://codex.wordpress.org/Function_Reference/add_custom_image_header This would enable the user to change the header image via the admin (Appearance -> Custom Header) or something alike. Embedded videos overlap sidebar. Please set the content_width variable The <code> $content_width </code> should be a global variable: <code> global $content_width; $content_width = 960; </code>
|
Theme Review: post thumbnail, header image, content width
|
wordpress
|
Is it possible to hide the update messages for any users other than the main admin? We use WP as a CMS for clients and it's a bit annoying that a normal user has to read something like: WordPress 3.1.3 is available! Please update now.
|
Hide Update reminder - this hides update messages for all non-admin users
|
Hide update messages from non-admin users?
|
wordpress
|
OK, I got a custom post type with thumbnail enabled which adds the "featured images" panel to that post-type just fine, but in my template when I do <code> if ( has_post_thumbnail() ) { the_post_thumbnail(); } else { echo 'none'; } </code> it just shows 'none' on each one even though I have a featured image set... I have <code> add_theme_support('post-thumbnails',array('post','custom_post_type')); </code> so it's supported by the theme but <code> has_post_thumbnail </code> always returns false what's going on here??? My template is : archive-custom_post_type.php : <code> <?php $loop = new WP_Query(array( 'post_type' => 'clients', 'posts_per_page' => -1 )); if($loop){ ?> <ul> <?php while ( $loop->have_posts() ) : $loop->the_post(); ?> <li> <a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>" > <?php if ( has_post_thumbnail($post->ID) ) { the_post_thumbnail('thumbnail'); echo get_post($post->ID)->post_excerpt; } else { echo 'broken ::' . $post->ID; echo get_post($post->ID)->post_excerpt; } ?> </a> </li> <?php endwhile; //wp_reset_postdata(); ?> </ul> <?php } ?> </code>
|
In your Custom Post Type, do you <code> setup_postdata( $post ) </code> in your custom Loop? If not, <code> has_post_thumbnail() </code> might not be defined/available? EDIT: Try adding: <code> setup_postdata( $post ); </code> Right before: <code> $loop->the_post(); </code> And then see if <code> has_post_thumbnail() </code> returns <code> true </code> ? Or, try passing the <code> $post->ID </code> to your call to <code> has_post_thumbnail() </code> ? <code> has_post_thumbnail( $post->ID ); </code>
|
Featured Image VS Post_thumbnail -- has_post_thumbnail lies?
|
wordpress
|
I have a theme that I'm developing from an HTML template I have. I'm also designing an options page along with a plethora of plugins built-into the theme itself. I've chosen a tabbed interface and I'm trying to learn how to use WordPress' Settings API. I'm using a class structure for the theme's functions. The following is the declaration of registering settings and whatnot. <code> public function __admin_init() { register_setting( 'cncfps_twitter', 'cncfps_twitter_options', array( &$this, 'wp_cncfps_twitter' ) ); add_settings_section( 'cncfps_twitter', 'Twitter', array( &$this, 'wp_cncfps_twitter' ), 'cncfps' ); add_settings_field( 'cncfps_twitter_consumer_key', 'Consumer Key', array( &$this, 'twitter_consumer_key' ), 'cncfps', 'cncfps_twitter' ); add_settings_field( 'cncfps_twitter_consumer_secret', 'Consumer Secret', array( &$this, 'twitter_consumer_secret' ), 'cncfps', 'cncfps_twitter' ); add_settings_field( 'cncfps_twitter_apikey', 'API Key', array( &$this, 'twitter_apikey' ), 'cncfps', 'cncfps_twitter' ); } public function wp_cncfps_twitter() { // TODO: wut. ?!?! echo "what is this?"; } public function twitter_consumer_key() { echo "Hello"; } public function twitter_consumer_secret() { echo "World"; } </code> When I want to display the fields as shown stackexchange-url ("here"), I don't see a thing. The following is how I attempt to display them. I did follow a few tutorials but it's just not clicking in my brain for some reason. <code> settings_fields('cncfps_twitter'); do_settings_sections('cncfps_twitter'); </code>
|
The <code> do_settings_section() </code> function call needs to correspond to the <code> $optiongroup </code> argument you pass to <code> register_setting() </code> . To see how all of the myriad functions fit together, see page 10 of my tutorial . It does get fairly confusing trying to follow how the various functions string together. EDIT: You do appear to be using the option group properly. Can you clarify what is/is not "clicking" for you? You mention in the title that you want to use a tabbed interface, but the question text itself doesn't really indicate where exactly you're running into difficulty.
|
Theme Options page with tabs
|
wordpress
|
im using paginate_links function to create pagination on my custom post type archives, no matter what i do im hitting 404 errors when going to view page 2 (ie clicking to go on one page in the pagination trail). I've checked and researched and dont seem to be getting anywhere with it all. heres my before the loop query inside archive-MY_CUSTOM_POST_TYPE.php: <code> <?php global $wp_query; $args = array_merge( $wp_query->query, array( 'post_type' => 'sales', 'posts_per_page' => 1, ) ); query_posts( $args ); if (have_posts()) : while (have_posts()) : the_post(); </code> and lower down after the loops endif and above wp_reset_query i have <code> <?php endif; ?> <div class="clear"></div><!-- / clear --> <div class="pagination"> <?php global $wp_query, $wp_rewrite; $wp_query->query_vars['paged'] > 1 ? $current = $wp_query->query_vars['paged'] : $current = 1; $pagination = array( 'base' => @add_query_arg('page','%#%'), 'format' => '', 'total' => $wp_query->max_num_pages, 'current' => $current, 'show_all' => true, 'type' => 'plain' ); if( $wp_rewrite->using_permalinks() ) $pagination['base'] = user_trailingslashit( trailingslashit( remove_query_arg( 's', get_pagenum_link( 1 ) ) ) . 'page/%#%/', 'paged' ); if( !empty($wp_query->query_vars['s']) ) $pagination['add_args'] = array( 's' => get_query_var( 's' ) ); echo paginate_links( $pagination ); ?> </div><!-- / paginate --> </code> On my loop-index.php this works with no problem, but on a loop inside Custom Post Type its a no go, i have no clashes with duplicated slugs as i have read that this can be an issue, so im taking it that it is something to do with how im querying the posts before the loop, any pointers? regards Martin
|
If anyone else as the same issue my full workaround is: 1) in wp-admin > > settings > > reading set blog posts to show as 1. 2) then override this in loop-blog.php to posts_per_page => 10. 3) in your custom post type loop.php files set posts_per_page => 5. Remember these are the settings that i require, your needs may be different, bottom line is, set blog posts in wp-admin to 1, you can configure the other number of posts_per_page to your own needs now all is working good, a little hacky but at least it works, so my next question is > > > is this a wp bug?
|
Custom post type archive 404's with paginate_links
|
wordpress
|
I am trying to setup a couple of company websites on a WordPress Network install running on IIS7 and SQL Server 2008. Ultimately, the sites will work together like this: Site 1 - All requests for this companies site (regardless of country/region) will go here. This site will just show a map to the customer allowing them to pick the regional site most suited to them (initially North America, Europe and Australia/NZ). Site 2 - North American site Site 3 - European site Site 4 - Australia/NZ site Sites 2-4 will share the same design and a lot of the same content. Where they will differ is in relation to news, contact information etc. Ideally, the same user accounts would be able to make changes to all of the sites with the one login and post news to each of the different sites. My current thinking to achieve this is to install WordPress at sites.domain.com and to then enable the Network feature (using sub-domains). Each regional site will then be region.sites.domain.com. Then, using a domain mapping plugin (recommendations? any IIS specific considerations?) I will redirect the regional domain names to the regional sub-domains I have created. Does anyone have any recommendations for the best approach to this setup and any tips/tricks to make it better?
|
I am not entirely sure that it would work with sub-sub-domains. :) Most of your requirements (IIS aside) seem very manageable: consistent design would be easy to achieve with shared theme (or several child themes if required); users can be easily assigned to multiple sites, using single login and account (through editing site in Network Admin).
|
WordPress Network for regional company websites
|
wordpress
|
I am looking for the bugs about an hour but i can't find anything. Can you look and say why my theme option is not working? Problem: The theme option not saving. Even the default option is also blank. I checked the value via php my admin. Check the code in pastebin. And also how i can debug this kinds of problem? http://pastebin.com/TPV5YvD9 Thanks in advance.
|
A little tricky to say by looking at code alone. The first thing you need to check in such cases - if your validation function receives data from submitted form. <code> var_dump() </code> input and <code> die; </code> right after that to stop execution and prevent redirect back. Depending on what you get there (if anything) check back through Settings API functions. There are a lot of arguments to juggle with those and it is easy to mix then up.
|
Why my theme option not working?
|
wordpress
|
I've created a custom post type that makes use of custom fields over the default editor. I want to receive an email notification when an update to the post is made. The email does not have to show the diff (though it would be nice). I've tried Email Post Changes and it requires you to have "Revisions" enabled. I've tried enabling it and I am guessing, because I am not using the default editor, that it won't work without it. Any thoughts on either getting the plugin working or figuring out how to have an email sent when a custom post type is updated?
|
If you publish a post, also custom post type, the hook get form status and post_type - <code> {$new_status}_{$post->post_type} </code> - is active and you can use this hook for send an mail. As an examaple for publish music: <code> add_action('publish_music', 'fb_my_function'); </code> You can also send the revision inside the mail, the revision is only a other post type and can get from the database and add to the message of the mail. Maybe you can see the possibilities on my last plugin , send mails for comments and posts. An simple example for custom post type "Archive" <code> public $post_type_1 = 'archiv'; add_action( 'publish_' . $this -> post_type_1, array( $this, 'fb_my_function') ); public function fb_my_function( $post_id = FALSE ) { if ( $post_id ) { // get data from current post $post_data = get_post( $post_id ); //var_dump($post_data);exit; <-- see this for all content or use the id for get the revisons // get mail from author $user_mail = get_userdata( $post_data -> post_author ); // email addresses $to = '[email protected]' // email subject $subject = get_option( 'blogname' ) . ': ' . $post_data -> post_title; // message content $message = $post_data -> post_content . ' ' . PHP_EOL . get_author_name( $post_data -> post_author ) . ' ' . PHP_EOL . . get_permalink( $post_id ); // create header data $headers = 'From: ' . get_author_name( $post_data -> post_author ) . ' (' . get_option( 'blogname' ) . ')' . ' <' . $user_mail -> user_email . '>' . PHP_EOL; // send mail wp_mail( $to, $subject, $message, $headers ); } return $post_id; } </code>
|
Custom post type without editor or revisions - Notify on update?
|
wordpress
|
I am trying to write a function for my functions.php file. I has to do the following; loop through search results and check the template if the template is 'landing.php' add it to ad array use the id's collected in the array to exclude these pages from the search results. I found some code on the Wordpress Codex forum, I have added a little bit myself but unfortunately don't know what i'm doing... <code> function filter_where($where = '') { global $wpdb; // do I need this? if ( is_search() ) { if(is_page_template('landing.php')) { echo 'yes!'; } // ids collected here $exclude = array(286); for($x=0;$x<count($exclude);$x++){ $where .= " AND ID != ".$exclude[$x]; } } return $where; } add_filter('posts_where', 'filter_where'); </code>
|
The filter you are using <code> posts_where </code> affects the creation of SQL query, so by definition it is executed before query runs and you have any search results. So you cannot loop through results at this point, what you can do is retrieve or hardcode list of unwanted items from elsewhere and use them to modify query. Update Ok, this is faster to code than trying to solve with comments. This is probably not perfect but should be good starting point for what you want: <code> add_action('pre_get_posts','exclude_pages'); function exclude_pages( $query ) { if( !empty( $query->query_vars['s'] ) ) { $pages = get_posts(array( 'post_type' => 'page', 'meta_query' => array( array( 'key' => '_wp_page_template', 'value' => 'landing.php', )), )); $exclude = array(); foreach( $pages as $page ) $exclude[] = $page->ID; $query->set('post__not_in', $exclude); } } </code>
|
Can anyone offer any help with this function?
|
wordpress
|
I have a super old blog that I upgraded from 2.0.7 to 3.1 by upgrading over multiple versions. One of my biggest concerns was losing all the link juice from my legacy URLs but they were clearly made at a time when I hadn't considered how the URLs would need to change. To my surprise I found that changing my permalink structure from /articles/%category%/%postname%/ to /id/%post_id%/%postname%/ went really smoothly as WordPress automatically looked up the appropriate URL -- which is great. But I'm wanting to know since Ive changed link structures, does it send 301 header messages so I dont lose link juice from 5+ year old links, or is there a way for me to force WordPress to do this for old URLs? Thanks!
|
Yes, WordPress will do a "301: Moved Permanently" to the "real" URL. WordPress calls this "canonical". When it hits a 404, WordPress will do a lookup on the URL fragments and attempt to find a post / page with that slug. If it finds one - it will do a <code> wp_redirect() </code> to the proper permalink of the post.
|
Does WordPress send a 301 header message when you change permalink structures?
|
wordpress
|
How do we get posts where the meta key does not exist in a post. I have created a meta_key video. and i want to be able to get some posts with WP_Query where custom field video does not exist or is blank. <code> $fsquery = new WP_Query( array ( 'posts_per_page' => 1, 'featured' => 'yes', 'meta_key'=>'video', 'meta_value'=>'' ) ); </code> this is not working.
|
There's actually a better solution that will (hopefully) be rolling out in WordPress 3.4 -- you can run the patch as a hotfix now if you'd like, but here's the TRAC link for the patch: http://core.trac.wordpress.org/ticket/18158 With this, you can do ... <code> $my_query = new WP_Query( array( 'meta_query' => array( array( 'key' => 'foo', 'compare' => 'NOT EXISTS' ) ) ) ); </code> or, swap it out for 'compare' => 'EXISTS' instead if you like. -George
|
querying with custom meta field with meta_query
|
wordpress
|
Using two plugins on one page; promoslider & events list. Tried to produce desired output. <code> +-----------------+ | slider output | +-----------------+ Text related to events list +-----------------+ | events output | +-----------------+ </code> Code listed below did not produce expected results. <code> // original code [promoslider width="600px"] Text related to events list [events_list] </code> Instead produced output out of order. <code> Text related to events list +-----------------+ | slider output | +-----------------+ +-----------------+ | events output | +-----------------+ </code> Encapsulated short codes in html table seems resolve the issue <code> // Table code <table> <tr><td>[promoslider width="600px"]</td></tr> <tr><td>Text related to events list</td></tr> <tr><td>[events_list]</td></tr> </table> </code> Is there a better way to display multiple plugins on the same page?
|
The promo slider on your demo site has the class <code> .random </code> , and in your <code> style-Red.css </code> file you give it a <code> float: left; width: 200px </code> . But because your promo slider is actually 600 pixels wide, you have 400 pixels that overlap with what follows: your text. So I don't think this is a WordPress issue but a CSS issue.
|
Better way to display multiple plugin output on the same page?
|
wordpress
|
I'm building a quite complex custom post type structure and I would need some help regarding my metaboxes. What I want to do: Thank's to the <code> have_fields_and_multi() </code> function, the user enters data in simple text input fields (with a "Add new" button) The values from the previous text inputs should be used to build a <code> select </code> dropdown in another metabox. To make it simple, here is a mockup (also attached to this post): http://idzr.org/0c95 I have the first part working, it's easy. But I can't figure out how to make the second part to work. If I use a <code> while($mb->have_fields_and_multi('aaa')) </code> in another <code> while($mb->have_fields_and_multi('bbb')) </code> the page is infinite (the loop doesn't end. If I use <code> foreach </code> I have other problems. Do you have an idea about how I can achieve this ? Thanks!!!
|
Ok, I finally managed to solve that by myself. It is possible thanks to : Create the first field : <code> <?php while($mb->have_fields_and_multi('types')): $mb->the_group_open(); $mb->the_field('type'); ?> <input type="text" id="<?php $mb->the_name(); ?>" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>" /> <a href="#" class="dodelete button">Remove</a> <?php $mb->the_group_close(); endwhile; ?> <a href="#" class="docopy-types button" style="float: left">Add new</a> <a href="#" class="dodelete-types button" style="float: right">Delete all</a> </code> Create the second batch of fields while using <code> foreach </code> to get the data from the first fields and put that in a <code> select </code> : <code> <?php while($mb->have_fields_and_multi('details')): $mb->the_group_open(); $mb->the_field('detail_select'); ?> <select name="<?php $mb->the_name(); ?>"> <option value="">Choose...</option> <?php foreach ($meta['types'] as $types) { ?> <option value="<?php echo $types['type']; ?>"<?php $mb->the_select_state($types['type']); ?>><?php echo $types['type']; ?></option> <?php } ?> </select> <?php $mb->the_field('detail_title'); ?> <label>Description</label> <input type="text" id="<?php $mb->the_name(); ?>" name="<?php $mb->the_name(); ?>" value="<?php $mb->the_value(); ?>" /><br /> <a href="#" class="dodelete button">Remove</a> <?php $mb->the_group_close(); endwhile; ?> <a href="#" class="docopy-estate_details button">Add new</a> <a href="#" class="dodelete-estate_details button">Delete all</a> </code>
|
Using WPAlchemy metabox values in another metabox
|
wordpress
|
I have created extra field that user can edit on their 'Your Profile' page. The extra field also available on WordPress register page. What I want to ask is, how to add the field to User > Add new page ? So, when admin creates a user, admin also input the user's extra field
|
With no hooks on that page (User > Add new page) other then <code> user_new_form_tag </code> its not possible to add new fields unless you hack the core file <code> wp-admin/user-new.php </code> . You could try adding that extra field by adding in in JQuery and processing it when the <code> $_post['action'] == 'adduser' </code> but that wont be very good practice.
|
Add extra field when admin create user
|
wordpress
|
I have this CSS setup for my blog posts meta information. But there are certain categories where I would like to use another image in the same spot and not display the meta information. I'm not quite sure how to do it. <code> .entry-meta { background: url("images/dish_blogtitle.png") no-repeat scroll center center transparent; color: #666666; float: left; font-size: 13px; font-style: italic; height: 100px; line-height: 18px; margin-left: -125px; margin-top: 5px; position: relative; text-align: center; top: -80px; width: 100px; } </code>
|
Have you checked the classes on your <code> <body> </code> element? It depends on the theme but WordPress has a function body_class() that dynamically adds a bunch of useful classes in there. It may look like this: <code> <body class="archive category category-news category-2 two-column content-sidebar"> </code> As you can see it is a powerful helper as you can easily accomplish complex style changes by prepending your definitions with these classes. In your case it could be: <code> .category-something .entry-meta { /* whatever style changes you need */ } </code> If there is no such awesomeness in your <code> <body> </code> element then you can add it there yourself very easily: <code> <body <?php body_class(); ?>> </code> The stackexchange-url ("answer") provided by @xLRDxREVENGEx is certainly valid and points in the right direction. It's certainly worth (re)thinking what approach is the right one for your use case. Hope this helps!
|
conditional function to change post-meta background image
|
wordpress
|
My new site was initially set up with an IP address (say http://123.123.12.12/ ). I later changed the siteurl and homeurl to my domain (say xyz.com). I also pointed the domain to the IP address so I don't lose out on the indexing in search engines. But now whenever I click on any of the links in the home page, it redirects back to http://123.123.12.12/ instead of going to http://123.123.12.12/newpage/ The anchor tag shows the URL as http://xyz.com/newpage/ Any relative URLs on any other pages work fine. But otherwise all links (from the menu) redirect to the home page. To summarize, any urls saying http://xyz.com/somepage redirect to home page Any ideas what I might be missing? Thanks. P.S. I changed the siteurl and homeurl in the database directly. Do I need to change it on the Wordpress Settings page as well?
|
Clear your permalinks by going to the permalinks page usually all it takes it just visiting it. Also clear your cache and flush your dns settings. Also make sure to clear any WordPress plugins that use cache. Check those and report back
|
Changing siteurl and homeurl - internal links redirect to home page?
|
wordpress
|
So let's say I run a TV show blog. One day, the show releases to the public a set of 10 screencaps from an upcoming episode. I post that on my blog, either as a post with multiple images, or specifically as a "gallery" post -- either way, readers can view all the image attached to that post as a gallery. Then, several days and several posts later, they release 10 more screencaps from that same upcoming episode. I want to make a separate post rather than bump the old one, but I also somehow want to be able to display all screencaps (20) from that particular episode in a single gallery. Or at least what would look like a single gallery. Possible? (Preferably without NextGEN or other plugins... trying to accomplish as much as I can using WordPress' native capabilities before stacking plugins.)
|
With the default <code> [gallery] </code> shortcode there is no easy way to combine different galleries into one. You can either specify two different galleries: one of the current post and one of another post, specified by post ID: <code> [gallery] [gallery id=42] </code> Or you can create a gallery by explicitly specifying all the attachment IDs: <code> [gallery include="23,39,45"] </code> Specifying multiple post IDs will not work because <code> gallery_shortcode() </code> uses <code> get_children() </code> to get the attachments, which uses <code> get_posts() </code> , which uses the standard <code> WP_Query </code> class, and this only allows a numeric <code> post_parent </code> value . However , we can exploit the fact that there is a filter at the top of <code> gallery_shortcode() </code> , that allows plugins to override the default gallery layout. The following example checks for an <code> id </code> parameter with multiple IDs (or the special keyword <code> this </code> ), gets all the attachments of these posts, and puts them in an explicit <code> include </code> attribute which is used to call the gallery function again. This allows you to combine different galleries like this: <code> [gallery id=this,8] </code> . You can extend this idea to support other attributes too. <code> add_filter( 'post_gallery', 'wpse18689_post_gallery', 5, 2 ); function wpse18689_post_gallery( $gallery, $attr ) { if ( ! is_array( $attr ) || array_key_exists( 'wpse18689_passed', $attr ) ) { return ''; } $attr['wpse18689_passed'] = true; if ( false !== strpos( $attr['id'], ',' ) ) { $id_attr = shortcode_atts( array( 'id' => 'this', 'order' => 'ASC', 'orderby' => 'menu_order ID', ), $attr ); $all_attachment_ids = array(); $post_ids = explode( ',', $id_attr['id'] ); foreach ( $post_ids as $post_id ) { if ( 'this' == $post_id ) { $post_id = $GLOBALS['post']->ID; } $post_attachments = get_children( array( 'post_parent' => $post_id, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => $id_attr['order'], 'orderby' => $id_attr['orderby'], ), ARRAY_A ); $all_attachment_ids = array_merge( $all_attachment_ids, array_keys( $post_attachments ) ); } $attr['include'] = implode( ',', $all_attachment_ids ); $attr['id'] = null; } return gallery_shortcode( $attr ); } </code>
|
Any way to "combine" galleries or show multiple galleries as one?
|
wordpress
|
I'm dynamically creating a custom post type in code (not in the editor) and I have an image I want to attach to my custom post type as a post thumbnail, and have it resized, etc. How do I do that. I'm successfully creating the custom post type using wp_insert_post(). I've looked at wp_save_image(), wp_save_image_file(), load_image_to_edit(), get_attached_file() and others, but they all seem to require an image in $_POST. I also looked at wp_insert_attachment() and update_attached_file() which seemed promising, but were not image centric.
|
WP 3.1 introduces <code> set_post_thumbnail() </code> function, that sets attachment (that you will need to create first, you seem to be on right track with <code> wp_insert_atachment() </code> ) as thumbnail for the post.
|
how to attach an image to a custom post type in wordpress using just code
|
wordpress
|
I've just installed a fresh WordPress setup on Windows Server 2008 Web R2 (IIS7) with SQL Server Express and WordPress 3.1. I completed the install successfully and logged into the admin section to start the activation of the WordPress network (using sub-domains). Having edited the wp-config file, I added the code WordPress generated to both wp-config (Network specific) and web.config (Rewrites). Since adding these changes, each time I try to login to WordPress, I just get loop'd straight back to the login page. I've tried to following so far: Comment out the network specific changes in wp-config and revert the rewrite rules to standard WordPress ones (Didn't work). Checked IIS Admin for any re-writes already in place (None) Details of wp-config and web.config below: <code> wp-config: define('WP_ALLOW_MULTISITE', true); define( 'MULTISITE', true ); define( 'SUBDOMAIN_INSTALL', true ); $base = '/'; define( 'DOMAIN_CURRENT_SITE', 'svr-web-csrms' ); define( 'PATH_CURRENT_SITE', '/' ); define( 'SITE_ID_CURRENT_SITE', 1 ); define( 'BLOG_ID_CURRENT_SITE', 1 ); </code> web.config: http://pastebin.com/8xctXizE Update: I have had a thought. From reading this here : Note that per the Settings Requirements you cannot switch from Sub-folder to Sub-domain > when running on 127.0.0.1 or localhost. This can potentially cause an endless loop of > reauth=1 on your root site due to cookie handling. I may have an issue due to the fact I am using an internal address. I'll set WordPress up with a proper domain and come back.
|
This sounds like your domain doesn't match the cookie being generated. It may not have anything to do with the IP. <code> define( 'DOMAIN_CURRENT_SITE', 'svr-web-csrms' ); </code> I would expect an actual domain or something, like this. <code> define( 'DOMAIN_CURRENT_SITE', 'subdomain.mysite.tld' ); </code> I tried to look at your web.config - but it appears that the URL is now broken.
|
WordPress Network on IIS7/SQL Server - Rewrite Issues
|
wordpress
|
I want to get all the data with the meta key of "project_id" from post meta table. I wrote a query, it should work in thoery, but I have no way to see what I get, and inject this query to my plugin doesn't generate anything. Please take a look at this query, and help me understand if it is correct, what's the formate of the outcome, How can I echo it to see what I get: <code> function mp_all_ids( ){ global $bp, $wpdb, $post; $query = <<<QUERY SELECT project_id.post_id FROM $wpdb->postmeta project_id LEFT JOIN $wpdb->postmeta height on height.post_id = project_id.post_id and height.meta_key = 'height' LEFT JOIN $wpdb->postmeta width on width.post_id = project_id.post_id and width.meta_key = 'width' WHERE project_id.meta_key = 'project_id' ORDER BY project_id.meta_value+(0) ASC QUERY; $data = $wpdb->get_results( $query ); return apply_filters( 'mp_ids', $data ); } </code> Edit: the var_dump gets the following result: <code> array(3) { [0]=> object(stdClass)#457 (1) { ["post_id"]=> string(3) "385" } [1]=> object(stdClass)#458 (1) { ["post_id"]=> string(3) "451" } [2]=> object(stdClass)#377 (1) { ["post_id"]=> string(3) "453" } } </code> How can I access the 3 strings in each object?
|
First of all, you should look into using WP_Query for this: http://scribu.net/wordpress/advanced-metadata-queries.html Secondly, to see the results, just do a var_dump() before the return: <code> echo '<pre>'; var_dump( $data ); </code>
|
How to test the outcome of a wpdb query?
|
wordpress
|
My Old Question: I made a Theme with rotating banner, common thing. So I want a way for users to select images. I think instead of implementing my own upload, I think its better to allow users to use the Media Library, how do I do that? The New One So far, I have something like below functions.php <code> // init wordpress media upload stuff ... if (is_admin() && isset($_GET['page']) && $_GET['page'] == 'elem_opts') { wp_enqueue_style('thickbox'); wp_enqueue_script('media-upload'); wp_enqueue_script('thickbox'); wp_register_script('elem_adm_js', get_bloginfo('template_directory') . '/js/admin.js', array('jquery', 'media-upload', 'thickbox')); wp_enqueue_script('elem_adm_js'); } </code> admin.js <code> jQuery(document).ready(function($) { $('#elem_upload_logo').click(function() { tb_show('', 'media-upload.php?type=image&amp;TB_iframe=true'); return false; }); window.send_to_editor = function (html) { imgurl = $('img', html).attr('src'); $('input[name=elem_opts[h_image]]').val(imgurl); tb_remove(); } }); </code> The media library upload thickbox pops up, I can click select files, but when I try to upload them nothing happens. In Firebug I can see the following:
|
Here are 3 links to get you started, your question should be more clear, do you want this to work like twentyten's header, using a custom theme options field, a category? stackexchange-url ("How to use media upload on theme option page?") stackexchange-url ("How can I add an image upload field directly to a custom write panel?") stackexchange-url ("Attaching media to custom posts without editor") stackexchange-url ("Creating an Image-Centric Custom Post Type?")
|
Plugging into the Media Library to upload images (NOT associated with any post)
|
wordpress
|
I have created a custom content type (and taxonomy) for my theme that will mostly replace the default post type. I know as for singles, i can create a template single-customtype.php to handle this but what about for everything else? what about http://mywebsite.com/posttype (is my only option forcing my theme user to create a page and select a template?) what about search, 404, archive and widgets? Would i have to customize them all. I can tell i am missing something huge here but i cant put my finger on it
|
for search you might need to adjust query to include your custom post type, <code> search.php </code> template or around that; 404 page is completely unrelated to post types; for archive you use <code> archive-customtype.php </code> template; sidebars/widgets are completely unrelated to post types.
|
handling templates and widgets for custom content types
|
wordpress
|
Is there a way I can make text widgets accept PHP? Perhaps something I can add in to functions.php? I'm redesigning my site, and I was wondering why I didn't use widgets at all in my current design, but then I realized it was because I use a lot of PHP in there. For example, one of the "widgets" is a tabbed content area, so I've got the HTML and JavaScript shell for the tabs, but then inside the tabs, I've got PHP calls for the most popular posts, the most recent posts, and the most recent comments. I can't do that with existing widgets. Obviously I could use a plugin, but I'm trying to go light on plugins where possible. Is there something I can just add to functions.php?
|
PHP in text widgets involves using eval(), which is evil. If you know PHP, stick with static sidebars.
|
Anything I can add to functions.php to make text widgets accept PHP?
|
wordpress
|
I'm trying to add a custom button or two to the TinyMCE rich text editor. The tutorials I've seen so far are either outdated or explain how to do it with a custom plugin. How can I do this without creating a plugin, perhaps in the <code> functions.php </code> file instead? To be specific, I want to add a "h2" button that will add in a <code> <h2></h2> </code> into the body.
|
It is almost code golf, but this is the smallest piece of code that I could up with that will create a button on the Visual editor to turn the current paragraph in a <code> <h2> </code> block. <code> add_filter( 'tiny_mce_before_init', 'wpse18719_tiny_mce_before_init' ); function wpse18719_tiny_mce_before_init( $initArray ) { $initArray['setup'] = <<<JS [function(ed) { ed.addButton('h2', { title : 'H2', image : 'img/example.gif', onclick : function() { ed.formatter.toggle( 'h2' ); } }); }][0] JS; return $initArray; } add_filter( 'mce_buttons', 'wpse18719_mce_buttons' ); function wpse18719_mce_buttons( $mce_buttons ) { $mce_buttons[] = 'h2'; return $mce_buttons; } </code> It is based on a TinyMCE code sample and uses a trick to pass a function as the <code> setup </code> variable (which will not be needed in 3.2 anymore). To add a button to the HTML editor you can extend the much simpler "quicktags" code by enqueuing this extra Javascript file: <code> jQuery( function( $ ) { var h2Idx = edButtons.length; edButtons[h2Idx] = new edButton( 'ed_h2' // id ,'h2' // display ,'<h2>' // tagStart ,'</h2>' // tagEnd ,'2' // access ); var h2Button = $( '<input type="button" id="ed_h2" accesskey="2" class="ed_button" value="h2">' ); h2Button.click( function() { edInsertTag( edCanvas, h2Idx ); } ); // Insert it anywhere you want. This is after the <i> button h2Button.insertAfter( $( '#ed_em' ) ); // This is at the end of the toolbar // h2Button.appendTo( $( '#ed_toolbar' ) ); } ); </code>
|
Add button to TinyMCE bar without creating a plugin
|
wordpress
|
I've got a custom database table with lots of data that I'd like to query several times from a custom template file I've built. Say the db table looks like this: <code> id name city zip 23 Mike New York 123 54 Peter Los Angeles 456 78 Steven Chicago 789 79 Tom Los Angeles 450 </code> And I want to run at least four queries, looking kinda like this: <code> SELECT * FROM table LIMIT $paginated,10 (this is presenting all of the names) SELECT id,city FROM table GROUP BY city (this will be a dropdown list of all the citys) SELECT zip FROM table WHERE city = "New York" GROUP BY zip </code> That's only three queries but anyway - is it more effective to just run one big query with all of the data into an array, and then just loop that array whenever needed, or is it better to perform actual db queries? I'm using $wpdb-> get_results for every query of course, is this harder for the server to work with? I mean, using WP code to perform DB queries should result in more PHP code for the compiler to translate, am I wrong?
|
The <code> $wpdb </code> object is based on ezSQL , it does not add much overhead, so I would not worry about that. Opening a second connection to the database yourself will probably lead to more overhead than using the <code> $wpdb </code> functions. The three queries you have described are ideal queries to do in the database (a small result set from a large dataset), so you should not emulate them in PHP. Be sure to add some indexes to the table to speed the queries up (one on <code> city </code> at least). Use the <code> EXPLAIN </code> feature of MySQL to know what the database is doing to execute your query and how you can help it.
|
Most effective use of DB querys
|
wordpress
|
Every time someone edits our blog the content is displaying all wrong. It looks perfect in the wysiwyg editor but when you publish the page the content is completely wrong (pictures displayed next to each other etc. How to prevent this? example link
|
This is because the images are defined as floating to the left. To solve this, you can add a <code> clear: both </code> to the <code> <h4> </code> elements (it probably won't hurt to do this in the stylesheet - will there be a situation where you need a title that exists next to a float?).
|
content gets scrambled
|
wordpress
|
I'm using a jquery ajax call to get certain data from wpdb and I'm getting the following message: <code> <b>Fatal error</b>: Call to a member function get_results() on a non-object in <b>C:\wamp\www\maps_en2\markers.php</b> on line <b>15</b><br /> </code> This is the call: <code> $.ajax({ type: "POST", url: "markers.php", data: ({'southWestLat' : southWestLat , 'southWestLng' : southWestLng , 'northEastLat' : northEastLat , 'northEastLng' : northEastLng}), success: function(msg){ alert( msg ); } }); </code> And this is the called code - markers.php: <code> <?php global $wpdb; $sql = "SELECT user_id, lat, lng FROM coordinates WHERE lat>".$_POST["southWestLat"]." and lat<".$_POST["northEastLat"]." and lng>".$_POST["southWestLng"]." and lng<".$_POST["northEastLng"]; $rows = $wpdb->get_results($sql, OBJECT_K); ... ?> </code> What's strange is that when the php code was on the same file as the javascript (and instead of the parameters 'southWestLat' etc, I used numbers, then it worked. I should state that the jquery is in a php file under twentyten theme folder but markers.php is under the root directory (couldn't use it when it was in the theme for some reason).
|
This will not work because you call <code> example.com/markers.php </code> directly, and that file does not load anything from WordPress, like the <code> $wpdb </code> object. You can include <code> wp-load.php </code> , but this might break if you move the WordPress installation to somewhere else. To be more in line with how Ajax calls in WordPress should be made, you should write it as a hook for <code> wp_ajax_[action] </code> . See stackexchange-url ("my introduction to Ajax in WordPress") for more details.
|
Can't use get_results() in ajax query
|
wordpress
|
I have seen that Wordpress uses <code> %category% </code> like strings to create url templates. Is there an easy way to allow such mechanism in a plugin? For example in the plugin's settings page user specifies an option <code> `<a href=%my_url%>Click here</a>` </code> And in my plugin I replace <code> %my_url% </code> with an actual URL before <code> echo </code> ing it. Is there a function/mechanism in wordpress that I can use to achieve this?
|
You don't need anything WordPress specific here. Use PHP's str_replace to replace tokens entered by users in the settings. In your plugin code, wherever you are echoing the setting value wrap it in str_replace with the value you want to replace %my_url% with. <code> echo str_replace("%my_url%", $real_url_value, $setting_text); </code>
|
Can I use %category% like Templates in my Plugin?
|
wordpress
|
I've got an issue, writing a correct rewrite rule. Basically, here are the examples of the url I want : <code> /myPage/mySuPage </code> Then the same with pagination <code> /myPage/mySuPage/page/3 </code> Then, the basic page, with 2 params, no pagination <code> /myPage/mySuPage/param1/param2 </code> Then, the one with 2 parameters and the pagination <code> /myPage/mySuPage/param1/param2/page/3 </code> More or less, i have it working with differents rules for each case, but if I put them in a row, nothing works. Here are the rules I wrote : <code> add_rewrite_rule( 'myPage/mySuPage/([^/]*)/([^/]*)/?', 'index.php?pagename=myPage/mySuPage&param1=$matches[1]&param2=$matches[2]', 'top' ); add_rewrite_rule( 'myPage/mySuPage/([^/]*)/([^/]*)/page/([0-9]{1,})?', 'index.php?pagename=myPage/mySuPage&param1=$matches[1]&param2=$matches[2]&pageds=$matches[3]', 'top' ); add_rewrite_rule( 'myPage/mySuPage/(.+?)(/page/([0-9]+))?/?$', 'index.php?pagename=myPage/mySuPage&param1=$matches[1]&param2=$matches[2]', 'top' ); </code>
|
Your first two rewrite rules do not end with <code> $ </code> , which indicates that the URL should stop there. So <code> myPage/mySuPage/param1/param2/page/3 </code> would still be matched by the first pattern, because it can just ignored the <code> /page/3 </code> part at the end. The next rewrite rules will then never be used. With stackexchange-url ("my Rewrite analyzer plugin") I was able to simplify your rewrite rules to these two: one without params and just optional paging, and one with params and optional paging. Combining these two into one did not work because the optional params woud "eat" the paging part. <code> add_rewrite_rule( 'myPage/mySuPage(/page/([0-9]+)?)?/?$', 'index.php?pagename=myPage/mySuPage&pageds=$matches[2]', 'top' ); add_rewrite_rule( 'myPage/mySuPage/([^/]*)/([^/]*)(/page/([0-9]+)?)?/?$', 'index.php?pagename=myPage/mySuPage&param1=$matches[1]&param2=$matches[2]&pageds=$matches[4]', 'top' ); </code>
|
add_rewrite_rule and pagination issue
|
wordpress
|
I have a custom post type set up like: <code> add_action('init', 'portfolio_register'); function portfolio_register() { $labels = array( 'name' => _x('Photos', 'post type general name'), 'singular_name' => _x('Portfolio Item', 'post type singular name'), 'add_new' => _x('Add New', 'portfolio item'), 'add_new_item' => __('Add New Portfolio Item'), 'edit_item' => __('Edit Portfolio Item'), 'new_item' => __('New Portfolio Item'), 'view_item' => __('View Portfolio Item'), 'search_items' => __('Search Portfolio'), 'not_found' => __('Nothing found'), 'not_found_in_trash' => __('Nothing found in Trash'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'publicly_queryable' => true, 'show_ui' => true, 'query_var' => true, //'menu_icon' => get_stylesheet_directory_uri() . '/article16.png', 'rewrite' => true, 'capability_type' => 'post', 'hierarchical' => false, 'menu_position' => 4, 'taxonomies' => array('post_tag','category'), 'supports' => array('title','editor','comments','trackbacks','revisions','custom-fields','page-attributes','thumbnail', 'excerpt', 'tags') ); </code> It pulls all of the meta boxes in and everything fine for the single page. On the home page I query from the Featured category like so : Edit based on suggestion from spartacus <code> <?php $args = array('category_name' => 'featured', 'post_type' => array ('post','Photos'), 'posts_per_page' => 20); $the_query = new WP_Query($args); while ($the_query->have_posts()) : $the_query->the_post();?> <?php //getImage(1); ?> <div class="featuredSlide"> <a href="<?php the_permalink(); ?>"> <img src="<?php bloginfo('template_url'); ?>/scripts/timthumb.php?src=<?php echo get_first_attachment() ?>&w=500&h=500&a=b&zc=1&q=80" alt="<?php the_title(); ?>" /></a> <?php the_title(); ?> </div> <?php endwhile; ?> </code> This works fine with normal posts I make but none of the posts in the custom post type category will be pulled into this featured category query. Can anyone see what is going wrong or have suggestions of what I should look for ?
|
You need to add your custom post type to your WP_Query call: <code> $args = array('category_name' => 'featured', 'post_type' => array ('post','Photos'), posts_per_page' => 20); $the_query = new WP_Query($args); //continue with your loop </code>
|
Categories not working as expected with custom post type
|
wordpress
|
I have around 140 post in database but wordpress admin page shows just 50 post. How could I let wordpress shows all the posts in database? Thanks
|
Are you sure those aren't pages, drafts, trashed, revisions or attachments ? run this in PHPMYAdmin and see how many results you get <code> select * from wp_posts where post_status='publish' </code>
|
Wordpress doesn't show all posts in database
|
wordpress
|
I installed a Wordpress plugin and I'm getting the following error. The weird thing is I checked the plugins' source and I really don't understand why it would need those scripts. [30-May-2011 11:10:03] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php/extensions/no-debug-non-zts-20060613/eaccelerator.so' - /usr/lib/php/extensions/no-debug-non-zts-20060613/eaccelerator.so: cannot open shared object file: No such file or directory in Unknown on line 0 [30-May-2011 11:10:03] PHP Warning: PHP Startup: Unable to load dynamic library '/usr/lib/php/extensions/no-debug-non-zts-20060613/ffmpeg.so' - /usr/lib/php/extensions/no-debug-non-zts-20060613/ffmpeg.so: cannot open shared object file: No such file or directory in Unknown on line 0 This is the plugin: http://wordpress.org/extend/plugins/upprev-nytimes-style-next-post-jquery-animated-fly-in-button/
|
Those messages have nothing to do with your plugins or WordPress. Those are from you PHP.ini file trying to load extensions that are either not there or in the wrong directory. Usually caused when you upgrade version of PHP and don't change the extension directory. If you have shell access run <code> $ php -V </code> to get more info. If your on managed hosting call your host they can and will fix for you.
|
eaccelerator PHP error
|
wordpress
|
I need to do a <code> WP_Query </code> with a <code> LIKE </code> on the <code> post_title </code> . I started with this regular <code> WP_Query </code> : <code> $wp_query = new WP_Query( array ( 'post_type' => 'wp_exposants', 'posts_per_page' => '1', 'post_status' => 'publish', 'orderby' => 'title', 'order' => 'ASC', 'paged' => $paged ) ); </code> But what I actually want to do looks like this in SQL: <code> $query = " SELECT * FROM $wpdb->posts WHERE $wpdb->posts.post_title LIKE '$param2%' AND $wpdb->posts.post_type = 'wp_exposants' ORDER BY $wpdb->posts.post_title "; $wpdb->get_results($query); </code> The output prints the results i'm excpecting, but I use the regular <code> <?php while ( $wp_query->have_posts() ) : $wp_query->the_post(); ?> </code> to display the results. And that is not working with <code> $wpdb->get_results() </code> . How can I achieve what I described here?
|
I would solve this with a filter on <code> WP_Query </code> . One that detects an extra query variable and uses that as the prefix of the title. <code> add_filter( 'posts_where', 'wpse18703_posts_where', 10, 2 ); function wpse18703_posts_where( $where, &$wp_query ) { global $wpdb; if ( $wpse18703_title = $wp_query->get( 'wpse18703_title' ) ) { $where .= ' AND ' . $wpdb->posts . '.post_title LIKE '' . esc_sql( like_escape( $wpse18703_title ) ) . '%''; } return $where; } </code> This way you can still call <code> WP_Query </code> , you just pass the title as the <code> wpse18703_title </code> argument (or change the name to something shorter).
|
WP_Query with "post_title LIKE 'something%'"?
|
wordpress
|
I have a business site hosted on wordpress. Now, we are planning to have a store locator page. We are looking to build something similar to Apple store locator . My question is how do we go about creating this? Should I build a plugin or is it possible to embed a php application and have the same "look & feel" as the site? Or can I make use of custom post types? Please note that, the address info, working hours and images will be stored on the DB.Ideas and suggests are welcome. Thanks in advance.
|
You should be able to do this completely with custom post types. Most of the structured info can go in custom fields. For the geographical info you can read "stackexchange-url ("Optimizing a Proximity-based Store Location Search on a Shared Web Host?")", where I explained how to store the coordinates of the stores not only in the <code> postmeta </code> table but also in a separate indexed table to allow quick lookups. Another user of this site packaged this functionality in his Geo Data Store plugin , you can also take a look at that.
|
Building a store locator with google maps
|
wordpress
|
I need to move a WordPress site hosted on Dream Host to the companies servers. To do so I used the built in import and export feature that comes with WordPress (using a WordPress export file). However, it did not copy over images from the site, and didn't preserve the featured images. Using import/export, is it possible to copy over the images and featured images as well? If not, is there another method I could use?
|
Ensure that the NEW site is already running the same Theme, and all appropriate Plugins. Generate your export file from your OLD site, ensuring that you export "all content". Import the file into the NEW site, ensuring that you enable/check the option to download/import all attachments. (It is on the same import step during which you assign Post authors.) Notes: If your NEW site isn't running a Theme that has Post Thumbnail support enabled, you might not get your "featured image" post meta exactly as expected. (Likewise, if your OLD site has Custom Post Types, Custom Taxonomies, or Post Format support enabled, you will need to ensure that these features are enabled on the NEW site, in order to ensure a proper import of these data.) If you don't enable the option (disabled by default) to download/import attachments, then attachments will be instead linked to the OLD site.
|
How to migrate a WordPress installation from one site to another, including all images?
|
wordpress
|
I want to get a groups of data from postmeta table. The postmeta table have 4 colums, meta_id, post_id, meta_key,meta_value. Each post_id has a list of meta_keys. I want to run a query and get a result of <code> arry(number of results)( [0]=>object(stdClass)#1( [post_id] => 123, [key1] => x, [key2] => y, [key3] => z ) [1]=>=>object(stdClass)#2( [post_id] => 456, [key1] => x, [key2] => y, [key3] => z ) ) </code> How to do it?
|
I was wondering the same myself recently and this is the best solution I've come up with. First, declare a really simple class in your functions.php <code> class Object { var $data = array(); public function __set($name, $value) { $this->data[$name] = $value; } public function __get($name) { return $this->data[$name]; } } </code> This is the generic object we will use to store everything Next, we will connect to the SQL database and pull all the data we need. In this case I'm doing a very generic query to select ALL the posts in the database and attach their relevant data. If you've got a large DB, you probably need to narrow this query down a little with some conditions on the post such as adding: <code> "WHERE post.post_type = 'graph'" </code> to the SQL query, but I'm not sure exactly what you narrow down the results by, so we'll stay generic for demo purposes... <code> global $wpdb; $query = "SELECT post.id as post_id, meta.meta_key, meta.meta_value FROM wp_posts as post LEFT JOIN wp_postmeta as meta ON post.id = meta.post_id"; $result = $wpdb->get_results($query); $last_post_id = -1; $object_array = array(); foreach($result as $post) { if ($last_post_id != $post->post_id) { $instance = new Object; $last_post_id = $post->post_id; $instance->post_id = $post->post_id; $instance->{$post->meta_key} = $post->meta_value; $object_array[] = $instance; } else { $meta_key = $post->meta_key; $instance->$meta_key = $post->meta_value; } } </code> What this is doing is it is taking the relatively "dirty" query from sql and organizing it into the format you mentioned above. lastly try printing the array out for yourself <code> print_r($object_array); </code> You'll notice that your variables are embedded in another array "data" within the object but because of the getter and setter functions we wrote in the class definition, you still get to call the variable names directly. i.e. <code> $meta_key = "my_key"; echo $object_array[0]->$meta_key; </code> Hope this is useful.
|
Query and get meta as object(stdClass) on wp postmeta table?
|
wordpress
|
Let's say I create a plugin with a menu page and three different submenu pages. How can I determine the URI for each one of them? For example, if I want to have a link on one of the pages to one of the other pages, how do I do that? I had this problem before, too, when I created a form to gather some information. I ultimately solved it by having the page that defined the form handle it. Like this: <code> <form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>"> </code> How would I let another page handle the form data, i.e. what would I put in the action parameter. I noticed some people hardcode the URI one way or another, for example through <code> $_SERVER['PHP_SELF'].'?page=slug </code> But that won't work with all URL schemes.
|
You can dynamically generate those URLs like this: <code> $url = add_query_arg( array( 'page' => 'slug', // whatever the page slug should be, either for this page or the other pages ), admin_url( 'options-general.php' ) ); </code>
|
Determining URIs for plugin pages
|
wordpress
|
As the title says, is there any option to save the data in different table in wordpress. I have around 10000+ data in my site in a different table. I have moved this table inside wordpress database and i have created custom post and now I want to show the data from my own table not from wp_posts. Any ideas, suggestion or example.
|
Suggestion: move the data from the custom table into the wp_posts and wp_postmeta tables, as a custom post type. It will save you a lot of effort, in the long run.
|
saving custom post type data to different table in wordpress
|
wordpress
|
I just created some settings for my theme ... not perfect, still learning ... http://pastie.org/1988772 I am expecting the "Settings Saved" yellow box Do I need to do something on my part?
|
Adding this beneath the title should do it: <code> <?php settings_errors(); ?> </code> WordPress does this for you automatically on the 'options' pages, but you have to do it yourself in other sections of the site.
|
Settings API no update status? (refering to the yellow bar when you save settings)
|
wordpress
|
i updated my wordpress in 3.1 (i'm using twenty ten) and some of my code has been deleted, i'd like to understand it : is it only because i'm using the "twenty theme", that the "code" was replaced with the new version? does a "new version" remove also the code if i use my own theme? and so : to have a code safe, the "plugin" folder is the only safe area? I'd like to be confident the next time i update my version of wordpress. Thanks
|
At the moment, WordPress replaces core files when it updates. This will change in the future, but for now all core files get replaced, i.e. every file that comes with WordPress. This includes the default twenty ten theme. If you modify twenty ten you should save your modified theme with a different name. To do this, make a copy of the twentyten folder and rename this folder. Then, inside the renamed folder open styles.css and change the line Theme Name: Twenty Ten to Theme Name: Same Name as your Renamed Folder. Add this folder back into wp-content/themes and activate it in your admin settings. When WordPress updates it leaves your own themes alone, so you won't lose the changes you made.
|
update = remove code
|
wordpress
|
For example, if the post was published on may 5th 2011, then clicking on "May 5th, 2011" would show all posts published in May 2011. How can that be done?
|
This is straight from the WordPress codex <code> <?php $arc_year = get_the_time('Y'); ?> <?php $arc_month = get_the_time('m'); ?> <a href="<?php echo get_month_link($arc_year, $arc_month); ?>">archive for <?php the_time('F Y'); ?></a> </code>
|
Is there a template tag I can use to link to the archive page corresponding to the month that a post was published on?
|
wordpress
|
I have searched and found a few plugins which help me offer appointment scheduler for the site owner. Is there something in existence which can offer the same functionality to all the users of the site instead of just the site owner? Like a visitor can schedule an appointment with any user of the site? Do you know of such a plugin? If such a plugin doesn't exist, any options which can fill my cup up? Or I will have to write something of my own probably using code of some existing one but which one (any suggestions?)
|
I've looked for something like that before and i found that its a pain to try and modify any of these plugins to work as a per user schedule, what i ended up doing is i created a custom post type 'user_events' with a few custom fields (start_time,end_time,location,user_status,...)and on each author profile I've created a grid view of all days in a month displaying all of the events that user had, at the button I added a custom form to create a new post (from user_events type), which had some major validation to prevent over booking by checking the start_time, end_time of events on that day. When a new post (user_event) is created i changed the post_author to the user ID and set the post status to pending or draft. then an email is dispatched to the user(author) and when the post(user_event) was changed to published another email is sent to the guest who requested the appointment. all of that worked well and good but took some time to code and sadly have no access to this code anymore but i'll gladly help if needed. Update This is something i quickly coded (not been tested yet) to display the month grid view on an author page <code> if(isset($_GET['author_name'])){ $curauth = get_userdatabylogin($author_name); }else{ $curauth = get_userdata(intval($author)); } if (isset($_GET['c_mon']){ $Month = $_GET['c_mon'] $Year = $_GET['c_yea'] }else{ $Month = date("m"); $Year = date("y"); } $day_in_month = cal_days_in_month(CAL_GREGORIAN, $Month, $Year); $first_day = date("l", mktime(0,0,0,$Month,1,$Year)); $last_day = date("l", mktime(0,0,0,$Month,$day_in_month,$Year)); //print grid //open the table echo '<div class="current_month"><table><tr><td>Sunday</td><td>Monday</td><td>Tuesday</td><td>Wednesday</td><td>Thursday</td><td>Friday</td><td>Saturday</td></tr>'; //skip days til first day of month = day of week switch ($first_day) { case 'Sunday': echo '<tr>'; break; case 'Monday': echo '<tr><td>&nbsp;</td>'; break; case 'Tuesday': echo '<tr><td>&nbsp;</td><td>&nbsp;</td>'; break; case 'Wednesday': echo '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'; break; case 'Thursday': echo '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'; break; case 'Friday': echo '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'; break; case 'Saturday': echo '<tr><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>'; break; } $count = 1; while ($count < $day_in_month){ //get all of says events $args = array( 'posts_per_page' => -1, 'post_type'=> 'user_events', 'author' => $curauth->ID, 'order' => 'ASC', 'orderby' => 'meta_value', 'meta_key' => 'user_events_start' 'meta_query' => array( array( 'key' => 'user_events_date', 'value' => $Month.'/'.$count.'/'.$Year, ) )); //open new week row if (date("l", mktime(0,0,0,$Month,$count,$Year)) == 'Sunday' && $count > 1){ echo '</tr><tr>'; } $events = New WP_Query($args); if ($events->have_posts()){ echo '<td><div class="day_container"><div class="day_date">'.$count.'</div><div class="day_events_container"><ul>'; while ($events->have_posts()){ $events->the_post(); $out = ''; $out = '<li class="event"><div class="evet_time">'.get_post_meta($post->ID,'user_events_start',true). ' - '. get_post_meta($post->ID,'user_events_end',true).'</div>'; $out .= '<div class="event_name">'.get_the_title($post->ID).'</div>'; $out .= '<div class="event_location">'.get_post_meta($post->ID,'user_events_location',true).'</div></div></li>'; $echo $out; } echo '<ul></div></div></td>'; }else{ echo '<td><div class="day_container"><div class="day_date">'.$count.'</div></div></td>'; } $count = $count + 1; } //close extra days of week form next month switch ($first_day) { case 'Sunday': echo '<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>'; break; case 'Monday': echo '<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>'; break; case 'Tuesday': echo '<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>'; break; case 'Wednesday': echo '<td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td></tr>'; break; case 'Thursday': echo '<td>&nbsp;</td><td>&nbsp;</td></tr>'; break; case 'Friday': echo '<td>&nbsp;</td></tr>'; break; case 'Saturday': echo '</tr>'; break; } //close table echo '</table></div>'; </code> Now this code assumes that you have: a custom post type named: 'user_events' all posts of user_events type post_author field is set to the desired user. custom fileds: user_events_date -> holds the event date in a month/day/year format ex: 5/29/2011 user_events_start -> holds the event start time in a 12:00 format user_events_end -> holds the event end time in a 18:00 format user_events_location -> holds the event location as string
|
WordPress plugin for scheduling appointments
|
wordpress
|
I would like to know if it is possible to manually upload images to WordPress (ftp/scp) and make it recognize them and add them to the media browser. This also has to work with Wordpress running in multi-site mode (network).
|
I haven't tested this in multi-site but can't see any reason that it wouldn't work. The Add from Server plugin searches for images that you manually upload to WordPress and adds them to the media manager. You can find it here: http://wordpress.org/extend/plugins/add-from-server/ Tested on the latest WordPress.
|
How to upload images manually to wordpress?
|
wordpress
|
I'm a little confused about this, even though I have read all of the API and searched for hours. When I activate my plugin I add some values to the options database, e.g. <code> add_option('code','24'); </code> How do I update that value or use it in the widget? I only see "instances" now, like the example on this page: http://wpcoderz.com/creating-a-multi-instance-widget-with-wordpress-2-8/ I don't really understand what instances are, the WP documentation doesn't provide much explanation about it.
|
Instance 'instance' is really ment as in "object oriented programming instance': You have a certain class (which is a certain widget you coded as a class) and the moment you use it on a site, you create a specific instance of it; you create an object you can manipulate. BUT you can have one instance that has e.g. value "hello" as header and another one that has "hello world" as header (same class different instances)(so 2 widgets of the same class but with different properties). Values in these widgets If you have values that are specific to an instance you would specificy them in the widget class code, so you can e.g. show them in a form to the end user to manipulate. Dont worry about saving to the database, the widget class in the background takes care of that. If you have values that are the same for all instances of that widget you maybe could grab that from an option you set but they will never show up to the user in a form. (as you know with add_option you add yourself a new option to the table wp_options.) with widgets there is an intermediate layer (the widget factory) that saves the widget options for you in this wp_options table, so you do not have to manually add these options and updates on these options, to see this open wp_options and walk through the content of this table. if you nevertheless want to have access to your own option value you should add the regular option code inside the widget code (since then this setting can be changed inside the widget screen instead of e.g. your own plugin screen). If it is a value you would like to use directly maybe it is easier to not use your own option value but just use the one in the widget. If you use it to manipulate another value maybe you can better add a filter instead and then hook into this filter to manipulate the value used in the widget (as opposed to reading the option value directly) So first you construct a widget e.g.: <code> /** * Constructor */ function __construct() { $widget_ops = array('classname' => 'widget_icons_latest', 'description' => __('Shows your latest ♥ WP-Favicons which corresponds (after some time caching) '. 'with the latest outgoing links you published on your website. You can style '. 'the icons by using the stylesheet in the text widget settings under the ♥ WP-favicons '. 'Context settings.')); $control_ops = array('width' => 200, 'height' => 350); parent::__construct('WPFaviconsLatest', __('♥ Show Latest WP-Favicons'), $widget_ops, $control_ops); } </code> Then, in the widget method you can set initial values e.g. look at $title and you see that it first looks if THIS instance of the widget ( meaning the specific widget of this type that was dragged to the widget bar) already set a title, if not then it assigns a default value. IF you want to use your default value from some option you saved in the database you can replace the fixed value with one that you read from the option table, but why should you? You also see the value "25" below which is pretty hard coded, maybe that would be a good value to fetch from a database options table that you set yourself in a plugin admin screen (so replace 25 with get option) <code> /** * (non-PHPdoc) * @see WP_Widget::widget() */ function widget($args, $instance) { extract( $args ); echo $before_widget; $title = apply_filters( 'widget_title', empty($instance['title']) ? '' : $instance['title'], $instance, $this->id_base); $amount = empty($instance['amount']) ? 25 : $instance['amount']; $instance['text'] = $this->specificOutput($amount, false); $text = apply_filters( 'widget_text', $instance['text'], $instance ); if ( !empty( $title ) ) { echo $before_title . $title . $after_title; } ?> <div class="widget_icons_latest"><?php echo $text; ?></div> <div class="widget_icons_latest">by <a href="http://wordpress.org/extend/plugins/wp-favicons/">WP-Favicons</a></div> <?php echo $after_widget; } </code> The update method just updates the values if they have changed. The form method displays the form in the admin screen of the widget.
|
How to save WP widget instances and options
|
wordpress
|
Some time ago I discovered that dropdown menus that do have clickable links on parent nodes are confusing for the users. Often they are not seeing that they can click on the parent, they just assume that the parent is just like a folder. Check yourself the demo from http://2010dev.wordpress.com/ - see the second menu item, named "parent page". This is clickable but it may be not so obvious for many people. Also, this approach impose some issues with touch based devices where people may find impossible or hard to click a submenu-item. I would like to see a solution for this problem, but not one that would require me to fully change the theme.
|
This is a known issue with the Twenty Ten theme, arising from both the theme and core code. Twenty Ten has a number of accessibility issues - see Trac: http://core.trac.wordpress.org/ticket/14782 Some of these have been corrected in a child theme for Twenty Ten that you can get here: http://accessible.sprungmarker.de/2011/01/accessible-1-0/ The CSS and functions in the child theme cannot correct the menu issues though. Unfortunately, the menu issues are still present in the new Twenty Eleven theme that is coming with WordPress 3.2.
|
Accesibility problems with dropdown menus in twentyten theme or others
|
wordpress
|
My site template 's header.php file has the following: <code> <title><?php wp_title ( '|', true,'right' ); ?></title> </code> Why does this produce the site title twice on each page?
|
You're using two different SEO plugins: Yoast and All in One. Not a good idea. One of them is doubling up the title tag on single post pages.
|
Site Title appearing twice on live site
|
wordpress
|
The title says it all. I've been taking WP_LIST_AUTHOR and modifying it to create more of a member directory than just a list of authors while leaving a lot of the original options intact (and I am going to add more down the line). My first task was to build pagination into it, which I managed to do successfully (code below) [although it's not very pretty yet]. I now want it to build this information into tables (probably 15 results per page, in a 3x5 grid. Row - cell cell cell Row - cell cell cell etc). I am not really sure on the best way to do this, or if this can even be done with the current way the code is constructed, any advice or linked resources would be greatly appreciated! I'm really just hacking things together ;) Also note; the site uses s2member plugin and any code will need to not mess with that functionality. <code> <?php /////////////////////// ///// SEXY TIME ///// /////////////////////// /** * CUSTOM FUNCTIONS BY DUIWEL * We are taking the regular wp_list_authors and forcing it to always display all * the authors, as well as have pagination and a better format * * This is my first attempt at a Wordpress Hack such as this * * 5/28/2011 * * I have left most of the original function text intact, including the comments below * * I used a lot of code from Crayon Violent at PHPFREAKS * http://www.phpfreaks.com/tutorial/basic-pagination * Most of his/her comments also remain intact * */ //ORIGINAL WP COMMENTS for wp_list_authors /** * List all the authors of the blog, with several options available. * * <ul> * <li>optioncount (boolean) (false): Show the count in parenthesis next to the * author's name.</li> * <li>exclude_admin (boolean) (true): Exclude the 'admin' user that is * installed bydefault.</li> * <li>show_fullname (boolean) (false): Show their full names.</li> * <li>hide_empty (boolean) (true): Don't show authors without any posts.</li> * <li>feed (string) (''): If isn't empty, show links to author's feeds.</li> * <li>feed_image (string) (''): If isn't empty, use this image to link to * feeds.</li> * <li>echo (boolean) (true): Set to false to return the output, instead of * echoing.</li> * <li>style (string) ('list'): Whether to display list of authors in list form * or as a string.</li> * <li>html (bool) (true): Whether to list the items in html form or plaintext. * </li> * </ul> * * @link http://codex.wordpress.org/Template_Tags/wp_list_authors * @since 1.2.0 * @param array $args The argument array. * @return null|string The output, if echo is set to false. */ //THE FUNCTION function duiwel_custom_list_users($args = '') { global $wpdb; // HIDE_EMPTY ORIGINALLY TRUE, now FALSE $defaults = array( 'orderby' => 'name', 'order' => 'ASC', 'number' => '', 'optioncount' => false, 'exclude_admin' => true, 'show_fullname' => false, 'hide_empty' => false, 'feed' => 'feed', 'feed_image' => '', 'feed_type' => 'rss2', 'echo' => true, 'style' => 'list', 'html' => true ); $args = wp_parse_args( $args, $defaults ); extract( $args, EXTR_SKIP ); $return = ''; $query_args = wp_array_slice_assoc( $args, array( 'orderby', 'order', 'number' ) ); $query_args['fields'] = 'ids'; $authors = get_users( $query_args ); // FYI This is the post count of each author, not the total count of authors $author_count = array(); foreach ( (array) $wpdb->get_results("SELECT DISTINCT post_author, COUNT(ID) AS count FROM $wpdb->posts WHERE post_type = 'post' AND " . get_private_posts_cap_sql( 'post' ) . " GROUP BY post_author") as $row ) $author_count[$row->post_author] = $row->count; // need to count 'authors' here $totalusers = count($authors); ////////////////////////////// ////// PAGINATION //////////// ////////////////////////////// $numrows = $totalusers; // number of rows to show per page $rowsperpage = 10; // find out total pages $totalpages = ceil($numrows / $rowsperpage); // get the current page or set a default if (isset($_GET['currentpage']) && is_numeric($_GET['currentpage'])) { // cast var as int $currentpage = (int) $_GET['currentpage']; } else { // default page num $currentpage = 1; } // end if // if current page is greater than total pages... if ($currentpage > $totalpages) { // set current page to last page $currentpage = $totalpages; } // end if // if current page is less than first page... if ($currentpage < 1) { // set current page to first page $currentpage = 1; } // end if // the offset of the list, based on current page $offset = ($currentpage - 1) * $rowsperpage; ////////////////////////////// ////// END PAGINATION //////// ////////////////////////////// ////////////////////////////////////////// ////// PAGINATION TO FOLLOW ARRAY /////// ////////////////////////////////////////// //I need to take the SQL LIMIT function from the pagination code I found //and incorporate it into the arrays I'm using, cause I'm not actually //querying a SQL table, I'm querying an array $pagination_user_table = $authors; $paged_authors = array_slice( $pagination_user_table , $offset , $rowsperpage ); ////////////////////////////////////////// ////// START NORMAL WP_LIST_AUTHOR //////// ////////////////////////////////////////// foreach ( $paged_authors as $author_id ) { $author = get_userdata( $author_id ); if ( $exclude_admin && 'admin' == $author->display_name ) continue; $posts = isset( $author_count[$author->ID] ) ? $author_count[$author->ID] : 0; if ( !$posts && $hide_empty ) continue; $link = ''; if ( $show_fullname && $author->first_name && $author->last_name ) $name = "$author->first_name $author->last_name"; else $name = $author->display_name; if ( !$html ) { $return .= $name . ', '; continue; // No need to go further to process HTML. } if ( 'list' == $style ) { $return .= '<li>'; } //some extra Avatar stuff $avatar = 'wavatar'; $link = get_avatar($author->user_email, '80', $avatar); $link .= '<div id=directoryinfo>' . ' <a href="' . get_author_posts_url( $author->ID, $author->user_nicename ) . '" title="' . esc_attr( sprintf(__("Posts by %s"), $author->display_name) ) . '">' . $name . '</a>'; if ( !empty( $feed_image ) || !empty( $feed ) ) { $link .= ' '; if ( empty( $feed_image ) ) { //Line breaking for RSS formatting (testing mostly) $link .= '<br>('; } $link .= '<a href="' . get_author_feed_link( $author->ID ) . '"'; $alt = $title = ''; if ( !empty( $feed ) ) { $title = ' title="' . esc_attr( $feed ) . '"'; $alt = ' alt="' . esc_attr( $feed ) . '"'; $name = $feed; $link .= $title; } $link .= '>'; if ( !empty( $feed_image ) ) $link .= '<img src="' . esc_url( $feed_image ) . '" style="border: none;"' . $alt . $title . ' />'; else $link .= $name; $link .= '</a>'; if ( empty( $feed_image ) ) $link .= ')'; } if ( $optioncount ) $link .= ' ('. $posts . ')'; $return .= $link; $return .= ( 'list' == $style ) ? '</li>' : ', '; } $return = rtrim($return, ', '); if ( !$echo ) return $return; echo $return; ///////////////////////////////////////// ////// END WP_LIST_AUTHOR NORMALCY ////// ///////////////////////////////////////// // little spacer echo "<br /><br />"; ////////////////////////////// ////// PAGINATION LINKS ////// ////////////////////////////// /****** build the pagination links ******/ // range of num links to show $range = 3; // if not on page 1, don't show back links if ($currentpage > 1) { // show << link to go back to page 1 echo " <a href=' " , the_permalink() , " ?currentpage=1'><<</a> "; // get previous page num $prevpage = $currentpage - 1; // show < link to go back to 1 page echo " <a href=' " , the_permalink() , " ?currentpage=$prevpage'><</a> "; } // end if // loop to show links to range of pages around current page for ($x = ($currentpage - $range); $x < (($currentpage + $range) + 1); $x++) { // if it's a valid page number... if (($x > 0) && ($x <= $totalpages)) { // if we're on current page... if ($x == $currentpage) { // 'highlight' it but don't make a link echo " [<b>$x</b>] "; // if not current page... } else { // make it a link echo " <a href=' " , the_permalink() , " ?currentpage=$x'>$x</a> "; } // end else } // end if } // end for // if not on last page, show forward and last page links if ($currentpage != $totalpages) { // get next page $nextpage = $currentpage + 1; // echo forward link for next page echo " <a href=' " , the_permalink() , " ?currentpage=$nextpage'>></a> "; // echo forward link for lastpage echo " <a href=' " , the_permalink() , " ?currentpage=$totalpages'>>></a> "; } // end if /****** end build pagination links ******/ ////////////////////////////////// ////// END PAGINATION LINKS ////// ////////////////////////////////// } /////////////////////////// ///// END SEXY TIME ///// /////////////////////////// ?> <div id="directorylist"> <ul> <?php duiwel_custom_list_users() ?> </ul> </div><!-- #directorylist --> </code>
|
Your snippet is a little too verbose to follow (and it's late here) so this is more of an alternate take. I think that forking <code> wp_list_author() </code> might be overkill here. It would be more elegant to hook inside user search and accurately slice the portion of authors you need. Here is some example code I came up with: <code> add_action('pre_user_query','offset_authors'); $authors_per_page = 1; $current_page = absint(get_query_var('page')); function offset_authors( $query ) { global $current_page, $authors_per_page; $offset = empty($current_page) ? 0 : ($current_page - 1) * $authors_per_page; $query->query_limit = "LIMIT {$offset},{$authors_per_page}"; } wp_list_authors(); </code> Also check out <code> paginate_links() </code> function for building pagination.
|
Modifying WP_LIST_AUTHOR Functions to output all users in a grid (and Paginate)
|
wordpress
|
Whenever I write a post on my blog and link to a previous post, that pingback shows up as a comment needing to be approved. I am running Disqus , but this was happening even pre-use of that plugin. What is the fix for this behavior?
|
The comment handling is somewhat difficult to follow in code. My educated guess is that you have comment whitelist enabled ( Comment author must have previously approved comment ), but since pingbacks are not identifiable by author they are treated as requiring moderation.
|
How to auto-approve internal pingbacks?
|
wordpress
|
WordPress usually has "Leave a Comment, "1 Comment," or "% Comments" on the blog page, and I want people to be able to hover over that and have jQuery show the latest comment in a rectangular box below it (pushing down all subsequent content). Obviously they'd click through to read more comments or respond, but I can't figure out where to start and go from there. As an example, if you look at the site Destructoid, they show the latest comment after each post. I want to show something similar, but only after the "# comments" is hovered over. Only then would the box with the latest comment show up and push the rest of the content down. It would disappear if the mouse is moved off of the link or box itself. I figure get_comments can be used to call it, but comments_popup_link doesn't take arguments for alt text or jQuery boxes, I don't think. Any suggestions?
|
The <code> comments_popup_link_attributes </code> filter will allow you to output attributes within the link. <code> function add_comment_hover_action() { echo ' onHover="fireMyJSCode();"'; } add_filter(‘comments_popup_link_attributes’, ‘add_comment_hover_action’); </code> Alternately, you could hook into the <code> comments_number </code> filter to add a span wrapper around the comment number text with a common class name and the parent post id as an attribute. Then in JavaScript you could assign a function to handle hover actions for all those comment spans. Inside your js function hover handler access the post id from the wrapper element.
|
How to show last comment on hover?
|
wordpress
|
I'm developing a wordpress plugin at the moment which I do not want in the Wordpress plugin repository. However I still want to be able to push updates to my costumers from my own API repository. I've been reading quite a bit about this, and one thing that seems to be something about is the <code> pre_set_site_transient_update_plugins </code> filter, however I can't find much info about this. I've tried this tutorial (http://konstruktors.com/blog/wordpress/2538-automatic-updates-for-plugins-and-themes-hosted-outside-wordpress-extend/) which I couldn't get working. I can tell from the comments that others can actually get this working with what must be almost the current version of WP (latest response Apr 22). I tried installing the plugin from the site and putting the API folder on a second domain, but the update notification I usually get when an update is available, didn't show anywhere at all. I'm not sure if it is actually possible to have custom plugins run the auto-update from other repositories so I would like to hear if anyone in here has any experience at all with this stuff? The solution in the tutorial seemed to be an easy solution - I wonder if it's somehow possible to do it in a more advanced way? Any help getting this auto-update from my own repository working would be much appreciated! (PS: I'm running WP version 3.1.3)
|
For the benefit of others who find this page, I suggest those wishing to provide their own updates outside the official WP repository check out this project on GitHub, that demonstrates the functionality: https://github.com/jeremyclark13/automatic-theme-plugin-update
|
Update plugin from personal API
|
wordpress
|
Hey guys, I'm using a calendar plugin that provides a sidebar widget to show current calendar dates. However this widget always shows N/A if I don't set a category for a specific event. Any idea how I could add a filter to that widget and match N/A and remove it? thank you for your help
|
In the method "widget" look for the line that sets the category then add either: <code> $cat = empty($instance['cat']) ? 'N/A' : $instance['cat']; </code> (where you replace N/A with something you like) or... better... add a filter instead like this: <code> $cat = apply_filters( 'widget_my_cat', empty($instance['cat']) ? 'N/A' : $instance['cat'], $instance, $this->id_base); </code> And then hook into 'widget_my_cat' to set it to something else if the value is 'N/A'
|
Filter Text from sidebar widget?
|
wordpress
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.