INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How to develop a theme while having another show up The title is the question : How to develop a theme while having another show up I already have a DB and a theme.... i like, when log as admin see another theme... just for the time making it clean and final... and then, remove the old one and have the new one able to be see for everybody... any plugin that do that ? * * * some research and result : < and < not sure what it's worth....
I used this one a while ago and it worked. Hasn't been updated in a while...but should still work. <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "themes" }
Removing the base "Author" or changing it to something else. is it possible? Is it possible to remove the AUTHOR base? Is it possible change it to postedBy so that the urls is site.com/postedBy/joe And finally, is it possible to remove a custom taxonomy base from the url so that a url like site.com/people/joe can become site.com/joe
Use the plugin Edit Author Slug to change the base. Screenshot from the plugin’s settings page: !enter image description here Your other question is … _another, separate_ question. ;)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom taxonomy, url rewriting, author" }
How to use "TRUNCATE TABLE" MySQL statement? I have tried dbDelta and $wpdb->query, they does not work. Does anyone has any ideas?
As try today, truncate is WAY BETTER that DELETE, because DELETE broke the site, and trucate just empty the table, here is the working code : global $wpdb; $wpdb->query('TRUNCATE TABLE wp_posts');
stackexchange-wordpress
{ "answer_score": 11, "question_score": 5, "tags": "database, mysql" }
wp_nav_menu li item empty I created an menu by admin panel > Appearence > Menu. I have just one menu page in **menu_lateral_1** . Or the result is <li id="menu-menu_lateral_1" class="menu"></li> <li id="menu-item-212" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-212"><a href="my_website">my page</a></li> With following code : $args = array( 'menu' => 'menu_lateral_1', 'container' => '', 'items_wrap' => '<li id="%1$s" class="%2$s">%3$s</li>' ); wp_nav_menu($args); I don't understand where the first item comes ?!
Take a look at the Codex documentation. The `items_wrap` attribute is for wrapping the list elements as a whole - not each individual menu item: > Whatever to wrap the items with an ul, and how to wrap them with If you look at this line you'll see that it is using `sprintf` to replace three place-holders in the provided `items_wrap`. The first being an ID, the second a class, and lastly the items. Try: wp_nav_menu( array( 'menu' => 'menu_lateral_1', 'items_wrap' => '<ul id=\"%1$s\" class=\"%2$s\">%3$s</ul>' ) ); ?> This should give: <ul id="menu-menu_lateral_1" class="menu"> <li id="menu-item-212" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-212"><a href="my_website">my page</a></li> </ul> **Note:** You should use `theme_location` rather than `menu`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Can I use wordpress comments system to build a user review system within my website? I am creating a part of my site where a user can enter a comment (review) and rate my web application. When a user enters a comment and rates my site out of 5, their comment will be available to the entire site (after approval). I am not sure whether to go about this by making a database table for this and manually setting up user input fields into my custom DB table, or trying to use a wordpress plugin, or try and leverage the wordpress comment system in a mixture of both. Can anyone provide an idea of the best way to go about doing this?
You can use comments and store individual ratings using `add_comment_meta()`. You would also probably want to store the rating average using `add_post_meta()`, since it's rather expensive to calculate it on the fly. Each time a rating is added or removed, you will have to update this average. I don't know if there are any plugins that do this already; haven't searched.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments, review" }
Sort posts by most recently modified Is there a way to list posts in the order in which they were modified? For example; A user posts 5 posts (#1 being the oldest and #5 being the newest), by default they would be listed with #5 being at the top, but say the user edited post #3 at a later date, is it possible to then list post #3 above #5 without manually changing the page attributes? This is a secondary query by the way, using get_posts
If you use `WP_Query` you can set the `orderby` to `modified` and then the order to `DESC` and you'll be good to go. If it's not a custom query, you can just use the `set()` method on the default `$wp_query` global to do the same. Since `get_posts()` is just a wrapper for `WP_Query`, you can set the `orderby` parameter there if everything else is working and not change anything else.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "loop, get posts, sort" }
How can I delete all my existing trackbacks? I'm sorting out a long-neglected wordpress.org blog. It has over 100,000 pieces of trackback spam. How can I remove them all?
To make this more WP-ish: function wpse_delete_trackbacks() { global $wpdb; $wpdb->query( $wpdb->prepare( " DELETE FROM %s WHERE `comment_type` = 'trackback' ", "{$wpdb->prefix}comments" ) ); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "spam, pingbacks" }
is there an update_post_meta action Are there any actions I can hook into for update_post_meta()? I don't see anything obvious in the source. Woocommerce lets you change the featured status of items via ajax from the edit screen. I am using a transient to store the featured items in lieu of querying them every time and I'm deleting that transient on the save_post hook, but it isn't getting fired because of the ajax function that directly updates the post meta. Worst case I can unhook woo's action and recreate it myself with the delete transient call, but I'm wondering if there is another hook i could use.
(See codex) `update_post_meta()` calls update_metadata('post', $post_id, $meta_key, $meta_value, $prev_value); This function is here. And there are plenty of hooks/filters: (In example of 'post', `$meta_type='post'`) ## Before metadata is updated: `update_{$meta_type}_metadata` (here) **Filter** - _If this returns anything other than 'null', the metadata won't save_ `update_{$meta_type}_meta` (here) **Action** ## After metadata is updated: `updated_{$meta_type}_meta` (here) **Action** `updated_post_meta` (here) **Action** - _For posts only_ All the actions take `($meta_id, $object_id, $meta_key, $meta_value)` as arguments. The filter filters a `$check` and takes the above as additional arguments.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "actions, post meta" }
Logout redirects to /forums/ A while back I installed a plugin which, upon logout, re-directed users to `/forums/`. Unfortunately, I have no idea which plugin that was and whether or not it's still active/installed. What code/db settings can I look for to remove the offending code? Thanks in advance,
I discovered the Hikari Hooks Troubleshooter ( this weekend to find what plugins were loading my header with competing open graph metadata. Enable it, and visit the frontend. There will be a modal dialog over your site which should list the hooks into wp_logout. One of these will be the offending plugin. If you're still using the other parts of the plugin and there are no settings to turn that feature off, you should be able to remove it by adding `remove_action('wp_logout', $plugin_function)` to your theme's functions.php. Make sure you disable HHT when you're done with it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "logout" }
PHP if Condition not working I'm trying to create a condition in Wordpress that only calls the `wp_head()` on all pages except for the "About Us" page and "News Articles" pages. Here's the code: <?php if (!is_page('about-us') || !is_page('news-articles')) {wp_head();}?> It seems to work great when I only use the command for one of the pages, but using an operator seems to mess things up. In some cases the pages load correctly, but the desired results are not happening. I've also double-checked to make sure that I'm referencing the pages correctly, and I'm confident that I am.
You should be using the "AND" operator, not "OR" <?php if (!is_page('about-us') && !is_page('news-articles')) {wp_head();}?> Because you want to display the WP head only if both conditions are true.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php" }
Category names on CPT archive pages I purchased a theme and I'm trying to customize the "blog archive" pages for the Portfolio CPT that's included with the theme. The theme is: < I've created some Portfolio categories and linked to them in the menu. Here's an example: < I want it to say "Kitchens" instead of "Blog Archives". How would I do that?
I was looking for a WordPress that would allow to me to display the category name at the top of the page. That function is single_cat_title() - <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, categories, theme development" }
How to display a certain template element only for posts published within certain time range? I recently migrated a blog from sub.domain.com to blogs.domain.com/sub/. Because I'm using Facebook comments, all the posts published before April 25 need to reference sub.domain.com/blog-entry-title as the fb:comments href. I know how to display certain posts for my date range with this code: <?php function filter_where($where = '') { //posts for Jan 1 to April 26, 2012 $where .= " AND post_date >= '2012-03-01' AND post_date <= '2012-03-15'"; return $where; } add_filter('posts_where', 'filter_where'); query_posts($query_string); ?> But can I manipulate this code to use at the template level to say: "If post published before April 25, display xyz comments; else display abc comments."
Sure, you can do something like this in your template code: <?php $migrate_date = mktime(0,0,0,1,1,2012); if ( get_the_date('U') > date('U', $migrate_date) ) { echo "<p>New</p>\n"; } else { echo "<p>Old</p>\n"; } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, comments, templates, facebook, date" }
How can I attach files without using a plugin? I want to add files from my site or from external links with files to any of my posts, and be able to add the size of the file and choose which ones it will do "File Force" and which not. I want to have too a counter that it will show how many clicks/downloads the file had. Any link that I add to a post internal or external, I want it to have automatically rel noindex, nofollow. Is this possible to do with custom fields??? I also tried by adding media>external media, I inserted it to the post but it doesn't show it in the post, have I done something wrong or I have to something more to find out?
I have used custom fields in the past to do something kinda like this. You name each custom field the same, and then in the value, give it some separation character. I used ||. Then you can do something like this: $output = array(); foreach($custom as $c) $output[] = explode('||',$c); Then you'll have an array of arrays with your information. From there you should be able to do with it what you want. I also wrote a shortcode to go along with this, that allowed me to display it anywhere in the page. That allows you to have more flexibility, and you don't have to mess with a custom template.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "custom field, attachments, media" }
Is there any plugin which can paste a common content to my every post? I am using wordpress for my blog. My blog contains events details and in every post i want to start with "this information is exclusively provided by...." this statement and end with my "feedburner subscribe us box" So what I am actually looking for is <---My String---> MY Actual Post <---My feedburner subscribe us code---> this. Is there any plugin which can automatically add the common stuff to my post. Please help out.
Actually you don't need a plugin to do this. Just add a simple function to your _functions.php_ file: function my_content($content) { $content = 'My content before post' . $content . 'My content after post'; return $content; } add_filter('the_content','my_content'); If you don't want additional content to appear in your feed, use following function: if( !is_feed() ) { function my_content($content) { $content = 'My content before post' . $content . 'My content after post'; return $content; } add_filter('the_content','my_content'); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "plugins, posts" }
How to write a new file when new post has been published in Wordpress I having a problam with my wordpress plugin. The plugin does whenever new post has been published, it will automaticly create a new file with that post content. this is my code function example($post_ID) { global $post; $content = htmlentities(get_post_field('post_content', $_GET['post'])); file_put_contents(dirname(__FILE__) . '\myFile.txt', $content); } add_action('publish_post', 'example'); But when i change the code some think like this. this will working file_put_contents(dirname(__FILE__) . '\myFile.txt', "Some string here");
Where you pass post id ? $content = htmlentities(get_post_field('post_content', $post_ID));
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, posts, publish" }
Save Option on Database Sorry for the question but can you help me? I have this form in a widget: <form> <fieldset> <legend>Counter Position:</legend> </br> <p> Right <input type="radio" name="position" value="right"/> <p> Left <input type="radio" name="position" value="left"/> <p> Center <input type="radio" name="position" value="center"/> </fieldset> </form> how to save on database the option selected?
<?php add_option( $option, $value, $deprecated, $autoload ); ?> < global $options; ?> <form action="options.php" method="post"> <?php $settings = get_option('options'); ?> <?php settings_fields('theme_options'); ?> <fieldset> <legend>Counter Position:</legend> </br> <p> Right <input type="radio" name="position" value="right"/> <p> Left <input type="radio" name="position" value="left"/> <p> Center <input type="radio" name="position" value="center"/> </fieldset> </form> <?php function r_set() { register_setting('theme_options', 'options', 'validate_options'); } add_action('admin_init', 'r_set'); function validate_options($value) { global $sa_options; $val['position'] = $value['position']; return $val; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, html, customization, options" }
How many SQL queries WP Super Cache make to serve cached page? WP Super Cache plugin generate page and save html of this page to static file and if needed this file is served instead of dynamically generate this page each time. **Does WP Super Cache plugin make any extra SQL queries during serving the cached page?**
I've received an answer about it from Donncha O Caoimh \- developer of the WP Super Cache plugin: > If using mod_rewrite to serve cached files then there won't be any queries executed. The page might load images that require queries but the cached html itself won't require queries. > > If using PHP mode than I think it won't need any or many queries but I can't remember right now. So there is 0 extra sql queries and the question is closed.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, cache" }
Hide / Show Custom field depending of the page ID (Magic Field 2) I use Magic Field 2 to display custome field on my page ! However, I would like to be able to hide several field depending on the page ID... I do not want to use custom post type because my website rely on basic page. Any idea on how I could do that ? Using javascript perhaps ? I can't figure out, which hook I should use. Thanks in advance for your time and patience. Cheers, Jk_
You can remove meta boxes with the `remove_meta_box` function: function wpse50430_remove_meta_boxes() { // make sure we're on an admin screen and `post` is set if( !is_admin() && !isset( $_GET['post'] ) ) return; if( $_GET['post'] == 99 ): // editing page ID 99 remove_meta_box( 'pageparentdiv', 'page', 'normal' ); endif; } add_action( 'admin_menu', 'wpse50430_remove_meta_boxes' ); To remove meta boxes added by plugins, you have to find the handle ID. If you use Chrome's developer tools, you can right-click the meta box and look for the ID of the element with class `postbox`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, plugin magic fields" }
Wordpress add_rewrite_rules for custom URLs ending in .html It's pretty common to see Wordpress running on pretty permalinks in the style of: /blog/2012/04/my-post/ However I'm trying to customize a fresh Wordpress install with a different set of URLs. I believe wp_rewrite is my best method, writing a small block of code inside functions.php. I have seen a few examples of wp_rewrite_rules but none appear to be simply changing all post URLs. Ideally I'd like to have them setup like this: /blog/2012/04/my-post.html I would love any help on this if possible.. it's been a struggle finding good code examples for even basic rewrite rules. Let me know if I can provide any more details.
You don't need custom rewrites for that, you can simply use the permalinks settings to achieve those results. Click the Custom Structure option and enter: /blog/%year%/%monthnum%/%postname%.html
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "php, htaccess, url rewriting, plugins" }
convert more tag to shortcode is there is a way to convert `<!-- more -->` to shortcode
Try adding this to your plugin file (or functions.php). You'll use [my_more] as the shortcode for this example. function wpse50449_more_func( $atts ){ return "\n<!-- more -->\n"; } add_shortcode( 'my_more', 'wpse50449_more_func' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, shortcode" }
Is There A WordPress Plugin That Produces PDFs of Posts Locally? Most of the WordPress PDF plugins out there use services like Joliprint and Print Friendly to convert posts to PDFs. Is there a plugin that does this locally utilizing the power of PHP (and/or WordPress), I mean, without using an external service?
I was half way through writing a long answer explaining why there weren't any ... when I found one. WP Post to PDF is a plugin, updated for WP 3.3.2, that generates PDFs locally and caches them for later.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "posts, pdf" }
Introductory paragraph only in list of blog posts My blog is displaying the full post of my latest blog post, instead of an introductory paragraph only. How do I make it show an introductory paragraph only, so readers need to click into the full post? Here's the blog: < (I haven't posted on it in a while and I can't remember how to do this.)
You need to use the more tag. The documentation is from WordPress.com, but it works the same on self-hosted installs.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "list" }
Mailing list sign up box I'd like to add a sign-up box with name and email fields to my site. I'll want to add a title so people know it's for my mailing list, and a note to say that i only send mails out occasionally. What would be an easy and solid way to add this? With a plugin? If a plugin is the way to go, waht would be a good plugin for this? I'd like the sign-up-box to appear in the right-hand column on every page -- the non-blog pages as well as the blog pages. It's for this site: < (I'll need to alter the margins on the non-blog pages.)
I'm a big fan of MailChimp for managing and sending email lists. As long as you stay under 2k subscribers and 12k emails / month, their service is free. They have a tool that allows you to create and customize an HTML form you can embed in a widget that automatically adds people to your mail list. <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugin recommendation, mailing list" }
Insert PHP code in Text I have this code for insert a permalink but doesn't work, return exactly code: $text = '<form><td>Permalink to: <?php the_title();?></td><textarea cols="85" rows="2" readonly="readonly" onclick="select()"/><?php echo $permalink = get_permalink( $id ); ?></textarea></form>'; This is what currently shows up: !Screenshot
A better, cleaner way to do this would be to use proper string return methods and concatenation. I say this, because you're trying to put functions that echo content (i.e. `the_title()` into a variable - this won't work!!! Instead: $text = '<form><td>Permalink to: '; $text .= get_the_title(); $text .='</td><textarea cols="85" rows="2" readonly="readonly" onclick="select()"/>'; $text .= get_permalink( $id ); $text .= '</textarea></form>'; Or, if you absolutely must have this in one long line: $text = '<form><td>Permalink to: ' . get_the_title() . '</td><textarea cols="85" rows="2" readonly="readonly" onclick="select()"/>' . get_permalink( $id ) . '</textarea></form>';
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, permalinks, code" }
this jQuery function works perfect in static html page but not on wordpress I am using wp_enqueue_script to do this. If I try to do something else lets say popup a dialog, it works but the code below does not. Can someone tell me the problem. thanks. var $j = jQuery.noConflict(); $j('#mystuff').hide(); var mouseLastYPos = null; $j(document).mousemove(function(e){ if(mouseLastYPos){ if (e.pageY < mouseLastYPos && e.pageY <= 2){ $j('#mystuff').show(); } } mouseLastYPos = e.pageY; });​ here is a working demo of this code on a static page. when you move you mouse to the top of the page some text appears. <
The jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load. In order to use the default jQuery shortcut of $, you can use the following wrapper around your code: jQuery(document).ready(function($) { // $() will work as an alias for jQuery() inside of this function }); That wrapper will cause your code to be executed when the page finishes loading, and the $ will work for calling jQuery. If, for some reason, you want your code to execute immediately (instead of waiting for the DOM ready event), then you can use this wrapper method instead: (function($) { // $() will work as an alias for jQuery() inside of this function })(jQuery);
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "plugins, jquery" }
Travel Blog Plugins I'm using Wordpress to create a blog of my travels later on this year. I would like the blog to have the following features * my posts to be geo-located * a map containing the locations of my posts * ability to click individual points on the map to get to the post. I am looking for the best/most appropriate plugins to use. Thanks, Al.
I think GeoMashup is the go-to plugin for something like this. < I've used it for a similar site with great results. There's a lot to dig into, it's very flexible, but you'll definitely be able to get what you want.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugins, google maps" }
Wordpress category loop offset possible? I have been on this for a while now and haven't really come across a solution to filter the posts on a category page using a sort of offset in php. There are plugin for posts and pages but I am trying to achieve this with pure php and specifically for a category page. Scenario example: A blog with 7 posts, setting the offset to say 3 would begin the loop on the category page to only show (Post4, Post5, Post6, Post7) and NOT (Post1, Post2, Post3). I am wondering if this would be possible at all and be dynamic enough to apply to all categories without the need to specifically identify which posts to exclude via id numbers.
The 'offset' parameter does what you want. I've written this hack, it should help you... <?php //The third parameter corresponds to action priority, //set it to change the order of execution in case of a conflict add_action('pre_get_posts', 'the_modified_loop', 10); function the_modified_loop($query){ //Remove 'is_admin' if you want the code to run for the backend category archive page if(!is_admin() && $query->is_category()){ $query->set('offset', 3); } } ?> Let me know if it worked!
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "php" }
What happens to the text in functions.php file outside of the php enclosure? I have a very basic question. In the `functions.php` file of a theme, what happens to the text that is outside a function and outside the <?php ?> tags? Can I place notes before and after the functions without commenting it and without affecting the system? Or should I at least enclose the out-of-php text in html comments? For example: comment/note/reference text <?php function my_function() { code; return results; } ?> more comment/note/reference text <?php function my_function_2() { code; return results; } ?> more comment/note/reference text cheers, Gregory
It will probably throw a 'Headers already sent' error/warning and cause a lot of trouble to everything.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions" }
How to Insert Self-Hosted Video in WordPress Post Does WordPress have an easy way to insert video in a post? I am not referring to YouTube, Vimeo or other hosting sites, just video I upload myself on the server or through the Media manager. I have an mp4 video for example, and I'd like to have it play within the post, it's hosted on the same server as the website.
HTML 5 <video width="640" height="360" src="/wp-content/uploads/2012/04/my_video.mp4" autobuffer> <div class="fallback"> <p>You must have an HTML5 capable browser.</p> </div> </video> For Flash Check out JW Player
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "videos" }
Get the blog page URL set in Options I have set the blog to be a different page other than the home page. I want to have a link from single.php to this blog page. Is there any function that pulls out URL for the blog ?
As of WordPress 4.5 you can use: get_post_type_archive_link( 'post' ); This handles the logic of getting the correct URL regardless of whether posts show up on the homepage or in a specified page.
stackexchange-wordpress
{ "answer_score": 48, "question_score": 54, "tags": "theme development, functions, permalinks" }
how would I include some html in the header section of a wordpress plugin? I get an error When I include some div into a plugin I am creating I get an error when activating the plugin. _"The plugin generated 33 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin."_ Though the plugin works on the site but I get an error when activating it. here is the plugin code. I want it to display the text on top of the page. I understand I need to use some hooks, but which one? hre is a link showing what I want. < <?php /* Plugin Name: test Plugin URI: Description: test Author: Ronny Kibet Author URI: version: 1.0 */ ?> <div id="bar">hello there</div>
The answer... add_action('init', 'text_on_top'); function text_on_top(){ ?> <div id="bar">hello there</div> <? } Never output anything outside of a function, use a suitable action/filter to do so!
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, headers" }
Importer failed to import posts as format "day and name" I had a blog exposing posts as "day and name". After exporting that blog and importing it on a new installation of WordPress I can't see the posts in that format, only in the default one: < Also moving to previous pages ( does not work. Is this a known issue with a solution?
The WordPress .xml import file only contains post data and not any site settings, such as permalinks. It seems to me that this is only an issue of setting the permalinks the same way of your old site. * Settings -> Permalinks (`/wp-admin/options-permalink.php`) * select `Day and name` * save changes If WordPress can't update the .htaccess file, follow this instructions: < [update] In case it is a server problem: < <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks, import, export" }
How to order results by date and meta key? I'm using wp-postratings to rate posts which stores the rating as a custom meta value `ratings_score`. It gives you the option to use `r_sortby` to order the loop by highest rated but I want to give it a trending feel by dividing the $ratings_score" by how old the post is in days. So something like this.. $ratings_score = get_post_meta($post->ID,'ratings_score',true); orderby = $ratings_score / days ago How can I accomplish this?
You could do this by sorting on a calculated factor. Dividing the rating by the days gives a good starting point: rating/days = factor (e.g. 15/6 = 2.5 or 11/3 = 3.6) You can balance this to your needs by multiplicate the variables (rating and day) with any factor you like. There are to ways to implement such a factor: 1. use wp-crons to hourly refresh the factor for each post and save the value as postmeta. So you can easily use a WP_Query and sort the posts by the meta_value_num. 2. calculate the factor directly in your post-loop
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "query posts, loop, query string" }
Redirect to post after submission with Gravity Forms? How do I redirect to a post after submission with gravity forms. It gives you the option to put in query string values but when I add `{post_id}/{Video Title:1}` I get `mysite.com/?123/name+of+post` and it just goes back to the homepage. My permalink structure is `post_id/postname` and `{Video Title:1}` equals the post name but it uses plus sings instead of dashes. What am I doing wrong?
Set the query string to `p={post_id}`. WordPress will redirect it to the proper URI then automatically.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "redirect, plugin gravity forms, query string" }
How to get the theme directory URI? I want to get the theme root URL with PHP. What would be the best way to do that? There is a function called `get_theme_root()` which gives me the path but not the URL. Maybe just get the current themes or parent themes URL and cut the theme directory off? How do I do that?
I think you just want `get_theme_root_uri()`. Note that it doesn't contain the trailing slash.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, urls" }
making images scalable for responsive designs Working on first responsive website template; layout is part fluid, with fixed sidebars, using media queries. I want to have some of my images be scalable. Per this article < it should be very simple, at least for manually loaded images. Add this to stylesheet: img{max-width: 100%;} img{ -ms-interpolation-mode: bicubic; } and manually remove width and heights that wp automatically adds. Have done both and not a thing happens. See images in the main areas (not sidebars) on these 2 pages: < and < I haven't added code to functions for thumbnails yet -- wanted to get the basics working first. What am I missing? Thanks!!
Nothing appears to happen because the size of the images is smaller than the available width. If I add a bunch of padding to the container in Chrome and then resize the window, the image scales once all horizontal width is consumed.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "responsive" }
How to handle shortcodes when using the JSON API I'm wrangling a little logic problem: I'm making a single page WP theme which uses the JSON API for the content and Mustache style templates for the presentation... However, shortcodes? What would be the best way to handle these? For example: JSON result->template->DOM injection->trigger hijack for gallery/slideshow/whatever the shortcode is? The above method feels a bit dirty as I'd have to either keep firing a parser to process the shortcodes or else I'd have to use JQuery.live (seriously dirty). Can anyone think of a more elegant way of doing this?
You can add your own AJAX API for `do_shortcode`. Add this to a suitable location (i.e. `functions.php` or a plugin): add_action('wp_ajax_doshortcode', 'ajax_doshortcode'); function doshortcode() { echo do_shortcode($_POST['text']); die(); // this is required to return a proper result } And this to your Javascript: $.ajax({ url : ajaxurl, data : { action : 'doshortcode', text : <text> }, type : 'POST', error : function(req, stat, err) {...}, success : function(data, stat, req) {...} }); `ajaxurl` is defined on admin pages; see here for instructions for viewer-side applications. Alternatively, you can set up such actions for all API functions you need, wrapping the original calls with `do_shortcode`.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "shortcode, javascript, json, plugin json api" }
How to show large image in checkout page using WP Ecommerce plugin I want to show large image in checkout page right now it showing 31x31 size image in `wpsc-shopping_cart_page` and using `<img src="<?php echo wpsc_cart_item_image(); ?>` to call thumbnail image. what should i do for that? !enter image description here
here is the solution i find myself with just 4 easy step 1. go to wp ecommerce plugin folder 2. find cart.class.php file 3. find wpsc_cart_item_image function 4. change $width and $height accordingly
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, images, plugin wp e commerce" }
Current theme broken - after server and domain migration I'm migrating a Wordpress install and trying to get down the correct process for doing so. I've tried using the method I thought would work, but it didn't. My files and database are in place, but when I visit the wp-admin the theme manager tells me this - The active theme is broken. Reverting to the default theme. Unfortunately if you then re-activate it, it work's but loses all it's widgets etc. I've been using a search and replace function to change all the instances and options using the old domain with this script - < Which is pretty cool. I'm just replacing with although even running this before I access the site doesn't seem to stop the problem of the broken theme and thus losing all the widgets. Anyone know how I can migrate this site without having the ass-ache of losing all the widgets (of which there are way to many to do manually).
Try the XCloner plugin: < I use XCloner to move sites between my live server and my dev server. It takes care of all the migration differences between the domain, database, etc. It preserves all my widget settings, custom menus, etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "themes, widgets" }
get_term_children doesn't return an array of children terms I am trying to get the term children and then check if they exist to display them. But I get no IDs in return of get_term_children command. This is the code: $children = get_term_children($term->term_id, locations); echo $children; $term is already defined and outputs well, "locations" taxonomy exists. The code returns me just an "Array" word, no list of child terms shows up. I've got a similar code in my post archive pages and it works well returning me child categories in n/n/n/n/n format: $children = get_category_children($this_category->cat_ID); echo $children; What's wrong with the first code? It should work as well as the second.
At first, try passing the Taxonomy as a string: $children = get_term_children($term->term_id, 'locations'); The function get_category_children produces a string as return, so you can just echo it. the function get_term_children, however, returns an array. To see the contents of the array, try print_r( $children ); instead of echo. The last thing to keep in mind is that a taxonomy does not need to be hierarchical - for example the built in tags. Be sure your "locations" is organized hierarchical, otherwise get_term_children won't work for you in this case.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom taxonomy, taxonomy, terms" }
Security updates to 3.3.2 I know all security updates are important but given that how important on a scale from 1 to 10 is it to upgrade from 3.1.3 to 3.3.2. I have some sites that need to be upgraded but the host has me locked down in an older version of php that limits me to 3.1.3. I am currently running version 5.2.3 of php. Thanks, Bart
Since WP 3.1.3 has come out, we've released: * 3.1.4 - **security update** * 3.2 * 3.2.1 - **security update** * 3.3 * 3.3.1 - **security update** * 3.3.2 - **security update** On a scale of 1-10, skipping a single security update is about a 3 (bad, but not catastrophic). Skipping _4_ security updates, though, would be closer to an 8-9 ... You should seriously consider moving to a new host if they're locking you on PHP 5.2.3. Even PHP 5.2.4 included several security updates, and the 5.2.X branch maxed out at 5.2.14. The current stable for PHP is 5.4 (thought 5.3.9 is still pretty solid).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, security, upgrade" }
How to check user role? I have functions that have to execute based on the user roles. How do I check the user role so that I can insert the respective function under their role? EG. if ($_GET['role'] == "free member" ) {//insert funtion 1} elseif if ($_GET['role'] == "sliver member" ) {//insert funtion 2} else {//insert funtion 3} I tried using current_user_can, like this : global $get_currentuserinfo, $current_user; if( current_user_can('free_member') ) {//insert funtion 1} elseif current_user_can('sliver_member'){//insert funtion 2} else {//insert funtion 3} This work with default role like "editor","author", "contributor". but seem doesn't work with custom role that created by role managing plugin. I am using Advanced Access Manager to create the custom role by the way. Since this role checking snippet is using in writing panel, so what approach is best to check the user role?
Looking around Google for a few minutes yielded several promising results. Here's a more detailed one adapted from a snippet on The Code Collective: function get_user_roles( $user_id ) { $user_roles = []; $user = get_userdata( $user_id ); $capabilities = $user->{$wpdb->prefix . 'capabilities'}; if ( !isset( $wp_roles ) ) { $wp_roles = new WP_Roles(); foreach ( $wp_roles->role_names as $role => $name ) { if ( array_key_exists( $role, $capabilities ) ) $user_roles[] = $role; } } return $user_roles; } This will return an array of the user passed in as `$user_id`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "user roles, customization" }
add_actions called from functions.php not returning good values I am trying to add some security/acccess prevention to my site via the functions.php. However whenever I try to add through functions.php (instead of as a plugin, which I've done in the past) it fails (always returns false). For example: add_action("parse_query", checkaccess()); // in functions.php and function checkaccess() { $allowAccess = false; if(is_admin()||is_front_page()||is_home()||current_user_can('administrator')) $allowAccess=true; if($allowAccess) echo 'whatup'; //do something here } even if i try something basic - eg `global $wp_query; var_dump($wp_query);` I can't get the query var, its all NULL. Any advice? Is there some kind of walled sandbox the fuctions.php file operates from that it can't get any of these?
Your `add_action` should be: add_action( "parse_query", "checkaccess" );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp query, actions" }
Page not found when trying to link to files in child theme directory I'm trying to create a child theme based on Toolbox 1.4 by Automattic. I have my scripts file saved as `child_theme/js/scripts.js` on my server and I enqueue it by using wp_enqueue_script( 'scripts', get_stylesheet_directory_uri() . '/js/scripts.js', array('jquery') ); in the `header.php`. When I view source in Firefox, I see the href to the stylesheet as and the href to the scripts as When I click on both, I can see the source of my `style.css`, but it says "Page not found" for my `scripts.js`. I've never created a child theme before. I used to just copy a theme and modify it. What am I doing wrong? **EDIT** It works when I move `scripts.js` out of the `/js/` subdirectory into the child theme's root directory and change the `wp_enequeue_script`. So what is wrong?
Shouldn't you be enqueuing that in functions.php instead? function script_enqueueing() { wp_enqueue_script( 'scripts', get_stylesheet_directory_uri() . '/js/scripts.js', array('jquery') ); } add_action('wp_enqueue_scripts', 'script_enqueueing'); Edit to add: if calling directly in header.php, use `get_template_directory_uri();` instead.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "404 error, wp enqueue script, child theme, directory" }
How to: Add a publish immediately button when editing custom WordPress posts? How to: Add a publish immediately button when editing custom WordPress posts? I have found to update a custom post type I need to re-edit the scheduled time to save it. Is it possible to simple update the content for custom post types by pressing something like "Current Date" then it will add the current date, there you can publish it?
As per the comments above: you should be able to click 'update' in the publish metabox. If your post is scheduled to be published, it will be updated and still scheduled to be published at that date. If the post is already published, it is updated (and remains published). If the post is in draft or pending status clicking 'publish' updates and publishes the post.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, posts" }
How do you make the email field on the profile page read only for subscribers? I would like to make the email field on the profile page for subscribers read only. They can see their email but not change it. I want only admins to to be able to change users email address.
Although the readonly attribute can be removed using Chrome/Firebug inspector (making the field editable again), much probably the average user will not know this. <?php function wpse50730_script_enqueuer(){ if(current_user_can('subscriber')) { echo '<script type="text/javascript"> jQuery(document).ready( function($) { $(".form-table #email").attr("readonly", true); }); </script>'; } } add_action('admin_head-profile.php', 'wpse50730_script_enqueuer');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "profiles, user meta" }
add_rewrite_rule() not playing nice with child pages function my_add_rewrite_rules() { add_rewrite_rule('testing/([^/]+)?$', 'index.php?pagename=testing&event_slug=$matches[1]', 'top' ); } add_action( 'init', 'my_add_rewrite_rules' ); function add_query_vars( $query_vars ) { $query_vars[] = 'event_slug'; return $query_vars; } add_filter( 'query_vars', 'add_query_vars' ); _/testing/foo_ \- Works, shows foo If I have **testing** set to no parent, the rewrite works and everything is good to go. If I set **testing** to a child of, lets say **about** , and update the add_rewrite_rule to.. add_rewrite_rule('about/testing/([^/]+)?$', 'index.php?pagename=testing&event_slug=$matches[1]', 'top' ); ... it loads about/testing but strips out my custom query_var and displays the page normally. _/about/testing/foo_ \- Loads page, doesn't show foo
if it's a child page, you have to update `pagename` to reflect the parent/child path: add_rewrite_rule('about/testing/([^/]+)?$', 'index.php?pagename=about/testing&event_slug=$matches[1]', 'top' );
stackexchange-wordpress
{ "answer_score": 12, "question_score": 3, "tags": "url rewriting" }
How to wrap oEmbed-embedded video in DIV tags inside the_content? I am making a Wordpress Theme for a website with video tutorials. I would like to put the video that is embedded in the content (with oEmbed) in a apart div. **An example** The full content (output from `the_content()`) is something like this: <p><iframe src=" width="900" height="506" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe></p> <p>This is an Test of a tutorial. Bla bla bla</p> And I would like to get this to: <div id="video"> <iframe src=" width="900" height="506" frameborder="0" webkitAllowFullScreen mozallowfullscreen allowFullScreen></iframe> </div> <div id="content"> <p>This is an Test of a tutorial. Bla bla bla</p> </div>
The `embed_oembed_html` filter runs before an oEmbed resource's HTML is outputted, so you could hook into this and wrap the output in a `div` as below. I can't think of a simple way of wrapping the other content. add_filter('embed_oembed_html', 'my_embed_oembed_html', 99, 4); function my_embed_oembed_html($html, $url, $attr, $post_id) { return '<div id="video">' . $html . '</div>'; }
stackexchange-wordpress
{ "answer_score": 17, "question_score": 9, "tags": "filters, oembed" }
can the_excerpt function also get images? Not sure if im going about this in the right way but, overall, ive been told to create, kind of like a news box on my home page and so, the "latest news" is going to be this clients posts. now i know i can control `the_excerpts();` content length etc but, i cant seem to find any way for it to also allow an image. when i showed the client the "news box" he wants whatever image is associated with the post, to come through. so i thought of `"the_content();"` but i dont think thats what i need(though im not sure which one will work best with what i need) so the main questions here for me are 1. Can i somhow get the image to come through with the excerpt, or 2. If the excerpt function doesnt allow it, then what can i use?
Ensure that your Theme supports Post Thumbnails, and that the client sets a "Featured Image" for each post. Then, combine `the_excerpt()` with `the_post_thumbnail()`, e.g. like so: <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <div id="post-<?php the_ID(); ?>" <?php post_class(); ?>> <div class="featured-image"><?php the_post_thumbnail(); ?></div> <div class="post-excerpt"><?php the_excerpt(); ?></div> </div> <?php endwhile; endif; ?> Then, just use CSS to style according to your needs.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "post thumbnails, excerpt" }
Add template meta box to category edit page? Is there any non-plugin solution to add template meta box on the category edit screen? Template meta box like that on the page edit screen, but this one for category. I'd like to have this function built into the theme page. Something similar to the one Mike Schnikel did for Scott B here.
I'm currently working on a theme framework and one of it's classes is a custom category template class which does just what you are asking for: it adds a select field to the category edit screen that lets you select a template, just like with pages, and i just published it as a plugin **`Custom Category Template`** and if you are not up with using a plugin then simply take a look at the plugins code which is a single class that you can even use from your functions.php file.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "metabox" }
Wordpress - query 5 posts with a specific post in top Many searches and tests but in vain, I need an expert to rescue me. I need a custom post query in worpdress, which returns only 5 posts starting from a specific post. In other terms, there is a div in single.php where i need the list of 5 posts starting from the current post (the post returned by single.php) I hope I was clear thanks for your valuable help.
You can do this by using `get_adjacent_post()` and the filter `get_previous_post_where` or `get_next_post_where`. You'll call `get_adjacent_post()` as normal, but you'll need to change the `LIMIT` to 5, using the filter. I wasn't sure from the question whether or not you wanted to have the current post be first. If you do, you'll need to set the `LIMIT` to 4 and then use the current postdata to generate the first post. I would create an array of post ids, and then use `get_post()` when you iterate through them, as I believe that `get_adjacent_post()` will return raw rows from the database.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, query" }
Permalinks for custom taxonomy stopped to work I'm not sure when this happened, I just noticed it. I have custom taxonomies and post types. For the longest time I was able to go to `domain.com/taxonomy/term` and it would display the posts related. Now it's not. I'm still able to access it by `domain.com/?taxonomy=taxonomyhere&term=termhere` The last time I remember this working I was on Apache but have recently moved over to nginx. I thought I tested a while ago and it and it was working though.
Sometimes a plugin changes WordPress' internal rewrite rules during an update, an installation or deactivation. If the plugin's update happens to run _after_ your taxonomy registration it may just wipe out the custom rules for the taxonomy. To inspect the currently active rewrite rules use the plugin Monkeyman Rewrite Analyzer. See this answer for details. To refresh the rewrite rules visit the permalink settings page once.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom taxonomy, permalinks, url rewriting, nginx" }
Send confirmation email when a user's role is upgraded I've been searching around for a solution but am coming up dry. I need to have a confirmation email sent to users when their role is upgraded. By default users are signed up as contributors and make them apply to be upgraded to an author and I want an automated email sent to the user as soon as they are upgraded. Any ideas?
Send email notification when user role changes \- Adding this snippet to the `functions.php` of your WordPress theme will send the member an email notification when the user’s role has changed. function user_role_update( $user_id, $new_role ) { $site_url = get_bloginfo('wpurl'); $user_info = get_userdata( $user_id ); $to = $user_info->user_email; $subject = "Role changed: ".$site_url.""; $message = "Hello " .$user_info->display_name . " your role has changed on ".$site_url.", congratulations you are now an " . $new_role; wp_mail($to, $subject, $message); } add_action( 'set_user_role', 'user_role_update', 10, 2);
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "email, user roles" }
can't limit search to only pages I'm trying to limit a search to only pages, but it isn't working properly. When I include this hidden field in the search form: <input type="hidden" name="post_type" value="page" /> The results include posts, pages, and custom post types. If I change the above to search only posts, it works properly, and only posts are displayed. Anyone have any ideas why it won't properly restrict my post to only display pages? I need to restrict the results for this search form only, so modifying the search query results in the search results template or in functions.php won't work for me.
A quick test on a default install with TwentyEleven confirms this, and I'm not sure why this is the case, however there is a way you can do this via your `functions.php`. add a hidden field to the form with your own query var: <input type="hidden" name="my_type" value="page" /> or: <input type="hidden" name="my_type" value="post,page" /> add the new query var to WP's recognized query vars: function wpse50828_query_vars( $query_vars ){ $query_vars[] = 'my_type'; return $query_vars; } add_filter( 'query_vars', 'wpse50828_query_vars' ); add your code to set the post type when that query var is set: function wpse50828_search( $query ){ if( get_query_var('my_type') ) $query->set('post_type', explode( ',', get_query_var('my_type') )); return $query; } add_action( 'parse_query','wpse50828_search' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 3, "tags": "search" }
In Loop Output Place Custom Field Content In Between Paragraphs I'd like to place the contents of a custom field or variable in between the second and third paragraphs in the loop on a page template. Is there a way to do this? So for example, on a client's website I would like them to use the post editor to write out their page content, and keep things simple for them by giving them the ability to write out a call to action in a custom field that diplays between two paragraphs of the_content(); using either a plugin or a PHP snippet or filter in functions.php. Thanks very much.
After researching this, here is what works for me: <?php $paragraphAfter= 1; //show box after selected paragraph $content = apply_filters('the_content', get_the_content()); $content = explode("</p>", $content); for ($i = 0; $i <count($content); $i++) { if ($i == $paragraphAfter) { ?> <!-- START OF BLOCKQUOTE --> stuff <!-- END OF BLOCKQUOTE --> <?php } echo $content[$i] . "</p>"; } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, the content" }
Get the timout value of a saved transient? Does anyone know if there is a Wordpress function to get the timeout value of a saved transient? I am using a transient with a 5 minute timeout to cache data from a web API call locally. Between transient timeouts I load the data locally from the transient acting as a cache and secondary API throttle. What I would like to do is read and display the timeout value of the currently saved transient data so the user knows how long they need to wait before the next data refresh. The value is stored in the 'wp_options' table as '_transient_timeout_transient-name', so I assume I could use the global $wpdb object and just do a SQL query, but I wanted to make sure there wasn't a more elegant way.
So, after one minute of more thinking, there is an easy solution, although i did not try it myself: $transient = '_transient_timeout_' . $_your_transient_name; $transient_timeout = get_option ( $transient ); you should be ready to go with this. Another Way throught the database would be: $transient = '_transient_timeout_' . $_your_transient_name; global $wpdb; $query = 'SELECT option_value FROM ' . $wpdb->prefix . 'options WHERE option_name = ' . $transient; $transient_timeout = $wpdb->get_var( $wpdb->prepare( $query ) ); the returned value is a timestamp, but i'm sure you know how to handle it from here.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "query, cache, api, sql, transient" }
Custom post type and URL Is it possible to remove alias from custom post type? Let me tell a bit more. For instance, I've created a post type, name "Book". So URL will be `domain.com/book/post-title` or `domain.com/?post_type=book&p=528.` I want the URL as `domain.com/post-title.` Is it possible?
In short - you cannot, or at least _should not_. `www.domain.com/post-title` is interpreted as post (if your structure is `%postname%`) and/or a page - and WordPress is set to deal with them as such, including any conflicts. You can do the following: add_action('init','wpse0845_add_rule'); function wpse0845_add_rule(){ add_rewrite_rule("([^/]+)/?",'index.php?book=$matches[1]','top'); } (and then flush rewrite rules, _once_ ). However, you'll notice that now your pages (and depending on your structure, posts too) give a 404.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "custom post types" }
Manipulate Output of wp_list_something: select menu instead of li's I'm working on a responsive webdesign where my navigation should swap into a select-menu when resizing the window in smaller sizes. Is it somehow possible to add another param to functions like `wp_list_categories()` or `wp_list_pages()` so that it outputs `<option>item</option>` instead of `<li>item</li>`? So what I wanna do is use `wp_list_pages()` and `wp_list_categories()` to ouput its default stuff in order to have a normal menu. However I also want to ouput the same pages and categories in a second `<select><option>…` navigation that is hidden by default but shown when a media-query is triggerd. Any idea how to dynamically produce this second menu? Thank you in advance!
you can easily do this the same way as `wp_list_pages()`, using `wp_dropdown_pages()`. the args needed to retrieve the pages are the same. for the categories, use `wp_dropdown_categories()`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "functions, filters, wp list pages, categories, responsive" }
Why does this WPDB code throw an empty WPDB error? I'm writing a feed reader plugin for wordpress. I'm seeing a DB error that I can't figure out. First I create a table called user_entries. Then I put a sample entry into that table. When I try to delete an entry, I get a very strange error in my debug log. There are no foreign keys yet, no indices on the db, etc. > [02-May-2012 11:21:52] WordPress database error for query DELETE FROM wp_wprss_user_entries > WHERE owner_uid = 2 AND feed_id = 2; made by do_action, call_user_func_array, wprss_unsubscribe_feed, WprssFeeds->remove So what is the error? It's just blank in there. This doesn't look like complicated SQL and it works fine in the phpmyadmin query window. I'm not sure what to do for a next step now, and I'd like folks to be able to unsubscribe from a feed!
The code you've linked to above: //$sql set to raw SQL statement $sql = $wpdb->prepare($sql,$feed_id); if($wpdb->query($sql)){ $resp->uf_error = $wpdb->print_error(); } So if there _isn't_ , an error you try displaying the 'error' with `$wpdb->print_error()`. Also`$wpdb->print_error()` doesn't **return** an error, it **prints** it. It's (probably) the printing of that non-error that is causing an error in your second database query, the one for which an error is logged. **Side note:** take a look at the `wpdb` class. There are methods in there that handle INSERT/UPDATE queries so you don't have to do them manually.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "wpdb" }
Can the_category display a post count? Is it possible for the_category to display a post count within a post. Looks like Posted In: Category Name (3),Category Name (2) etc etc Possible or not? I would just use wp_list_categories but it needs to appear on a post by post basis like this post is posted in category x and y not just all of them...
How about this... add_filter('get_the_categories', 'wpse50876_the_counter'); function wpse50876_the_counter($cats){ foreach($cats as $cat){ $cat->cat_name = $cat->cat_name.'('.$cat->count.')'; } return $cats; } Try it...
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
Why is $wpdb->get_results failing on certain tables but not others (which have data)? I'm trying to pull some custom data from a Cart66 table. My code works whenever I pull results from standard WP table in (my array is populated and the print_r shows that data), but not with any Cart66 tables (it prints an empty array). I am absolutely certain that I've got data in these tables (I've rechecked that I'm using the correct table names about 1,000,000 times). I've tried two Cart66 tables which have data in them. The codex says the get_results class should work with any table, not just standard tables. I thought it might be the underscore that was causing trouble, but underscores are supposed to be fine, and indeed, standard WP tables with underscores work fine. $rawproducts = $wpdb->get_results( "SELECT * FROM $wpdb->cart66_products" ); print_r($rawproducts); This is maddening! Any ideas? Thanks!
you do not have to specify the $wpdb again in your query, but be sure that your table uses the prefix, if it has one. if it doesn't, skip the part with the prefix. also, you should always prepare a manually added query first. this should do it: global $wpdb; $query = $wpdb->prepare( "SELECT * FROM %s", "{$wpdb->prefix}cart66_products" ); $rawproducts = $wpdb->get_results( $query ); print_r($rawproducts);
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "database" }
no emails for a user account Is it possible to create a user account without an email. Just a username? I saw that there is a plugin to allow multiple authors under one email. Does anyone have any recommendations on other ways to do this. I know this not ideal but I have one user who will posting on behalf of multiple users. Having the user verify their email through gravatar for each new author is a <
As far as I'm aware, it's not possible via Add New under the Users tab, however, the `wp_create_user` function will let you create users without an email address: $username = 'someuser'; $pass = 'swordfish'; $new_user_id = wp_create_user( $username, $pass ); You'd have to wrap that in a basic plugin and provide some sort of UI for adding users.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "author" }
Highlight menu item when on a custom post type? I'm currently using this code to display a menu of pages. I'm using CSS to target the class `current_page_item` which works fine until you're on a page with a custom post type. How can I target that class when the page the user is on is a custom post-type such as news or events? <div id="menu-repeat"> <?php $args = array( 'depth' => 1, 'show_date' => '', 'date_format' => get_option('date_format'), 'child_of' => 0, 'exclude' => '1908, 6282, 6380', 'include' => '', 'title_li' => __(''), 'echo' => 1, 'authors' => '', 'sort_column' => 'menu_order, post_title', 'link_before' => '', 'link_after' => '', 'walker' => '' ); ?> <ul><div class="menu-button"><?php wp_list_pages( $args, 'sort_column=menu_order' ); ?></div></ul>
If this is for a one-off site, I would suggest doing this with CSS. Philosophically, adding the `current_page_item` class to a menu item when that's not true feels a bit wrong too. As long as you're using the `body_class()` function on your `<body>` element in the theme, there should be a class called `single-{event}` where "{event}" is the id of the post type. Hence, add the selector `.single-{event} .page-item-{ID}` where "{ID}" is the page ID of the events page (you'll see that as the class on the menu item as well).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "custom post types, custom taxonomy" }
front end logo upload like happytables happytables has a cool feature where if you are logged in, on the home page && haven't uploaded a logo yet it will insert a drag + drop image box similar to image uploader on the backend. any ideas on how to pull this off? currently digging thru the source code, but if anyone has some pointers, i'd greatly appreciate it --
I actually wrote this for Happy Tables so should be able to give you a couple of pointers, though I don't have time to go into too much depth at the moment. We use this "image well" on tables tables a fair bit, it's basically the drag/drop upload from the WordPress upload. Similar to something like this: < we use Plupload for the image well, which send the file to the WordPress media-upload.php. Anyway, this is all open source from Happy Tables which you can view here: < It is pretty modular, so you might be able to use it as is pretty much. It does lean on WP Thumb, which you can download here: <
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "admin, front end" }
How to update Post Meta values through the comment system I'm working on allowing users to rate posts - through the comment meta. Storing and displaying individual ratings is working, however, I would like to be able to store the average rating in the post meta. I have this thus far, seem to get stuck on passing values to the post meta. add_action( 'comment_post', 'add_av_rating', 1 ); function add_av_rating($comment_ID) { $commentdata=get_comment($comment_ID, ARRAY_A); $parent_post=get_post($commentdata['comment_post_ID']); //get rating, get post meta & calc update_post_meta($parent_post, 'average_wr', $commentdata); } Even when I put a value such as 'thisText' instead of $commentdata it seems to fail. What am I doing wrong?
`$parent_post` is an object, `update_post_meta` requires the ID, so should be: update_post_meta( $parent_post->ID, 'average_wr', $commentdata );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "post meta, comment meta" }
Choopy Video Playback in a popup using Artiss Youtube Embed I'm using Artiss Youtube Embed to embed youtube videos on my site which works great because it allows me to control all the parameters for the video player. My issue is that when the video has choppy playback when it's playing in a popup window. I allow users to click on thumbnails on the homepage and then I use SimpleModal Jquery plugin to popup the video from the post. I tested a video from youtube using their iframe embed code and it worked perfectly. So something with this plugin is causing the choppy playback which only occurs in the popup. It works normally on a single post page. Any idea what might be causing that?
Thanks to David Artiss I figured out this was a problem with the Windows Mode setting. By default it's set to opaque but for it not to conflict with video in a popup
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, videos, youtube" }
Add existing user as administrator I run several wordpress sites that I created. A friend has asked me to help admin his existing site. So we want to add my userid as admin to his site. However, User | Add User allows addition of a 'brand new user' with new password, email ets. I would much prefer not to have another wordpress user account to remember. Can I not add my existing userid as admin to my friend's site?
WordPress user accounts are unique to a single installation of WordPress. Even if they are hosted on the same server, there's no simple way (and, more importantly, probably no secure way) to hook them together. WordPress accounts on WordPress _.com_ can be added to other sites, but not accounts on self-hosted WordPress installations. The only "exception" to this situation is that a user account can be added to multiple sites if those sites are all part of a multisite network (which is essentially what WordPress.com is). _Note: Using the same email account to register user accounts on multiple sites will associate each user account with a gravatar account with the same email address, but that's pretty much only useful for getting a gravatar image or using JetPack's gravatar hovercard plugin._
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "user access" }
Sorting by tag or category Here's the scenario: A user clicks on a tag which takes them to a list of all those posts with that tag. There are hundreds of posts, so the user needs a way to filter these. Here's the question: How would you build a drop down that a user can select to filter by category while on the tag page. Filter all Yellow tags by Color category for instance. Also the reverse would be useful. Searching the Color category and filtering by the tag Yellow.
The function get_posts() allows you to set parameters for both categories and tags. You could build two drop down boxes that list all categories or tags and then use JavaScript or just make a new page to sort these. What other information do you need?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "sort" }
How to Override default update_count_callback for category Is it possible to override default `update_count_callback` for category? The default function counts published posts while I want to count private posts. I do not want to register a new taxonomy.
In your update_count_callback function do a check for $post->post_status and don't increment your count if post_status is not private. See this excellent answer on writing a custom update_count_callback callback function. ## Edit: Misread the question. To override the existing default for the category taxonomy you can create a function that overrides the global $wp_taxonomies variable function change_category_arg() { global $wp_taxonomies; if ( ! taxonomy_exists('category') ) return false; $new_arg = &$wp_taxonomies['category']->update_count_callback; $new_arg->update_count_callback = 'your_new_arg'; } add_action( 'init', 'change_category_arg' );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "categories, taxonomy, callbacks" }
Keep formatting for tables copied from MS Word? I've found that copying and pasting tables from MS Word was closest to easiest when it comes to making tables; rather than formatting a table from scratch in a WYSIWYG editor. The one shortfall I've found is that the "center" formatting does not copy over. It LOOKS like it does but the formatting is not actually applied. you have to go through each cell and center it. Just wondering if anyone has a clue on how the WP editor handles MS Word and maybe if there's a fix?
I actually have a pretty awesome way to get the HTML output of the Microsoft Word table formatting. I use MS Live Writer and copy and paste from MS Word. Then I can simply view the HTML output and copy and paste that into the WordPress editor. It works perfectly. The only downside is that now you have a ton of in-line CSS formatting on the table itself. You can't really accomplish the same with stylesheets if you have variety and complexity across different tables you want to publish.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "formatting" }
Allow users to register as a higher role than default with code By default all new registrants for my site are assigned the role "contributor" and then I make them request an upgrade to an "author" account through a form. I also send out invitations to certain people to join the site in which I want them to automatically register as an "author" so they can skip the application process. Now my first thought was to send out some type of key code in the email and have them enter it in on a registration page but that seems like a lot of hassle. What I'd like to do instead is send them a link to a registration page that signs them up under the "author" role. But I also have issues with that approach in that I would need the link to only work when accessed by that email address it was sent too. I know this is a vague question but I'm looking for a solid solution for what I want to do.
You could combine your two ideas- generate a code and send them a link to a sign up form with that code as a query string in the url. match the code with the email address they enter when they sign up, then delete it once sign up is complete so it can't be used again.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "email, user registration, user roles" }
Plugin is not generating title tags on any pages or posts I am using the Wordpress SEO plug in and for some reason the plug in is not longer adding title tags to any posts or pages. I just updated my theme, and something has changed between this version and the last one regarding the way it works with the Wordpress SEO plugin. I checked the header.php and as far as I can tell it has the correct code: <title><?php wp_title(''); ?></title> If I deactivate the plugin the titles come back. Does anyone have any ideas of what could be happening? I'll be happy to supply any code if needed.
It turns out there was an issue with a plug in (Wordpress SEO) and the theme. I had to click the check box for "enable title rewrite" within the plug in settings in order to get it to work.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, theme development" }
How Do I Load My Action Earlier Enough? With add_action, I want to intercept as early as I can in my plugin and send a 304 Not Modified header per some rules. **Does anyone know what the order is of events?** When I view this page, it seems to hint that the best place for this would be plugins_loaded, and that it comes before the init event. Is that correct? The page in that link doesn't describe what the event order is, but seems to imply it.
The page you referenced does have the correct order of events listed there. If you want to see which events were fired for a particular request you can install debug-bar and debug-bar-action-hooks. If you are wanting to send a header either `plugins_loaded` or `init` will work. But it is recommended to use the `send_headers` action that is fired just after the request is parsed, also if your rules depend on data in `WP_Query` you will need to use `send_headers`.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "plugin development, hooks, actions" }
Showing relevant categories on custom taxonomy template I an using two taxonomies with private posts. 1. category e.g. massage, travel 2. location e.g. new-york-city, boston etc. On a location page, I want to show categories that are relevant to that location. e.g. If I am on `?location=boston` page I would find all the posts that are in `boston`, then I would find a list of categories in which these posts are categorized. I want this list to be displayed on top of location page. Is there is a simple, built-in way to do all this?
In `the_loop`, just add this code... <?php $cats = wp_get_object_terms(get_the_id(), 'category'); ?> Print_r `$cats`, it will have the list of the `categories` applied to this post.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, multi taxonomy query" }
Internal Links to Pages in PHP? What is the best way of linking to WordPress pages with PHP? Considering that I move the page from a local server to a live server to another URL? <a href="/wordpress/services" title="Read More" class="yellowButton">Read more</a> How could you replace this code with PHP linking to the WordPress page. /wordpress/services
# Page Permalink from $id If you know the Page `$id`, use `get_permalink()`: <?php $permalink = get_permalink( $id ); ?> # Page Permalink from $slug If you know the Page `$slug`, such as `/about` (including hierarchy, such as `/about/work`), use `get_page_by_path()` to determine the Page `$id`, then use `get_permalink()`. <?php $page_object = get_page_by_path( $slug ); $page_id = $page_object->ID; $permalink = get_permalink( $page_id ); ?> # Page Permalink from $title If you know the Page `$title`, such as "Some Random Page Name", use `get_page_by_title()`, then use `get_permalink()`: <?php $page_object = get_page_by_title( $title ); $page_id = $page_object->ID; $permalink = get_permalink( $page_id ); ?>
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "pages, links" }
Allowing logged in users to create custom posts I'm looking to create a site with a wide array of user contributed content. I have strong experience in programming, and I'm evaluating Wordpress for the task. My question: Having created a custom post type, can I allow a broad array of users (not necessarily per-approved or know to me) to create and manage their own instances of that custom post type? What's the best way to go about this? Is there a front end for that creation, or do they need access to the admin? Thanks for any help.
Right - so there are some plugins that do this. Some are focused on saving admins the trip to the backend. I needed something that kept users out of the backend entirely, but allowed them to contribute custom posts. I'm going with wp-user-frontend and so far, it's doing the trick.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, user access" }
add_menu_page permissions - what am I doing wrong? I am running a fresh install of Wordpress 3.3.2 and the only plugin enabled is one I'm developing, but I can't seem to get past a permissions issue in `add_menu_page`. With the exception of using anonymous functions instead of named functions, I'm following the documentation almost exactly. My plugin source: <?php /* Plugin Name: Some Plugin */ add_action('admin_init', function() { add_menu_page('Some Page', 'Some Page', 'manage_options', 'some-slug', function() { echo 'Hello, world!'; }); }); ?> The menu link shows up fine at the bottom of the menu, but instead of "Hello, world!", I see: > You do not have sufficient permissions to access this page. I've also tried using the `administrator` capability in place of `manage_options`, but have the same results. What am I doing wrong?
You want the `admin_menu` hook, rather than `admin_init`. Also, you shouldn't use anonymous functions. Instead, use: function wpse51004_add_menu_page() { add_menu_page('Some Page', 'Some Page', 'manage_options', 'some-slug', 'wpse51004_some_page_callback'); }; add_action('admin_menu', 'wpse51004_add_menu_page'); function wpse51004_some_page_callback() { echo 'Hello, world!'; }
stackexchange-wordpress
{ "answer_score": 14, "question_score": 5, "tags": "permissions, capabilities, add menu page" }
RSS Feed Custom Title? For some reason my RSS feed is repeating the site title twice without a space, obviously quite annoying. BlognameBlogname for example. Is there any hook i can use to have a custom title for the RSS Feed? So i could have a title 'This is My RSS Feed for Blogname' or anything i wanted? Is this possible or am i stuck with the double name. Thanks for any help.
**Edited** : Bad answer removed. Here is the working code: function custom_blogname_rss($val, $show) { if( 'name' == $show ) $out = 'Custom Blog Name'; else $out = $val; return $out; } add_filter('bloginfo_rss','custom_blogname_rss', 10, 2); Don't forget to change _Custom Blog Name_ to something useful. Put that code into a plugin.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "hooks, rss" }
Can a plugin deactivate itself? We have a situation where a couple of our longstanding plugins (Google Analytics is one) are currently offering the option to " **Activate** " them. This figures, because Google Analytics traffic stopped dead a while back. So it seems as if it _did_ turn itself off. Is this possible? Can the plugin's original author issue an update or something which causes it to go wrong and deactivate? Or do we have to assume someone deactivated it by mistake?
As far as I know, a plugin can be deactivated in these conditions: * manual deactivation * failed plugin upgrade * remove or rename the containing folder * changing the active plugin list in the database Hopefully someone else will come through and add to this if I missed any.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "plugins, google analytics, deactivation" }
Wordpress Image uploads plugin needed I am looking for a wordpress plugin where I can upload images and store them into a category. For example I would have say..10 images to upload, I would give the album a name or date and then upload them. Is there any plugins around that can do this?
Sounds like NextGen Gallery would be a good fit - <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Using shortcodes to communicate my page design I came across this page < and on it there is this message: "The entire code of this sample page is available in the Shortcode Generator". Lets say i gave someone this theme and wanted to produce his/her own page look just like the one shown without inserting one shortcode after another.Can shortcodes be used to make one big page "template" such that with one insertion of shortcode,the design in the services page shall be inserted and the user shall only swap the dummy content for his/her own?.
If you are going to use that shortcode inside post/page content, then you can build any layout/design with that shortcode. You can do even more if you are calling `do_shortcode()` in your theme. Technically its possible to do it and whether it would be a good implementation or not depends on the use case. Like for specific layouts inside the page content, this is an excellent choice but for using it as a substitutes to page templates, that will be a bad design choice. You can do pretty much inside a shortcode, point is when you should. Read more on implementation here - <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "shortcode, page template" }
Creating a user's own folder on user registration I need a plugin or some guidence on creating a user's own folder on user registation. For example...A user clicks on Register and registers ... I need wordpress to create a directory which would be linked with this user. The reason I want to do this is because I am going to work on building a dashboard where a wordpress template will display the contents of this user's own directory. Let me explain further step by step: (Note: "Not Req" means I don't need help with this step) 1. User Registers and wordpress creates a directory called the same as the username. 2. User uploads images to that specific directory via ftp or upload - **"Not Req"** 3. I create a template that would display the content of the directory / sub (images) in some kind of tree format. Right now, what I need to do is step 1. Hope this helps.
You can use the `user_register` action to hook into the register proces and then create the user directory with `wp_mkdir_p`. function create_user_dir($user_id) { $user_info = get_userdata( $user_id ); $upload_dir = wp_upload_dir(); $user_dir = $upload_dir['basedir'] . '/user_dirs/' . $user_info->user_login; wp_mkdir_p($user_dir); } add_action( 'user_register', 'create_user_dir'); This example makes a directory in `uploads/user_dirs`. < <
stackexchange-wordpress
{ "answer_score": 6, "question_score": 5, "tags": "plugins, plugin development" }
Require file in functions from theme directory using PHP I am trying to dynamically get the facebook php sdk from my current themes folder. I am writing this in my functions.php, but all my attempts break the site. See my attempts below... require template_url('/') . 'facebook-php-sdk-6c82b3f/src/facebook.php'; require get_bloginfo('template_url') . 'facebook-php-sdk-6c82b3f/src/facebook.php'; Can any one help me understand why this does not work? Thank you very much.
Use `get_template_directory()` instead , require doesn't work with http://
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "functions" }
Changing the permlink and SEO I have a doubt on changing my permlink structure for the second time. What happened was I have moved my old website to the wordpress blog by copying all the posts. After the migration, i have set the 301 redirect to the new url of wordpress and now it is updated in the google. After that I found the permlink is not good I am changing the structure to shorter url. I found the old urls are correctly redirected to the new one i think it is handled by the wordpress. Will it be a 301 redirect by the wordpress? Please help me.
You can check the status of the redirect using any number of developer tools (chrome can do this by default). I believe the default redirect that wordpress does when the post title is changed is a 301, but I could be mistaken. If you need finer control (or would like regex support), the Redirection plugin is a great option, and it supports 301, 302, 307, and 404 codes out of the box.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "permalinks" }
How to get the deleted category id? I want to do some action at the time of deleting a category using that category id. Is it possible to get the category id?
Use the `delete_category` action, which passes category id as an argument: function my_category_delete_function( $id ){ // do something with category $id } add_action( 'delete_category', 'my_category_delete_function', 10, 1 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
CSS classes for theme Does anybody know predefined (suggested by WP) CSS classes which should I use in my theme? I have seen somewhere in Internet a list of all CSS classes, which are used in WP theme, but can't find it. **UPDATE:** I have found the site where I've seen this list: <
There are many CSS classes generated by WordPress, depending on context. The Theme Review Guidelines include the following, WordPress-generated CSS classes: * Alignment Classes: * .aligncenter * .alignleft * .alignright * Caption Related Classes: * .wp-caption * .wp-caption-text * .gallery-caption * Post Classes: * .sticky * Comment Classes: * .bypostauthor Then, there are the body classes generated by `body_class()`. Then, there are the post classes generated by `post_class()`. Then, there are the comment classes generated by `comment_class()`. Then, there are the menu item classes generated by `wp_nav_menu()`.
stackexchange-wordpress
{ "answer_score": 16, "question_score": 9, "tags": "theme development, themes, css" }
Migrate comments to Disqus Is there a way to migrate all comments on my blog over to Disqus somehow? Thinking about using Disqus rather than the regular WordPress comments, but I don't want to lose the comments that are already written.
!Disqus export comments During the process of installing the Disqus Comment System plugin on WordPress, it actually allows you to export your comments to Disqus, as shown in the screenshot above. And they've quite a helpful documentation as well: * Install Disqus on WordPress (self-hosted) * Exporting comments from WordPress to Disqus Not to mention the numerous 'how-to' videos on YouTube. :)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments, migration, disqus" }
When I re-save a post with [code] sections, the entities are double-escaped (> becomes &gt; etc) I've a hard time googling for this issue. On my blog, whenever I update an existing page, code sections are doubly escaped. I.e., on a recent page I have find /V "QWERTYUIOPPO" < calc.exe:yourads.txt and after a recent edit it has become: find /V &quot;QWERTYUIOPPO&quot; &lt; calc.exe:yourads.txt When I save it once more, it will escape the entities once more: find /V &amp;quot;QWERTYUIOPPO&amp;quot; &amp;lt; calc.exe:yourads.txt Etc. Needless to say this is nasty. For pages containing a lot of code this is a real bummer. Until now I just did some search and replace actions, but this can't stay forever. Does anybody recognize this issue? Here's an example page that illustrates this issue. Also in the screenshot for future reference (as I sure hope to solve the issue on my pages sometime soon). !enter image description here
I face this issue quite often on my own site where I publish code tutorials. Unfortunately, there isn't a good solution. Instead, I recommend this workflow: * Use the WYSIWYG editor to build your article content leaving placeholders for your code snippets. * Switch to the HTML editor to add your code snippets The visual editor (TinyMCE) tries to escape code-like characters for display. It wasn't meant for writing code snippets in the first place.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "posts, syntax highlighting, escaping" }
Should I remove transients from the wp_options table? I have been doing some cleaning up in the database of one of my WordPress installs, and I noticed that the `wp_options` table was about 2.1mb, and had 1200 rows. I've gotten it down to around 800 rows, and 1.2mb. However, there are a bunch of transients. Should I remove these? I know they don't autoload, so it probably isn't causing strain on the database. Most of the transients have formatting like the following: _site_transient_browser_03df11ec4fda7630a5... _site_transient_browser_065e09a1287aadfb4d... _site_transient_timeout_browser_03df11ec4f... _site_transient_timeout_browser_065e09a128... _transient_feed_1a5f760f2e2b48827d4974a608... _transient_feed_f8e8c12cc5c787789728d7481a... _transient_feed_mod_e6460a14e5784b3ee64f91... _transient_timeout_feed_1a5f760f2e2b48827d... So, is it worth taking the time to remove these? Thanks for reading! Any thoughts are appreciated.
This is not an amount that is likely to cause performance issues. However if you are concerned about leftover transients it is worth looking into if any code you are using is consistently "leaking" them (creating transients that are never removed). See Are transients garbage collected? for relevant discussion and some code snippets.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "database, optimization, options" }
Overide a function that is inside a plugin I would like to change the behavior of one function in a plugin. Instead of rewriting the file and having to deal with updates I would prefer a solution that works similar to the way add_filter works for the wordpress core. Is this possible using either php or wordpress?
If there are hooks in the function, this is possible, if not, there may be pluggable functions, where you can replace their function with your own custom function. I have not seen pluggables in plugins frequently, but with most of the more popular plugins, you do see actions and filters. You may be able to interact with the plugin by changing the behavior of the functions which it calls to your desired effect. This can be tricky, and often results in hacky solutions, but it's better than nothing. If there is not a way to interact with the plugin, then you can fork the plugin's code. Naturally, this is the least desirable, but it may be your only option.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "plugins, php" }
How to get Post ID with the Add Filter Function I'm writing a plugin and am trying to figure out how to add data to the end of a post based on some Custom Meta Information. So i've done this so far: add_filter('the_content', 'AppendMeta'); And here is the "AppendMeta" function AppendMeta($content) { echo $content; // Echo out post content $PersonName = get_post_meta($post->ID, 'PersonName', true); echo 'Person: ' . $PersonName; } That code works if I replace $post->ID with the id of the post, but I need it to work based on the post the user is currently navigating. How would I pass the post id in as a parameter? $post->ID doesn't work in this scenario and I can't find out why.
Nevermind, found out I can use `get_the_ID();`. This function will return the post id inside the `the_content` filter. The function simply declares the global `$post` object and returns its ID. add_filter('the_content', 'wpse51205_content') wpse51205_content($content) { echo $content; // Echo out post content $PersonName = get_post_meta(get_the_ID(), 'PersonName', true); echo 'Person: ' . $PersonName; } If you don't want to use `get_the_ID()`, you simply need to declare the `$post` object global before using it: add_filter('the_content', 'wpse51205_content') wpse51205_content($content) { global $post; echo $content; // Echo out post content $PersonName = get_post_meta($post->ID), 'PersonName', true); echo 'Person: ' . $PersonName; }
stackexchange-wordpress
{ "answer_score": 10, "question_score": 4, "tags": "plugin development, filters" }
Only show div on homepage/blog index in wordpress/php I have a wordpress site. I have a div that I only want to appear on the homepage (in the header). What type of php if statement do i need... In other words: only show .... in the header of the main blog index page. Problem is the header itself is loaded in every page. Thanks!
See: < <?php if(is_home()): ?> <div>Your div.</div> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 4, "tags": "php" }
Retrieving multiple values to the Post Meta (using an array) I'm having a problem retrieving post_meta values that I have stored in an array. I use this for storing the array: add_action( 'comment_post', 'add_food', 1 ); function add_food(){ global $post; $testvalues = array('bread', 'cake'); update_post_meta($post->ID, 'food', $testvalues); } and this for retrieving it: add_filter('the_content', 'print_food'); function print_food($content){ global $post; $custom_fields = get_post_custom($post->ID); $food_field = $custom_fields['food']; $content .= $food_field[0]; return $content; } however, this is added to the content of my page: a:2:{i:0;s:5:"bread";i:1;s:4:"cake";} The technique works fine for the comment_meta. What am I doing wrong here?
Aha! I think I found your answer. Two facts: * The description of the $meta_value argument on add_post_meta() functions's codex page notes: > An array will be serialized into a string. * The $single argument's description on the get_post_meta() function's codex page notes: > If set to true then the function will return a single result, as a string. If false, or not set, then the function returns an array of the custom fields. This is not intuitive. For example, **if you fetch a serialized array with this method you want $single to be true to actually get an unserialized array back**. If you pass in false, or leave it out, you will have an array of one, and the value at index 0 will be the serialized string. (emphasis added) Therefore, this [untested] snippet should get you your food array as an array rather than a serialized string. $food_field = get_post_meta( $post->ID, 'food', true );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "array, post meta" }
get_page() - Only variables can be passed by reference When I try to use `get_page()` function I get the error message: Only variables can be passed by reference But what doesn't make sense is that I can use a work around that blows my mind: # First test $test1 = get_page(49); **Returns error message** Only variables can be passed by reference # Second test $page = get_page_by_title( 'About' ); $test2 = get_page($page->ID); echo 'ID:'.$page->ID.' Post title: '.$page->post_title; **Returns no error** ID:49 Post title: About Can anyone shed some light on what I'm doing wrong?
Correct to your first test: $id = 49; $test = get_page( $id );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages" }
what does $options = get_option('test_theme'); do? I'm trying to set up theme options so they save with AJAX, I found this tutorial < it's calling $options = get_option('test_theme'); but I don't understand what that is returning. it calls this right before the form, presumably to loop through the options? the data is actually getting saved, it's just not being represented when the page is refreshed.
This sets $options to the value of test_theme in the database, you can go to phpmyadmin and the wp database and the wp_options (if wp is your prefix) and do a search on option_id row and you'll find it there. To get this option it should be saved before in the database using add_option() and update_option(), for more info check out the Options API
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, jquery, ajax, theme options" }
Whole bunch of errors on WP website - media upload, edit slugs, edit screen not working I am having a problem which I didn't meet before. I took a client website for just a small bunch of modifications, so I wasn't there when WordPress was installed or when the theme was developed. But when I enter the admin area, I can not upload media, I can not edit slugs, and on top of all, the "edit" screen for pages and posts is not working: I can't see the text I am typing, I can't see the format buttons, I can't use the visual/html buttons (please see attached). The website in question uses Genesis framework along with a Genesis theme child. It has a bunch of plugins installed. Now I am asking you, in your experience, what could cause these problems? \- WordPress was installed wrong \- A plugin is causing the problems \- It has something to do with Genesis \- ...? problem screenshot What do you think?
I had the same problem, but some extra and different plugins, after 2 days of disabling plugins one by one, checking theme files etc, etc, I decide to start from 0, Backup database, (all post, etc,~) and just re install. Not a beauty, but it will solve the problem faster than you searching for the needle on the haystack. Possible quick solution - Reinstall all including Plugins.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "uploads, errors, media" }
Can't get CSS Into the Head via add_action I'm trying to add some CSS to the head part of the CSS but I can't get it to work (I want to add it to the head before the Theme CSS so the plugin user can easily over-ride plugins default CSS without !important over-rides). Here is what I tried: <?php add_action('wp_head', 'addCSS'); function addCSS() { wp_register_style( 'prefix-style', plugins_url('AddToCartStyles.css', __FILE__) ); wp_enqueue_style( 'prefix-style' ); } ?> EDIT: Maybe the way I worded this was confusing. I Don't want to include the CSS in the plugin Admin Page, I want to include the CSS in the regular theme pages (e.g. the pages the end user will actually see).
You don't call enqueue or register functions hooking into the `wp_head` hook. At that hook its too late to add more, I guess, unless you play with priority parameter. Use the init hook to call `wp_enqueue_*` & `wp_register_*` functions. Do it like this: <?php add_action('wp_enqueue_scripts', 'addCSS'); function addCSS() { wp_register_style( 'prefix-style', plugins_url('AddToCartStyles.css', __FILE__) ); wp_enqueue_style( 'prefix-style' ); } ?> This should work! Just changed the hook in your code.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "plugin development" }
How to remove specific categories from posts? I need to select all posts from database without fetching some categories. For example I fetch posts with this code: $featuredPosts = new WP_Query(); $featuredPosts->query('showposts=40'); So, now, how can i remove categories with id of: 22, 23 and 24?
Make query like this: $query = new WP_Query( array( 'posts_per_page' => -1, 'category__not_in' => array( 2, 6 ) ) ); 2, 6 being the category ID you want to exclude.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories, wp query" }
Add a Save Button to Custom Meta Box > **Possible Duplicate:** > Adding submit or update button to custom metabox? I added a Meta Box Like So: add_action('add_meta_boxes', function() { add_meta_box('CNMeta', 'Custom MetaBox', 'CNCustomMeta', 'post'); }); I also added a thing that saves all of the meta information like this: add_action('save_post', function($id) { if(isset($_POST['CNPrice']) ) { update_post_meta( $id, 'CNDetails', strip_tags($_POST['CNDetails']) ); } }); So they can save it by updating the post, it would be nice if I could add a submit button at the bottom of the meta box that also updates the post (and doesn't popup a warning saying "You are about to leave this post unsaved" How would I do something like that?
To update a post. <input id="publish" class="button-primary" type="submit" value="Update" accesskey="p" tabindex="5" name="save">
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugin development, post meta, metabox" }
Set generic reservation form for custom post type I want to create a simple reservation (reservation.php) form for a custom content type (houses), i have created the reservation.php in the theme directory. The question is: How can i link to this general reservation form from the custom post type and pass the post id via `POST` or `GET`, so i can retrieve some information like post title, taxonomy, and so on. A plus would be do this with a nice permalink like `mysite.com/lake-house/reservation/`
If you have to make it a separate page that's available by visiting a permalink, you have to think what happens when user visits this page directly, without visiting the single post (house) first. If you know how to handle it, the easiest way would be to make the reservations.php it's own page template and just link to that page from within your single post, while adding post ID as an argument. The best way to do this, however, is, like kaiser suggested, include the reservation form in the single post template.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, templates" }