INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Display a list of users with avatar filterable with alphabets I'm trying to create a page which should display a list of users with the role "Author" only and exclude all other default and custom roles. I also want them to be filterable by alphabets, so if I click on "A", or "B", and so on, the users starting with that alphabet should show on the page. I tried to use wp_list_authors but that's very limited to what I need here. (code below) <ul> <?php wp_list_authors('exclude_admin=1&optioncount=1&show_fullname=1&hide_empty=1'); ?> </ul> Any idea how this can be done or any plugin for this?
Alright, I've got a plugin here which sorts it out. amr users wordpress plugin
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions, customization, filters, users" }
Auto Stock Update after Order cancel from Admin of Woocommerce? I recently implemented Woocommerce and in trial session I found following issue: **1.** Initially, I provide 10qty for Product1. **2.** place a Dummy Order from front-end of 10qty of that Product1. **3.** Then After that I see Product1 is Out of Stock. **4.** From Admin of woocommerce, If I cancelled that dummy order or reduce the product qty on that order, It Doesn't Update the Stock Qty of that product1. And I still see the Out of stock label on that product even after that order has been cancelled which reserved this qty. Hence is their any way to Auto-Manage this Stock Updates between orders and Inventory.
Sorry to Trouble this Slept world of Wordpress. I got My answers From Awaked wordpress world,directly from Author of Plugin here: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "plugins, order" }
How to get the url to tag & category base set by the user? I'm searching for half an hour now on how to get the url/permalink base in Wordpress (the 'category' and 'tag' value set in the backend). Could you please point me in the right direction? I want to dynamically print the following - but only replace the `tags` and `category` part (not the tag/category itself): <a href="/tags/my-tag">My Tag</a> <a href="/category/my-category">My Category</a>
You really shouldn't need this, as you should be outputting the URLs via the API: `get_tag_link`, `get_category_link`, `get_term_link`. However, for the sake of answering the question, they're stored in options: get_option( 'tag_base' ); get_option( 'category_base' );
stackexchange-wordpress
{ "answer_score": 9, "question_score": 3, "tags": "categories, theme development, permalinks, tags" }
Rewrite vs Redirect from ?p={ID} WordPress does a 301 from ` to ` but I thought a URL rewrite was different from a redirect and therefore this wouldn't result in a 301. Can anyone clarify?
A _rewrite_ enables ` to translate internally to the proper query vars to load the requested post. The shortlink does a 301 _redirect_ to the pretty URL because it should not be possible to access the same content from more than one URI. This is so a search engine won't index the same post under two URIs.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "url rewriting, redirect, htaccess" }
bulk deleting empty items in the media library I wrote a function, which should rename my attachments, based on the post title. Unfortunately this function created over 10.000 empty instances in my media-library, before I was able to stop it. The instances are all attached to a single post, which I could delete if it's necessary. I'm really sorry to bother you with the ask for help, but I'm a bit scared to screw things up again.
Since I didn't expected an answer to this question I tried it with wp_delete_attachment();. I wrote this function on a random page of my site (since the site isn't live yet) and executed it from there. $attac_kill_ids = range(1235, 22686); //fill an array with the post_ids from the empty instances foreach( $attac_kill_ids as $kill_id ){ $kill_post = get_post( $kill_id ); if( $kill_post ) { wp_delete_attachment( $kill_id, true ); echo '<br />killed #' . $kill_id; } else continue; } ' _delete_ ' would be more precise, but ' _kill_ ' sounds more dangerous and keeps me concentrated thereby. Then I used this line in phpMyAdmin to set the ID-counter back to 810 ALTER TABLE wp_posts AUTO_INCREMENT=810
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "media library, bulk, customization" }
Possible to enqueue scripts and CSS to Multisite Network dashboard? Is it possible to enqueue scripts and css **only** to the Network Admin Dashboard? To edit the network admin menu, you have this hook: `network_admin_menu`, so I also tried `network_admin_enqueue_scripts`, but this didn't work. Thanks! Roc.
You can use the global variable `$current_screen`. It has the property `is_network`, with a boolean value, that indicates if we are in `/wp-admin/network/` or not. add_action( 'admin_print_scripts', 'network_scripts_wpse_91699' ); function network_scripts_wpse_91699() { global $current_screen; if( !$current_screen->is_network ) return; wp_register_script( 'test', plugins_url( 'test.js', __FILE__) ); wp_enqueue_script( 'test' ); } This action hook can also be used like add_action( 'admin_print_scripts-site-new.php', 'callback' );` and it will only print in the screen `/wp-admin/network/site-new.php`, so there's no need to check if the current screen is a network one or not.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "multisite, wp enqueue script, dashboard, network admin" }
Filter post before *editing* I know there are a lot of hooks in WP for altering a posts content (and other fields) before the post is written to the DB upon saving; but what I am interested in doing is running my custom filter before the post is _loaded_ for _editing_. So basically when my custom post type is loaded by /wp-admin/post.php?post=##&action=edit, I would like to run my filter on it before the content is displayed in the WYSIWYG editor. Is that possible or no?
You can use the `the_editor_content` filter: function wpa_editor_content( $content ) { global $post; return "this post's id is $post->ID " . $content; } add_filter( 'the_editor_content', 'wpa_editor_content' );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "posts, filters, hooks" }
JavaScript Errors when Loading NextGEN Gallery I am using NextGEN Gallery and NextGEN GalleryView. _**(Editors Note: Not sure what this sentence means)_** But I can't get the image those image was hidden. When I check the css and js files, all of file are included when I check in firebug the below error is shown: jQuery.timer is undefined ...for: jquery...r=1.1.2 (line 144) jQuery("#ngg-gallery-1-133").galleryView is not a function easing: 'easeInOutQuad'
The GalleryViews plugin hasn't been updated in a while. jQuery has changed a lot since then. You'll most likely need to either downgrade jQuery (not recommended by any means) or upgrade the plugin's JavaScript to work with later versions of jQuery. It looks like there aren't newer versions of the scripts so you may have to either do custom modifications or ditch the plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "gallery, plugin nextgen gallery" }
replace html entities in posts between pre tags I run a wordpress blog with a syntax highlighter plugin (Crayon). The plugin highlights code between pre tags, example: <pre class="lang:languageid" title="example"> some code </pre> Wordpress sometimes replaces characters suchs as `" & < >` with html entities which are shown in the code `&quot;` `&amp;` etc. I tried several plugins that should prevent this but they don't (always) work. Is there an easy method to bulk edit old posts and search for entities between `pre` tags en replace them with the character? Or would it be easier to use a replace function on display and replace entities with their characters? Any suggestions to prevent this in the future are welcome as well (perhaps extend/modify crayon?). I usually write my blogs with Windows Live Writer but the behaviour also occurs when editing posts with the builtin editor.
Both answers are not the full solution, seems that if I combine them I am very close (just need to fix the replace part). The regex from @hasinhayder answer seems to work well in the plugin that @nathanpowell suggested. There is no way to split points, common best practice seems to be to combine both answer in your answer and accept that one. I hope that's ok for both? The answer is then: Use the Search RegEx plugin for wordpress and use a regex expression `|<pre.*>(.*)</pre|isU` to match html entities within pre tags.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "syntax highlighting, customization, pre" }
how to "not" display new posts with a specific category on the main page? I've read this and this but I'm just a basic user. I have a "technical" blog that more and more people visit. I'm a freelance, and now, when someone hears about me, he/she wants to search for me, and my blog is #1 (before anything else). The problem is that it was a personal blog, and now it becomes professionnal. So I would still like to post some articles, but when there are some specific tags (like "games", "family" and so on), I'd like them **not** to appear on the main page but only under the category filter (` ` would be ok, but _not_ ` How to do this?
There is even an example in the WordPress codex here for this: < function exclude_category( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'cat', '-3,-8' ); } } add_action( 'pre_get_posts', 'exclude_category' ); Just modify the category IDs (replace -3,-8 by your category IDs preceded by the minus sign) and put it in your functions.php or your plugin code. The WordPress codex states the following: > `query_posts()` is the easiest, but not preferred or most efficient, way to alter the default query. The preferred way is hooking into `pre_get_posts` and altering the main query. This way you just alter the main query instead of throwing away the results of the first query and running a second.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "categories, blog" }
User registration on sub site I have configured multi-site wordpress. I have some sub-sites as like **site1.mydomain.com** and **site2.mydomain.com**. Now i just want to enable the user registration on my sub-sites. When a user clicks on register link in any sub-site (site1.mydomain.com or site2.mydomain.com) **it takes them to the main site** (mydomain.com) and register them as an administrater of another site. so he will be having another site as (site2.mydomain.com). But i want is that, if the user clicks the register link on the sub-site (ex:site1.mydomain.com) they **should be register only on that sub-site itself and become the member only for that site with some roles**. I am very new to wordpress. I dont even know the coding standard of the wordpress. But i hope i can manage these things. Now i am just roaming around with the plugins. Please some one help me for this.
What you've described is default behavior for WordPress where when a user registers on a subsite, they're really registering with the root site. Check out this plugin, which looks to help with new user sign ups and adding them to the right subsite. < If that plugin isn't what you're looking for then perhaps this one is. < A couple options for you to check out. A word of advice, **be sure to back everything up (including your database!)** in case something goes wrong, you have a way to go back to a working site.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "multisite, user registration" }
Theme Check: Could not find post_class I've inherited a theme from a another developer that I've re-styled for a client. We're just about finished, but I thought I'd run it through the Theme-Check plug-in to see if there's any errors or problems. Unfortunately there's a ton. I've gotten rid of most of them, but I have one Required left: REQUIRED: Could not find post_class. See: post_class I've read the WP page on post_class, but as a relative newcomer I still don't understand what it is, or why it should be _required_. What should I do to fix this?
## What it does `post_class` adds classes to the posts on a post by post basis, usually adding them to some kind of post "wrapper". This allows for the targeting of posts with CSS rules according to various criteria-- category, tag, sticky, format, etc. That is, theme authors, plugin authors, and individual users can write CSS rules based on the classes added by `post_class` and get very fine grained control over layout. ## Why you want it While I am not a canonical source, I am sure it is required according to the WordPress Theme guidelines to ensure a minimal functionality across themes. If you aren't submitting your theme to the WordPress repo you can do what you want. There are no WordPress Theme Police to track you down and spank you, but `post_class` and the related `body_class` are very useful and easy to implement. I see no reason not to use them.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "theme development, themes, debug, post class" }
Should all references to a text domain be to my current theme? I'm running Theme Check on a theme I've inherited and I've come across lots of recommendations like this one: RECOMMENDED: Text domain problems in loop.php. The twentyten text domain is being used! The site has no plans for being translated, so what's the best thing to do in this situation? Replace every reference to `twentyten` to my theme's text domain, or just remove all references of a text domain at all? The WordPress documentation is a little confusing :-/
You can remove all the translation references if you don't plan on translating it. You can also leave it in place, it shouldn't hurt anything.. If you want to remove it, go through your theme files and find references to `__(' Your Text', 'Domain')` and just change it to the "Your Text" portion. (Sometimes, you may even see `_e('Your Text, 'Domain')`).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, themes, debug, textdomain" }
wp_editor in text mode only(without TinyMCE) Is there a way to call `wp_editor` for a meta box using just the text/HTML mode without TinyMCE. I think the deprecated function pre-3.3 did this but I'm not sure how its done now.
Yes, it's possible to set it to false. The full parameters list is in the file `wp-includes/class-wp-editor.php`. These are the default values for the **`$settings`** array when calling `wp_editor( $content, $editor_id, $settings );`: array( 'wpautop' => true, 'media_buttons' => true, 'textarea_name' => $editor_id, 'textarea_rows' => 20, 'tabindex' => '', 'tabfocus_elements' => ':prev,:next', 'editor_css' => '', 'editor_class' => '', 'teeny' => false, 'dfw' => false, 'tinymce' => false, // <----- 'quicktags' => true ); Check the source code for details of each parameter. I've just made a small test with a meta box and works ok.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "wp editor" }
Do I really need the div class entry? I was wondering if it's really neccessary to keep the `<div class="entry">` in the page.php file (or any other template for that matter). I typically use a blank HTML5 wordpress theme and it doesn't have any declarations within the CSS file for that class. So I just wanted to get other opinions on it. Thanks!
No specific markup is required in a theme. The only exception are themes published on wordpress.org, they have to follow the guidelines. And even there, `<div class="entry">` is not required. The only parts you have to use are these: while ( have_posts() ) { the_post(); print '<h2>' . get_the_title() . '</h2>'; the_content(); wp_link_pages(); }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "theme development, themes, pages, page template" }
Subdomain and subdirectories together in one installation I'm currently want to develop my design company website and choosing wordpress as my CMS. How do I should install the wordpress when I want the domain structure like this: * Blog = blog.example.com * Portfolio = example.com/portfolio/... * Shop = shop.example.com = using WooCommerce I'll be glad if someone would help, because I really have no idea to config.
If you want sections in a subdomain _and_ in subdirectories, use a multi-site installation. See Create a Network and our tag multi-site. Then you set the the blog and the shop as separate sites, and the `portfolio` as a custom post type or as a regular page in the main blog.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "multisite, installation, domain, configuration, customization" }
Archive - same title for the first two posts I created an archive page called archive.php Here I include header / footer and this code: <?php if (have_posts()) : while (have_posts()) : ?> <h1 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?><a/></h1> <?php the_post(); the_content(); ?> <br /> <?php endwhile; endif; ?> The problem is that when there are more posts for a month, the first two posts have the title and permalink of the first post. How can I fix this? Anticipated thanks! **EDIT** Good advice toscho. I fixed it, here's the solution: <?php while(have_posts()) : the_post(); ?> <h1 class="entry-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?><a/></h1> <?php the_content(); ?><br /> <?php endwhile; ?>
You have to call `the_post();` before you use `the_permalink()` or `the_title()`. Both functions work with a global `$post` object that will be set up by `the_post();`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, plugin development, widgets, archives" }
How to use "menu_order" field for posts? I have a special case where I'd like to order posts in a custom order and it would be great to use the "menu_order" field that is normally only used for pages. What would be the best way to expose that in the WordPress admin UI?
Apparently it's as easy as: add_action( 'admin_init', 'posts_order_wpse_91866' ); function posts_order_wpse_91866() { add_post_type_support( 'post', 'page-attributes' ); } And then doing the query: $order_posts = new WP_Query(array( 'post_type' => 'post', 'post_status' => 'publish', 'orderby' => 'menu_order', 'order' => 'ASC', ) );
stackexchange-wordpress
{ "answer_score": 46, "question_score": 30, "tags": "wp admin, menu order" }
How to highlight most recent posts in a list I want to be able to highlight the most recent post in a list of recent posts. By highlight I mean bold or style slightly differently from the other posts. This is the code I use now: <h2>Assignments</h2> <ol> <?php $recentPosts = new WP_Query(); $recentPosts->query('showposts=15&cat=188&order=ASC'); ?> <?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?> <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a> </li> <?php endwhile; ?> </ol> This simply returns a numbered list. I would like to style differently the most recent post (i.e. the last item on the list). How can this be done?
I found a better solution: <h2>Assignments</h2> <ol> <?php $recentPosts = new WP_Query(); $recentPosts->query('showposts=15&cat=188&order=DESC'); ?> <?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?> <?php $ageunix = get_the_time('U'); $days_old_in_seconds = ((time() - $ageunix)); $days_old = (($days_old_in_seconds/86400)); ?> <?php if ($days_old > 3) : ?> <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a> </li> <?php else : ?> <li><strong><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></strong></li> <?php endif; ?> <?php endwhile; ?> </ol>
stackexchange-wordpress
{ "answer_score": -1, "question_score": 0, "tags": "posts" }
Is it possible to have users register without having a password? I'm developing a plugin and I wanted to allow users to just subscribe to a custom user level without having a password sent to them via email. this level will not be able to contribute to the site, so just reading capability. I will use this subscription to add the email to a mailing list and to allow the user to buy on this website, nothing else. Do you have any suggestions on how to build this up?
If you're just wanting to add them to a mailing list, you really don't need to create a user account for them. Just use something like this: < or Gravity Forms to capture their email addresses. The fact that you then say "to allow the user to buy on this website" seems to suggest that the user _will_ need to log in - how will you authenticate them otherwise?
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "password, user registration" }
Function in functions.php by url I want to use wordpress content in external mobile app. I need an URL address to get content from function located in `functions.php` for example: function test() { return 'it works'; } What I need is an url address (` which will return a value from function test. I hope that I wrote it clearly. Sorry for my language mistakes.
You can check for the presence of a specific query variable, so ` You check for this on the init hook and if it isn't there you just quit early and WP goes about it's business. If it is there, you can then do something, just don't forget to exit at the end or the full page loads and that can mess up the response you are trying to send to your app. function wpa_91930() { // if query var is not present just return if ( ! isset( $_REQUEST['my_listener'] ) || 'test' != $_REQUEST['my_listener'] ) return; // send response echo "it works"; // don't forget to exit when you are done exit; } add_action( 'init', 'wpa_91930' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, urls" }
Removing any and all inline styles from the_content() For one of my current projects, I had to transfer blogposts from an old Wordpress site to my project. Things went smoothly until I've seen that all the posts were copy pasted from Word, leaving this before pretty much every paragraph: <span style="font-size: medium; font-family: georgia,palatino;"> And at some places things like these: <p style="text-align: justify;"> <p style="text-align: justify;"><span style="font-size: medium; font-family: georgia,palatino;"><strong><span style="color: #000000;"> So because I don't have the 40 hours (even less the patience) to just go into every post (there's about 100) and remove those unwanted tags, I'm looking for a filter that would just remove all style (except maybe if it contains text-decoration:underline) elements before outputting the_content() Is there such a thing?
If we want to remove all inline styles, then just simply need to add the following code in functions.php. add_filter('the_content', function( $content ){ //--Remove all inline styles-- $content = preg_replace('/ style=("|\')(.*?)("|\')/','',$content); return $content; }, 20);
stackexchange-wordpress
{ "answer_score": 18, "question_score": 7, "tags": "posts, filters, the content" }
Minimum Word Count Before A Post Can Be Made Pending Review I'm looking for a way to check that a post has a minimum word count before allowing it to be sent for review (added to the pending post status). Below is the code I have: if (current_user_can('contributor')) { function minWord($content){ global $post; $num = 150; //set this to the minimum number of words $content = $post->post_content; if (str_word_count($content) < $num) wp_die( __('Error: your post is below the minimum word count.') ); } add_action('draft_to_pending', 'minWord'); } This appears to "work", in that it brings up an error message when the word count is indeed below 150. However, the post is still saved as a "pending". Is there any way to prevent the post from being made pending, but instead keep it saved as "draft". Cheers Peter
Those transition post hooks run after the post is saved. You will have to interrupt the process earlier. I would hook to `wp_insert_post_data`. function minWord($data){ if (current_user_can('contributor')) { $num = 150; //set this to the minimum number of words if (str_word_count($data['post_content']) < $num) { $data['post_status'] = 'draft'; } } return $data; } add_action('wp_insert_post_data','minWord'); Seems to work when I test it. Following your code, this only effects the "Contributor" role. It does not interrupt status changes for other roles.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "save post" }
"sufficient permissions" error for admin after duplicating WP database to new install I recently copied the tables from a live WP install to a dev site for that same site. I've changed all the prefixes, the site/WP URLs, and the salt values. I can successfully log into the new dev site, but the admin account (not actually named admin) does not have admin privileges. Once I log in and am redirected to the dash, I get the `You do not have sufficient permissions to access this page.` error. I've verified through the usermeta table in the DB that admin account has `administrator capabilities` and I'm out of ideas. Any thoughts on what I might have missed in the table migrations?
So you've duplicated the tables in the DB, with the new set having the dev_ prefix? In that case, the problem is probably that you have not updated the fields within the duplicated tables that inherit that prefix. For instance, dev_usermeta will now have a meta_key called wp_capabilities. This needs to be dev_capabilities. Also, dev_options will contain an option_name called wp_user_roles. This needs to be dev_user_roles. I'm not aware of any other instances, but I may be wrong.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin, database, capabilities" }
How to add menù section to my WordPress template? I am pretty new in WordPress blog and I am developing a blog with this template: < As you can see at the top of the page there is a "menù" that only show the page in the site (at this moment: "Home" and "Pagina di esempio"). This menù is showed by the following lines of code into the header.php file: <?php wp_list_pages('title_li=&depth=1'); ?> So I think that this is not a true menù but only a list of the statics pages present on my blog. If, in the administrator dashboard I go to the menù section in the "Position of themes" square say me that: **"This theme has no support for menus but it is possible use the personalized menu widget to add every created menu in the sidebar"** So I think that my template have no definied a true menù section on the top (but only a list for the static pages). Can I add a true section where add a true menu? How can I do? Tnx Andrea
1. You need to edit functions.php andding the following line `<?php register_nav_menu( 'primary', 'Primary Menu' ); ?>` 1. Then go in admin section Apearence-Menus and create one menu 2. In the header replace `<?php wp_list_pages('title_li=&depth=1'); ?>` for example (the primary menu) with: `<?php wp_nav_menu( array( 'theme_location' => 'primary')); ?>` more details for nav_menu here
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, menus, themes, templates" }
Forgot password not working I have been trying to reset my admin password for my local install of wordpress running on MAMP. Previously had been working fine but I forgot the password but when I go through the process of 'Lost your password' I am meant to get an email with new password but it never arrives in my hotmail (also checked the junk) I know these can sometimes take a while to come through but it has been a day now.. Any ideas I could try? Thanks
Probably you dont have any mail server installed/enabled (like sendmail/qmail/postfix) in your local machine. You can still reset your admin password from database. The table "wp_users" stores the password in the "user_pass" field You can just replace the value with a md5 hash value of your desired password for the admin user. _Note: This is good for test/local environments and dont do so in Production server because it invalidates the effect of salt :)_
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "password, troubleshooting" }
How to add a class and title attribute to the link generated by next/previous post The following code <?php previous_post('%', '&#60;', 'no'); ?> <?php next_post('%', '&#62; ', 'no'); ?> returns these links, as it should <a href="post_address/"><</a> <a href="post_address/">></a> My question is about adding a class and title attribute so that the code returns <a class="normalTip" title="Previous Project" href="post_address/"><</a> <a class="normalTip" title="Next Project" href="post_address/">></a> I am using the iWR Tooltip plugin and would like to use it on the links for the post navigation. There is probably a simple solution by adding something to the function.php file, but I have not come up with the answer. Any ideas?
`previous_post` and `next_post` are deprecated. you should be using `previous_post_link` and `next_post_link`. That function applies the `{$adjacent}_post_link` filter. You can use that to get what you want. A very, very crude example: function construct_np_attr_wpse_92086($matches) { if ('prev' == $matches[1]) { $np = 'Previous'; } else { $np = 'Next'; } $ret = 'rel="'.$matches[1].'" class="normalTip" '; if (!empty($np)) { $ret .= 'title="'.$np.' Project"'; } return $ret; } function add_attr_to_np_links_wpse_92086($link) { return preg_replace_callback('/rel="([^"]+)"/','construct_np_attr_wpse_92086',$link); } add_filter('next_post_link','add_attr_to_np_links_wpse_92086'); add_filter('previous_post_link','add_attr_to_np_links_wpse_92086');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, next post link, previous post link" }
Collect Data from NEXT item while in loop I am trying to get the value of a custom field. The trick? I'm in the loop, currently printing out 2 of 5 for this example. I would like to get some info from 3 of 5 (or even 1 of 5) while printing out info on 2 of 5. I hope that makes sense. Any help would be great!
As you posted no code and little in the way of exactly what criteria you are using, I can't really writ functioning code but inside your Loop try: var_dump($posts[$wp_query->current_post -1]->post_title); That is, `$posts[$wp_query->current_post -1]` is the previous post. You can change `-1` to plus or minus whatever value you want but the math cannot result is a figure below `0` or above your posts_per_page -1 (I think), as those don't exist. The query only gets posts on "this page". If you do need information from posts that appear on a previous or next page you will have to query for that information.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, loop" }
Format Buddypress Date Picker Output I've created a custom profile field for my BP users and I'm looking to show the value on the user's profile page. The code below does this... <?php bp_profile_field_data( array('user_id'=>get_the_author_meta( 'ID' ),'field'=>'birthday')); ?> ...But it displays it as "1985-10-30 00:00:00". How can I format this to display like this: "October, 30 1985"
I have no idea if BuddyPress has built in date functions but WordPress does and PHP does. This should do it: $bpress_date = bp_profile_field_data( array('user_id'=>get_the_author_meta( 'ID' ),'field'=>'birthday')); // $bpress_date = "1985-10-30 00:00:00"; // test echo date('F, j, Y',strtotime($bpress_date)); PHP's `date` expects UNIXTIME. That is why the date string is passed through `strtotime`. It does not work without that step. You probably want to consider using WordPress' `date_i18n`, however, which would look like: echo date_i18n(get_option('date_format'),strtotime($bpress_date)); This gives you some ability to internationalize things as the date will displayed according to the blog's date format settings.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "buddypress" }
Fetch all Posts where logged in user has commented I'm not good at sql queries so the question is: How do I list all the Posts where logged in user has left the comment? I guess it's kinda obvious that redundancy is unwanted in case user posted multiple comments to the same Post. Thanks!
It should be simple since comments are stored with a user_id if they are created by a logged in user and if not then its set to false so all you need to do is select the post id from comments that are made by user_id bigger the zero, something like this: function get_posts_with_loogedin_user_comments(){ global $wpdb; $sql = "SELECT DISTINCT comment_post_ID FROM $wpdb->comments WHERE user_id > 0 "; $post_ids = $wpdb->get_col($sql); if ($post_ids) return $post_ids; return false; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "sql" }
How to not show post_thumbnail from specific category for not logged users Can you guys help me with some examples so i can sort out the thumb posts from a specific category (EXAMPLE) to not be shown for not logged users, instead to be shown an image which tells them that they have to be logged in order to see that post. Logged users can see all thumb posts. I tried to have this question short as possible, if need anything else i will do it. Thanks
You can hook a filter to the `post_thumbnail_html` and check if its a post in that category and if the user is not logged in ex: add_filter( 'post_thumbnail_html', 'my_post_image_html_wpa92119', 10, 3 ); function my_post_image_html_wpa92119( $html, $post_id, $post_image_id ) { $category_to_exclude = "CHANGE_WITH_CATEGORY ID"; $logIn_Img_path = "CHANGE THIS WITH PATH/TO/NON-LOGGED/USERS/IMAGE"; //check if the post have that category nad if the user is not logged in if (has_category( $category_to_exclude ) && !is_user_logged_in()) return '<a href="'.wp_login_url( get_permalink($post_id) ).'"><img src="'.$logIn_Img_path.'" alt="please log in"></a>'; //if you got here then he is either logged in or its not the specified category return $html; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "post thumbnails, conditional content" }
Last posts from custom taxonomy How can I post last posts from custom_taxonomy? I tried this like, but it doesn't works. $terms=get_terms('tax_name'); $request=array(); if(count($terms)>0) { foreach($terms as $t) { $request[]=$t->slug; } } query_posts( array( 'tax_query' => array( 'taxonomy' => 'tax_name', 'field' => 'slug', 'terms' => $request, ) ) ); while ( have_posts() ):the_post();
First you really shouldn't use `query_posts` for that use get_posts or WP_Query and second `tax_query` accept an array of arrays from the codex: > tax_query takes an array of tax query arguments arrays (it takes an array of arrays) so: $terms=get_terms('tax_name'); $request=array(); foreach((array)$terms as $t) $request[]=$t->slug; $tax_q = new WP_Query( array( 'post_type' => 'post', 'posts_per_page' => 1, 'tax_query' => array( array( 'taxonomy' => 'tax_name', 'field' => 'slug', 'terms' => $request, ) ) ) ); while ( $tax_q->have_posts() ): $tax_q->the_post();
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "custom taxonomy, query posts" }
Cannot retrieve author in sidebar of single.php Within a post I can use `the_author()` to retrieve the author name, but in the sidebar of a single-post page this does not return anything. How to get metadata on the post author outside the post?
Test whether on a single post. If so, get a user object by the current posts' author ID and echo its `display_name` property: if ( is_single() ) { global $post; $author = get_userdata( $post->post_author ); echo $author->display_name; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "sidebar, author" }
Adding Relevant Post Images I want to add relevant posts at the end of each of my posts page **with an image** in my newly created website < But being a beginner this is a great problem for me as I can't do that as I don't have that much knowledge of PHP and wordpress. I search out for plugins but couldn't find a good one for the purpose. I hope to get a reply soon. A php code for the purpose is highly preferable.
This plugin sounds like what you're looking for. It uses post tags to find all relevant posts. Upload it to your plugins directory and activate it. Then just decide where you want it on your site and add post tags to get content to relate to each other. < Note. I am not the developer of this plugin, just a happy user.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, images" }
Why does this loop only work on the homepage? I've been trying to figure this out all day now. Consider the following code below: <div class="slider"> <div class="slides"><?php wp_reset_query(); if(have_posts()) : while (have_posts()) : the_post(); if(is_sticky()) : ?> <div class="slide"><a rel="bookmark" href="<?php the_permalink() ?>"><?php echo the_post_thumbnail('full'); ?><h2><?php the_title(); ?></h2></a></div> <?php endif; endwhile; else: ?> <p>Sorry, no posts matched your criteria.</p> <?php endif; ?> <div class="left-arrow"></div> <div class="right-arrow"></div> </div> </div> The loop above doesn't work on the site's pages (e.g: page 2/3/4) or 404.php, but works perfectly fine on page 1 (the index.php). Why is that and how do I fix this?
If you look at that code carefully, the only thing it ever prints are sticky posts: if(is_sticky()) : ?> <div class="slide"><a rel="bookmark" href="<?php the_permalink() ?>"><?php echo the_post_thumbnail('full'); ?><h2><?php the_title(); ?></h2></a></div> <?php endif; You stand a better chance of having sticky posts on page 1 of the index than on any page thereafter. 404 pages don't have posts at all, sticky or not. That is why they are 404 pages. I think that is why the code **_appears_** not to work on some pages, but it isn't that the code is broken, just that the conditions for printing post data and not met.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "theme development, loop" }
more tables created when create a new site Can someone suggest me an idea on this? I am using Wordpress MU. And as per my requirement every user who register on main site will have a sub-site for them. And it is working correctly. I noticed that whenever a new site is created it is creating few tables in the database as like wp_2_post, wp_2_postmeta and so on. **Whenever a new site is created, it is creating about 9 new tables in my database**. **If i have 1000 users in my site, then will it create about 9000 new tables in my database?** I will be having lot more users with my site. So, can someone tell me is this right? Can i have this much of tables in my database? Or can i do anything else to avoid this? **Is there any other way to avoid this.?**
Yes, this is the correct behavior, and no, there is nothing you can do about it in a multi-site setup. But that's usually not a problem; disk space is cheap. Maybe you could run a workaround with a single-site installation and rewrite rules to map subdomains to URLs like `/author/post-name/`. But that sounds like a collsion magnet; so I wouldn't recommend it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, table, read more, customization" }
Hiding or removing file extension displayed in HTML on attachment page I’m doing up a photography theme in WP at the moment, and I’ve already got great help on this thread (thanks Milo!) for a previous question. In that thread, I asked about displaying the file name of an uploaded file on the `attachment.php` page for that file. I’m now using the suggested answer, which uses this code to display the name: `<?php echo basename( wp_get_attachment_url( $post->ID ) ); ?>` What I need to do, however, is to display this file without its extension: so, `filename`, instead of `filename.jpg`. Is there any easy tweak to this existing PHP snippet that could do this? If not, what would be a best-practice way of achieving this end result? I should add that I’m far from a PHP expert, so take it easy on me... :) Thanks.
You could use `substr()` > Returns the portion of string specified by the start and length parameters. in combination with `strrpos()` > Find the numeric position of the last occurrence of needle in the haystack string. **Example** $name = basename( wp_get_attachment_url( $post->ID ) ); echo substr( $name, 0, strrpos( $name, '.' ) ); This will show the string (in this case a filename) untill the last occurance of `.`.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "attachments" }
Translate Woosidebars plugin strings I'm trying to translate Woosidebars strings in french using PoEdit but my french strings are never shown on the front-end. English strings are always displayed, even when I change the language (And I can see it works since other plugins strings are well translated). I've created and added a french translation file called 'woosidebars-fr_FR.po' in the 'woosidebars/lang/' folder. This file is compiled without errors (.mo) If someone had the same issue it would be great to share a solution! Regards
I've finally found why this strange thing was happening on my website. It appears there was a conflict with the WPML String translation module which was already installed and configured to translate widget strings. `fr_FR.po` file was never called because the WPML plugin was configured to use database translated strings and not `.po`/`.mo` files for widgets.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, translation" }
Retrieve Custom Taxonomies with Description and Slug I've been looking to grab a list of custom taxonomies for a custom post type with the titles, descriptions and tag but have not been able to progress or find anything helpful. **Breakdown** : * I have registered a custom post type 'submissions' * I have registered a custom taxonomy 'award-category' that is specifically for the custom post type 'submissions' * I'm trying to output a list of title, description and slug for each 'award-category' item (not post, the actual categories). Any suggestions to point me in the correct direction..
Here's how you can output all the custom taxonomies in any template for examination: <pre> <?php $args = array( 'public' => true, '_builtin' => false ); $taxes = get_taxonomies( $args, 'objects'); foreach ($taxes as $key => $tax) { $terms = get_terms( $tax->name, array('hide_empty' => false) ); // return empty ones too! foreach ($terms as $key => $term) { echo 'term ID ' . $term->term_id . ', term name: ' . $term->name . ', description: ' . $term->description . '<br/>'; } } ?> </pre> Please note that depending on how your custom taxonomies were defined your `public` value may need to be changed to `false`. Just try both. **Edit:** `get_terms()` will allow you to get all terms for the particular taxonomy.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, terms, categories" }
Comments screen in backend, how to disable Quick Edit | Edit | History | Spam | for non admins I'm trying to adjust the comments screen for non admins to my project. Right now I'd like to disable **Quick Edit | Edit | History | Spam** under any comment left for any post created by the user. Thanks!
This is done filtering the `*_row_actions`. For the Comments screen (`/wp-admin/edit-comments.php`) this is the hook: add_filter( 'comment_row_actions', 'comments_row_wpse_92313', 15, 2 ); function comments_row_wpse_92313( $actions, $comment ) { if( !current_user_can( 'delete_plugins' ) ) unset( $actions['quickedit'], $actions['edit'], $actions['spam'] ); return $actions; } I cannot see a `History` option, maybe it's included by some plugin (?). It's a matter of adding it to the `unset` list. These are the default actions in the core files: $actions = array( 'approve' => '', 'unapprove' => '', 'reply' => '', 'quickedit' => '', 'edit' => '', 'spam' => '', 'unspam' => '', 'trash' => '', 'untrash' => '', 'delete' => '' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "comments, spam, quick edit, trash" }
Is there a way to create a "copy post" link? Much like the "edit" link when viewing a post, is here a "copy post" function I can include with my theme?
Yes, Duplicate Post is what you need. You have the function that you need in <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions" }
Using static pages on Wordpress site I built a few static pages in HTML while I was practicing some techniques. I would like to include those pages (and that hard work) in a word press site. I have already created the WP page that hold the 6 items that I want to use as links to my work. I would like to link to another spot on my server or site that will then display the already-created sites and or pages. (some of my work is a complete site some of it is single-page). * Can I even do this? * Do I have to change all my already-created HTML files to PHP? * Can I link to static HTML sites? (that would be ideal) * I have tried copying and pasting the straight HTML from the pages into the text editor on the WP page, nothing happened. Thanks for your help, Josh
I would suggest making your own page template. Start by moving the files into your WordPress theme folder, and giving them a name. Like `page-foo.php`, `page-bar.php`, so on. Then on the top of these new files add PHP like the below, changing the `Template Name` to something that makes sense to you. <?php /* Template Name: Foo */ ?> Then place your code under this header. Go into WordPress wp-admin, go to Pages and add a new page. Then on the right under the `Page Attributes` widget, select the Template name that corresponds with your content that you want to display for that page.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "customization" }
Best practice to update the file header.php I would like to know, what is the best practice for updating the `header.php` file: From within WordPress editor: Appearance > Editor **or** Directly in the `header.php` file itself (in the www_root)?
This question leans towards getting some subjective answers, as I think it's a matter of personal preference. The built-in editor works just as well as any other text editor. That goes for any of your theme files, not just `header.php`. The benefit of using an external editor (like Notepad++ and using FileZilla to FTP your changes), is that you have the possibility of using 'syntax coloring'. I highly recommend Notepad++, as it supports multiple document encodings (UTF-8, ANSI, etc) and many scripting languages (with their generally accepted syntax coloring), such as PHP, JavaScript and CSS, your most common languages when working with WordPress.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "templates, custom header" }
javaScript in <head> section of WP API How do I place the following javaScript in the `<head>` section of the Wordpress _Widgets_ API menu screen? <script type="text/javascript"> jQuery(window).load(function() { jQuery("#logocheckbox").change(function() { jQuery("#logocheckboxdiv").fadeToggle("slow"); }); }); </script>
function load_custom_logo_js($hook) { if( 'widgets.php' != $hook ) return; echo (' <script type="text/javascript"> jQuery(window).load(function() { jQuery("#logocheckbox").change(function() { jQuery("#logocheckboxdiv").fadeToggle("slow"); }); }); </script> '); } add_action( 'admin_enqueue_scripts', 'load_custom_logo_js' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "php, functions, widgets, javascript" }
Is there an action for save_menu and/or update_menu? I want to "save" my menus into transients. I want to update those when there's been any changes to the menus via the admin custom menus. I've looked for an action but can't see to find anything. Perhaps I missed the obvious?
: do_action( 'wp_update_nav_menu', $menu_id, $menu_data ); Consequently, a nav menu is a custom post type, as are its menu items, so all of the usual hooks for publish/save/update/trash apply
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "theme development, menus, theme options, actions" }
Pass custom css class to add_menu_page My theme currently uses add_menu_page() in order to display the theme options sections on the left hand admin menu. I would like to be able to attach a parent css class to the main menu item in order to selectively show/hide the menus for advanced users. I don't see this documented in the codex so I'm asking here to find out if there is a workaround or undocumented feature that I can utilize. Any help, much appreciated. The basic idea is that I have one main menu item and about 8 submenu items. Currently, all the menu items are displayed in the menu. I would like to use custom css to toggle the visibility of the submenu items, however, there is currently no custom id or class that I can use to target my menus.
You should **not** do this via CSS as the underlying functionality would still be there (and thus open for direct access). I'd rather rewrite the theme in a way that the menu pages are only added if the current user has a certain capability. if (current_user_can( SOME_CAP )) { add menu pages ... } You could even provide a new capability for your theme. Have a look over here, if you're interested in this.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, add menu page" }
How to hide W3 Total Cache from non admins? I would like to be able to hide W3 Total Cache from non admins. How can I go about doing so? The following code I tried implementing in my functions.php file does not work: function hide_w3tc() { if (!current_user_can('super_admin')) { remove_submenu_page('admin.php?page=w3tc_dashboard'); } } add_action( 'admin_menu', 'hide_w3tc');
You can try to use `remove_menu_page()`, so you code example would be like: function hide_w3tc() { if (!current_user_can('manage_network')) { remove_menu_page('w3tc_dashboard'); } } add_action( 'admin_menu', 'hide_w3tc',11); where we use a priority greater than the default of `10`, since the _W3TC_ menu page is added via add_menu_page('Performance', 'Performance', 'manage_options', 'w3tc_dashboard', '', 'div');
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugin w3 total cache" }
Get all media files for current author I'm trying to create a list on the frontend of my site of all media items that the current user has uploaded. It seems like the way to do this would be to loop through and compare the ID of the current author with the ID of the author of the media item and then only display the items when a match is found. But, I can't figure out how to get the author of the media item. Is there a function for this? Does someone have a better (easier) way to do this?
Media are just posts - so just query posts. This is untested: $args = array( 'author' => $author_id, 'post_type' => 'attachment', ); $query = new WP_Query( $args ); I'm not sure if you want currently logged in user or the author of the post currently in the loop - either way you can set $author_id above appropriately.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "author, media, front end" }
woocommerce product categories in menu I am using woocommerce plugin, and added some product categories in appearance->menu. I mentioned that if I logging off, the product categories is not showing at all... please help. sorry for bad english.
I found the answer. The main problem is: First of all woocommerce plugin has own ID system. And wordpress has own ID system. And it happened that with the same ID was two different items. For example: Woocommerce category name "my category" has ID: 13 And Wordpress page "Logout" has ID: 13 So, in woocommerce where is function called "woocommerce_nav_menu_items" is checking pages like "Logout", "Change password", "View order", "Edit address" to avoid show if user is not logged in. And this function is checking if you are not logged in, unset all these pages which would be in menu. And it's happened what my created category in woocommerce was with the same ID like created page "Logout". **My suggestion:** If this will happen to you just delete created category and create a new one, because the system will assign another ID to your category. I hope this will help for many people.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugins" }
Archive for custom fields? Recently I've done a nice taxonomy system on my WordPress website. Created also the taxonomy archive template files, so wherever I'm listing the taxonomies I can click on them and will bring me on a results page filtered by the clicked taxonomy. I'm wondering if the same situation can be reproduced also with custom fields? I know custom fields are different by hierarchical tackle, but just wondering.
WordPress does not support by default `custom_field`s archive like for taxonomies ( _yeah, taxonomies can have categories_ ) but we can create a destination page with page template ( _linked from the listed`custom_field`_) and added a searching on the `custom_field`, like this ( _from the **listing page_** ): <?php if (get_post_meta($post->ID,'_my_meta',TRUE)) : $key_meta = get_post_meta($post->ID,'_my_meta',TRUE); endif; ?> <a href="<?php bloginfo('url'); ?>/?s=<?php echo $key_meta[meta_field]; ?>"><?php echo $key_meta[meta_field]; ?></a> The destination page's layout we can customize by preferences.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, archives, template hierarchy" }
Show specific content on parent custom post type and all children I have 5 main posts within a custom post type. Some of these posts will have children. I have content that should only be displayed on the parent post and all children of that post. What's the best way to achieve this?
You could setup a condition based on post ID: <?php if (is_page(12) || $post->post_parent=="12") { ?> <ul> Your Menu </ul> <?php } else { ?> <ul> Another Menu (or put nothing here) </ul> <?php } ?> If you don't know how to locate the post ID: "Roll over any page, post or category with your cursor (while logged in and in the "manage" area of course), and the page, post or cat_id number appears in the progress bar in the bottom of the browser." - <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, conditional tags" }
output only if within a combination of two cats What Im looking to do is look if on one page out put posts that have 2 cats selected (they must have both selected to be shown, not just one cat) if (is_page(15) || $post->post_parent=="15") { $option1 = '11, 4'; $option2 = '11, 7';} <?php $my_query_args = array( 'posts_per_page' => 10, 'meta_key' => 'price', 'meta_value_num' => '', 'orderby' => 'meta_value_num', 'order' => 'asc', 'tax_query' => array( array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => array( $inventory_home ), 'operator' => 'AND' ) ) ); $my_query = new WP_Query( $my_query_args );?>
Your query has some odd elements like `'meta_value_num' => '',` but it sounds to me like what you want is exactly what `category__and` does. $my_query_args = array( 'posts_per_page' => 10, 'meta_key' => 'price', 'category__and' => array($catid1,$catid2), 'orderby' => 'meta_value_num', 'order' => 'asc' ); Side note: your `price` meta key will not order in a way that you think is correct unless the associated values actually are numbers.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
Display one category and its suncategories I am using this code to filter posts. How can I modify to display only one category and its subcategories. Not all categories. <form action="<?php bloginfo('url'); ?>/" method="get"> <?php $select = wp_dropdown_categories('show_option_none=Select category&show_count=1&orderby=name&echo=0'); $select = preg_replace("#<select([^>]*)>#", "<select$1 onchange='return this.form.submit()'>", $select); echo $select; ?> <noscript><div><input type="submit" value="View" /></div></noscript> </form>
Instead of: $select = wp_dropdown_categories('show_option_none=Select category&show_count=1&orderby=name&echo=0'); put this: $select = wp_dropdown_categories('show_option_none=Select category&show_count=1&orderby=name&echo=0&child_of=' . $ID_OF_PARENT_CATEGORY); where $ID_OF_PARENT_CATEGORY is a variable holding the ID of parent category, from which you want to show the children. # Showing parent That category WON'T show. To show it, you must do some greater hack (here I'll show you only thing that I can think right now), since there are no argument like `include`, so that you can just include it. You can show categories that are PARENT and it's siblings, so, you will show children of PARENT's parent. That means that you will put in args 'show_option_none=Select category&show_count=1&orderby=name&echo=0&child_of='.$ID_OF_GRANDPARENT.'&exclude='.implode(',', ARRAY_OF_PARENTS_SIBLINGS) Reference
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories" }
Fatal error: Call to undefined function wp_get_current_user() I have some strange error or may be I do not have the skills to tackle this issue. I am building a plugin for Multisite. When is use `is_admin()`, my plugin works fine but when I use `is_super_admin` it shows me this error `Fatal error: Call to undefined function wp_get_current_user()`. I did my search but could not be able to find any solution. My Code is this if(!is_super_admin()){ add_action('widgets_init','my_unregister_widdget'); function my_unregister_widgets() { unregister_widget( 'WP_Widget_Pages' ); unregister_widget( 'WP_Widget_Calendar' ); } } I saw this question but it's not helping me.
`wp_get_current_user()` is a pluggable function and not yet available when your plugin is _included_. You have to wait for the action `plugins_loaded`: Example: add_action( 'plugins_loaded', 'wpse_92517_init' ); function wpse_92517_init() { if(!is_super_admin()) add_action('widgets_init','my_unregister_widget'); } function my_unregister_widgets() { unregister_widget( 'WP_Widget_Pages' ); unregister_widget( 'WP_Widget_Calendar' ); } Or move the check into the widget function: add_action( 'widgets_init', 'my_unregister_widget' ); function my_unregister_widgets() { if ( is_super_admin() ) return; // not super admin unregister_widget( 'WP_Widget_Pages' ); unregister_widget( 'WP_Widget_Calendar' ); }
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "plugins, multisite" }
Wordpress pagination on custom script I am using WP for my RealEstate project where all properties are pulled from a custom table (wp_listing) and displayed in a custom page template (page-realestate.php). I know WordPress has built-in pagination methods to deal with paged content (pages, posts lists). I want to use that same pagination methods for the list of properties I am fetching from my custom DB table. Is this possible? How? [EDIT] Code is something like: echo '<ul>'; $properties = $listing->getProperties(); for($i = 0; $i < count($properties) ; $i++) { echo '<li>' . $properties[$i]['address'] . '</li>'; } echo '</ul>';
It is unclear exactly which "built-in pagination methods" you are looking for. WordPress uses several. If you are looking for the `next_posts_links` and `previous_posts_link` functionality, write your own function as those built-in functions depend upon the `$wp_query` global as you can see in the source. I doubt it is worth the time and effort to try to hack that to work with data from your custom table. If you want pagination as you see at the bottom of the admin edit post screen, the built-in function `paginate_links` is generic. So long as you pass in the proper values you can paginate your own data without a problem. I have done it, and it works well, but you have to be very careful with all the parameters. Based on the information in your question, I don't think I can write the code you need. Plus, I am not even sure if that is what you are looking for.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pagination" }
How to allow wordpress to create username with symbols like + I want to allow users to create username with **+** symbol. but wordpess removing the symbol by the register validation process. If I gave username as **abcd+123** , the user registered with username as **abcd123**. I need the username registered as it is with **+** symbol. Answers are greatly appreciated.
We need to add a filter to 'sanitize_user'. Here is the sample code that will work for you. add_filter( 'sanitize_user', 'tubs_sanitize_user', 10, 3); function tubs_sanitize_user($username, $raw_username, $strict) { $new_username = strip_tags($raw_username); // Kill octets $new_username = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '', $new_username); $new_username = preg_replace('/&.?;/', '', $new_username); // Kill entities // If strict, reduce to ASCII for max portability. if ( $strict ) $new_username = preg_replace('|[^a-z0-9 _.\-@+]|i', '', $new_username); return $new_username; } Note: This code is the modified version of the original WordPress sanitize_user function.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "user registration, username" }
Create custom field key upon theme activation Upon theme activation I want to create an 'URL' key for the custom fields. Like in !this screenshot. I know who to run functions when a theme is activated, I don't know how to create this custom field key though. Any thoughts? I don't want to be using custom meta boxes.
Those values are populated from the unique keys in the `*_postmeta` table, excluding keys that begin with an underscore (`_`). If you want to pre-populate that key the add a value to the table under post ID `0`. There is no way to pre-populate those that I am aware of besides to add a dummy meta_key/value to the `*_postmeta` table. `add_post_meta('0','URL','');` does not work, at least not when I try, so you need to write the SQL. $wpdb->query("INSERT INTO {$wpdb->postmeta} (post_id,meta_key) values (0,'URL')"); That will create numerous entries in the database, however, unless you take further steps to avoid it. **I strongly advise against this hack.** Using a custom meta box is by far the cleaner solution, and I cannot guarantee that there are no negative consequences to adding a dummy key/value to `*_postmeta`. I highly recommend that you reconsider the custom meta box option.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom field, metabox" }
Show all terms in a custom taxonomy with all child terms wrapped in a ul Is there a way that I can list all the terms within a custom taxonomy in an unordered list and wrap all child terms in another unordered list? For example; <ul class="menu"> <li><a href="#">Parent 1</a></li> <li> <a href="#">Parent 2</a> <ul class="sub-menu"> <li><a href="#">Child of Parent 2</a></li> <li><a href="#">Child of Parent 2</a></li> <li><a href="#">Child of Parent 2</a></li> </ul> </li> <li><a href="#">Parent 3</a></li> </ul>
You can take a look at the Wordpress function `wp_list_categories()`. If you want to display all the terms within a given custom taxonomy you can for example use: <?php $args = array( 'taxonomy' => 'my_custom_taxonomy_slug', 'orderby' => 'name', 'hide_empty' => 0, 'title_li' => '', 'hierarchical' => 1, 'walker' => null, ); ?> <ul class="menu"> <?php wp_list_categories( $args ); ?> </ul> If you need to adjust the html structure, you can use a _custom walker_ that extends either `Walker_Category` or `Walker`. You can read more about it here in the Codex: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom taxonomy, terms" }
How to make all the posts commentable by default? Imputs in Settings/Discussions are not saved I've modified my website quite a bit and now looks almost as I desire. I've set all the posts to be commentable in Settings/Discussions but it seems that this imput is not saved and new posts by authors are not commentable. Everytime, I need to "quick edit" the new post and mark the |_|Allow Comments field as selected |x|. This takes me a lot of time and I wonder if there's a way to have a function to make all the new posts as commentable as, just like I said, it seems not possible to choose it as option in Settings/Discussions. Thanks!
A common method to keep all the posts open for comments, is to add this line into the file `functions.php` in the current theme directory : add_filter('comments_open', '__return_true'); where `__return_true` is just a core function that always returns `true`. ps: since this seems to be helpful, regarding to the problem described by @user27309, it's better to have the comment solution, added as an answer ;-)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "comments, quick edit" }
Custom query shows custom post types in trash I have a custom wordpress query like so: $query = new WP_Query(array( 'post_status' => 'future || publish', 'post_type' => 'kalender', 'order' => 'ASC' )); But the problem is that the items shown on the pages also include the items that are in the trash? I don't understand why because according to the `post_status` only published & future posts should be shown? The item in the trash is a post in the future though? Maybe that's why it's shown but how can I exclude that one?
The syntax in the query above is wrong, it should be: $query = new WP_Query(array( 'post_status' => array( 'publish', 'future' ), 'post_type' => 'kalender', 'order' => 'ASC' )); That seems to solve the problem. :)
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "custom post types, wp query, query posts" }
Insert Captcha Code info Any Form (Created of Plugin) I am looking for best option on Captcha. Plugin's don't seem to be the answer because this is a custom form for the theme I am using. Unfortunately, they don't offer any spam protection. The form is heavily styled so I do not want to start from scratch. I do have access to the contact form code and can plug one right in. I can't imagine I am the only one with this issue. Doing a Google search hasn't been very insightful as well. Is my best option to find a plugin or add custom code? if so - can I do some kind of Javascript only protection? I'd rather not integrate it with PHP unless I have to...
I'd say this question is _mostly_ off-topic since it's not WordPress-specific. Mostly, because the majority of PHP solutions out there use sessions, which will not work out-of-the-box in WordPress. Google search actually handles this question quite well. Have a look at this discussion for nice techniques. Finally, Contact Form 7 has Captcha built-in.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "plugin contact form 7, captcha" }
How to Access Script Tags in Header IN my Wordpress blog, I am looking to update a link in header that I believe is outdated: `<script type='text/javascript' src=' How do I get to this link? What file is it in? In my header.php file, I see `wp_head()` \-- I track that down and it doesn't lead me to anything that I can understand....
If done right there should be a callback hooked to `wp_enqueue_scripts` which has either `wp_enqueue_script` or both `wp_register_script` and `wp_enqueue_script` in it. Something like the following from the Codex: function themeslug_enqueue_script() { wp_enqueue_script( 'my-js', 'filename.js', false ); } add_action( 'wp_enqueue_scripts', 'themeslug_enqueue_script' ); You will need to find that callback function in your theme or in one of your plugins. You should be able to narrow things down by disabling plugins one by one, and by switching themes to a default theme like Twenty Twelve. Once you find it it should be obvious how to change the path. If not done right, I have no way to guess what was done or how to alter it.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "headers, scripts" }
Is there anyway to get the inputted password string from the login form? Is there anyway to get the password string from the login form?
this should do the job, just add it to `functions.php` or put in a plugin: add_filter( 'wp_authenticate_user', 'my_authenticate_user', 10, 2 ); function my_authenticate_user( $user, $password ) { // do whatever you want with the $password variable here return $user; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "login, password, wp login form" }
Remove post_tag from default post type, add custom taxonomy I've been searching for a while for an answer to this, but the results I find always deal with custom post types as opposed to the built-in 'post' post type. I want to remove the default 'Post Tags' taxonomy from the built-in 'post' post type and then add my own custom taxonomy to replace it. Essentially, I have other custom post types using my custom taxonomy and I'd like to align the 'post' post type with them. I can't for the life of me figure out how to edit the default post type though, any ideas how I would do this? Thanks in advance.
to completely remove post tags: < if you want to remove post tags from posts, but keep on other custom post types: add_action( 'init', 'my_register_post_tags' ); function my_register_post_tags() { register_taxonomy( 'post_tag', array( 'my_post_type_here' ) ); } to add your own custom taxonomy to posts, use register_taxonomy, setting the `$object_type` parameter to `post`.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "posts, tags" }
Which file renders the "Edit Gallery" Settings page? I was looking for a tutorial on adding options to the "Edit Gallery" page. In the hopes of adding some GUI inputs that would result in the generated [gallery] short-code having custom attributes. I found this question. I was hoping that taking a look at how the page and options are rendered, and were the request "insert gallery" is sent would help me understand the issue. So again the questions are : 1) Where in the WordPress core can I see how the "Edit Gallery" page and its settings are rendered? 2) What file / function handles the "insert gallery" request ? I created a separate questions so someone could get some easy points : ) Thank you.
Browsing through the code at < it appears that the file you're looking for is `/wp-includes/media.php`. I wouldn't recommend editing core files, though; any updates you make would be clobbered in the next upgrade.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "shortcode, gallery, core" }
Gravity forms and wp_update_post I am using Gravity Forms to let users create posts. The user fills out a bunch of information, and a post is created. The user gets to choose which categories the post is in, but there is one more category that I need to add for every post. I am trying to use the gform_after_submission hook (< and wp_update_post. I just want to add one more category to the post. Here is my code: add_action("gform_after_submission_5", "add_category", 10, 2); function add_category($entry) { $post = get_post($entry["post_id"]); $post->post_category = array ( 48 ); wp_update_post($post); } This does add the appropriate category, so that's good, but it also removes ALL of the other post data, which is bad. What am I doing wrong? Can this code be made to work, or should I be taking another approach?
Looking at core, it seems post_category always overwrites: // Passed post category list overwrites existing category list if not empty. Instead, try something like: //wp_set_post_terms( $post_id, $terms, $taxonomy, $append ) wp_set_post_terms( $entry["post_id"], 48, $taxonomy, true ) Obviously, replace $taxonomy with the correct name.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin gravity forms, wp update post" }
get_post_meta property of non object I am getting a custom field outside the loop in header.php. I get the custom field just fine but I found that when the custom field is empty, I get an error message Trying to get property of non-object Here is my code <?php $description = get_post_meta( $post->ID, 'page-description', true ); ?> <div id="page-title"> <?php if( !empty($description)) { ?> <p><?php echo $description; ?></p> <?php } ?> I did some searching on this site and one post said to globalize the $post variable. I tried that but didn't work. I can't figure out what is wrong with it.
Try this: <?php $description = get_post_meta( $post->ID, 'page-description', true ); ?> <div id="page-title"> <?php if( $description !='' ) { ?> <p><?php echo $description; ?></p> <?php } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, custom field" }
Does the textdomain have to be the theme's name? Does a theme's text domain have to be the actual theme name? If you develop WP themes, couldn't you just use the same name (perhaps your business name) for all the theme's you develop, making it easier to copy and paste code as you develop? (even though a find and replace is rather simple).
The text domain is a unique identifier, which makes sure WordPress can distinguish between all loaded translations so Using the basename of your plugin/theme is always a good choice because plugin/theme basename is always unique though it is not mandatory to have plugin/theme basename as text domain, you can use any unique identifier. If you're translating a plugin or a theme, you'll need to use a text domain to denote all text belonging to that plugin/theme. This increases portability and plays better with already-existing WordPress tools. In general, an application may use more than one large logical translatable module and a different MO file accordingly. A domain is a handle of each module, which has a different MO file so you should not use same text domain for different theme/plugin instead it should be unique for every plugin/theme. You can get more information from this page.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "theme development, translation, localization, textdomain" }
Are you sure popup on Contact Form 7 I have a contact form built with Contact Form 7. What I want to do is when the user hits the submit button to throw up a pop up window with a notice asking if their sure they want to submit the form with an ok or cancel button. I've found the hook 'wpcf7_before_send_mail'. I was hoping there might be something i could do in the additional settings. Something like wpcf7_before_send_mail: "javascript here" But when I have tried to just get an action to work like this say: before_send_mail: "window.alert("hello");" It just submits the form without doing anything. How would I get a popup to appear with an ok and cancel button, ok submitting form and cancel breaking the action?
The `wpcf7_before_send_mail` is a hook that is triggered after form submission, so it isn't what you're looking for. You should make a javascript script that triggers when the user hits the submit button on your page. It's implementation could be a simple using javascript `confirm()` \- example \- or using a modal box to ask the user to confirm his choice.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery, javascript, plugin contact form 7" }
Loading Canvas & WooCommerce translation file in child theme I'm trying to localise a site (Canvas child theme). I already have the translated .po and .mo files. I uploaded the WooCommerce translation files to `child-theme/woocommerce/i18n/languages/` in the child theme and the Canvas translation file to `child-theme/lang/`. This follows the same directory structure as the parent theme and plugin. I have also defined WPLANG as 'af_AF' In my functions.php I have the following function function weg_localisation() { load_theme_textdomain('woothemes', get_stylesheet_directory() . '/lang'); unload_textdomain('woocommerce'); load_textdomain('woocommerce', get_stylesheet_directory() . '/woocommerce/i18n/languages.woocommerce-af_AF.mo'); } add_action('init', 'weg_localisation'); Unfortunately I'm having no success with this. Any idea where I'm going wrong? Thanks,
There was a syntax error in loading the WooCommerce translations and I managed to get the parent theme translations working by following the same method I used for the WooCommerce translations. function weg_localisation() { unload_textdomain( 'woothemes' ); load_textdomain('woothemes', get_stylesheet_directory() . '/lang/af_AF.mo'); unload_textdomain('woocommerce'); load_textdomain('woocommerce', get_stylesheet_directory() . '/woocommerce/i18n/languages/woocommerce-af_AF.mo'); } add_action('init', 'weg_localisation');
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, child theme, localization" }
I want my post to republish again after adding a custom field I wanted a code in Wordpress that could allow me to republish the post every time I add a new custom field. For example, if I already have a post and wanted to add an update to it; I want it to appear at the top of the site after updating it. Is that possible ? Thanks in advance
It can be achieved by scheduling the post time to current time + a few seconds for example. Each time you add a custom field, just before saving - change the publish time to the current time and then save.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, loop, metabox, publish" }
Wordpress Media Uploader custom Javascript not working I encountered a strange problem with my JavaScript (jQuery) when trying to modify the behavior of my Media Uploader in Wordpress 3.5 !Image filter selector This was my JQuery: $('.attachment-filters').change(function(){ if($(this).val() === 'uploaded'){ alert("Uploaded images selected"); } else { alert("Other option selected"); } }); And this was the part of the media uploader i wanted to react to: <select class="attachment-filters"> <option value="all" selected="selected">All media items</option> <option value="uploaded">Uploaded to this page</option> <option value="image">Images</option> <option value="audio">Audio</option> <option value="video">Video</option> </select> To my big frustration this worked perfectly in a JS fidle, however it failed miserably in my wordpress admin screen...
The solution was to simply wrap my JQuery in a function like this: $('#wpcontent').ajaxStop(function() { $('.attachment-filters').change(function(){ if($(this).val() === 'uploaded'){ alert("Uploaded images selected"); } else { alert("Other option selected"); } }); });
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom field, admin, uploads, media" }
Using get_option() in JavaScript Previously, I used the `get_option()` function to get an option in PHP, like this: $width = get_option('my_width'); This is inside a shortcode function. Now, I want to have an option in JavaScript. Is that possible? The JS is added with `wp_enqueue_script`, from a shortcode function.
Define an array of parameters to be injected into the script: $script_params = array( 'myWidth' => get_option('my_width') ); Localize the script via `wp_localize_script`: wp_localize_script( 'your-script-handle', 'scriptParams', $script_params ); `scriptParams` now is a js object you can access from within the script: alert( scriptParams.myWidth ); // the value from the PHP get_option call in the js
stackexchange-wordpress
{ "answer_score": 13, "question_score": 9, "tags": "shortcode, javascript, wp enqueue script, options" }
How long does plugin review usually take? WordPress says that plugins are manually reviewed within a "vaguely defined amount of time". What's the experience? How long does this take, on average?
This appears to be a few days to a week, as said in the comments. I can say I've experienced the same amount of time a few times now. However, this is no _rule_.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "validation, review" }
What is the simplest way to create a redirect If I have a custom post type called Drink which has permalinks like `/drink/pepsi/` then `/drink/` will list all of the Drinks. How can I rewrite `/drink/` to `/drinks/`? I want permalinks for single Drinks `/drink/pepsi` to stay with the `/drink/` root but I think `/drinks/` makes better sense for the "archive" of Drink.
When you register your custom post type, set the `has_archive` argument to the slug you want for the archive page, in this case `drinks`: $args = array( 'rewrite' => array( 'slug' => 'drink' ), 'has_archive' => 'drinks', );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks" }
how to create a post type like comments I want to create a post type but don't allow to create new item on the back-end, the item of this post type can be only created on the front-end by the user. How can I do this? Thank you
You can set `show_ui` to `false` in register_post_type arguments You can create a "post" in the front-end using wp_insert_post
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
Function Reference for custom link in Admin Menu Management Page What is the function reference for the text within the URL field in the Admin Menu page? I have a PHP function that is utilizing `the_content` function reference to look for specific file paths and replace said file path with a custom path. My goal is to apply this function that is successfully changing paths within my pages/posts to changing the same type of paths when I'm adding custom links in the Admin Menu Management page. Currently this function that uses `add_filter` and `the_content` function reference is not working for the Admin Menu Management Page. I create custom menu sets and place them in sidebar's using widgets for easily management "quick links" to other pages and documents. I've been using the following codex page to find function references: Function_Reference.
There doesn't seem to be a single filter _just_ for a menu item URL, but in `wp-includes/nav-menu-template.php` there are a few filters: * `wp_nav_menu_objects` \- the menu items before being formatted with HTML * `wp_nav_menu_items` \- a HTML list of the navigation menu items * `wp_nav_menu` \- the completed menu just before output
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, menus, filters, admin menu" }
Using _s theme, menu changes do not affect header menu I'm using the _s theme and seeing the header menu point to 'Home' and 'Sample page'. in `functions.php`, we have register_nav_menus( array( 'primary' => __( 'Primary Menu', 'mytheme' ), 'secondary' => __( 'Secondary Menu', 'mytheme' ), ) ); Then in `header.php`, we use <?php wp_nav_menu( array( 'theme_location' => 'Primary Menu' ) ); ?> <?php wp_nav_menu( array( 'theme_location' => 'Secondary Menu' ) ); ?> etc. Finally, we have created both menus in the Wordpress custom menu section and added some custom items, but they are not reflected in the site. How do we match them up?
You should be calling the menus by name, not description: <?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?> <?php wp_nav_menu( array( 'theme_location' => 'secondary' ) ); ?>
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "menus, navigation, customization" }
adding a text message beside the comment submit button What is the cleanest way to display a text message beside the submit button like this in screen shot: !example of what I am talking about I am currently doing it by editing the file `wp-includes/comment-template` line `1577` (wordpress 3.5) before: <input name="submit" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" /> after: <input name="submit" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" /> (your message will only be visible after moderation) I understand this is not the optimal way to do it, but what is the way to do it. I prefer as a plugin, but editing a theme would be fine.
You should **not** edit the Wordpress core files! If you have `comment_id_fields()` in your comments template, like this: <p class="form-submit"> <input name="submit" type="submit" id="<?php echo esc_attr( $args['id_submit'] ); ?>" value="<?php echo esc_attr( $args['label_submit'] ); ?>" /> <?php comment_id_fields( $post_id ); ?> </p> you might use: add_filter("comment_id_fields","my_submit_comment_message"); function my_submit_comment_message($result){ return $result." <span>(your message will only be visible after moderation)</span>"; } and place it in `functions.php` in your current theme directory.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "plugins, themes, comments, comment form, comments template" }
Under theme folder, what's sequence of action for index.php, page.php, single.php? `index.php`, `page.php`, and `single.php`: All three files are under the theme folder and use the Loop to check for posts. Which one gets executed first, and the next? What's sequence for WordPress to read those files?
In general, the most specific template will be used first if it's available, then WordPress will try the others. It depends on what thing you're looking at (post, page, taxonomy, etc) and where your're looking at it (archive, single). This is all explained in detail by the Template Hierarchy.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme development, templates" }
How to do a task only once for logged in users I want to do a task only once after an user has visited my site. I am currently doing like this: function my_task(){ //do my tasks } add_action('init', 'my_task'); I am doing this from a plugin. This actually loads **my_task()** function every time users load any page of wordpress. But I only want to load it once for each user for each session. Once they close the browser, and come back again, I want it to load again only for once till they exit. How can I do this? Thanks in advance.
There are various ways to do this, but I've recently addressed a similar problem by using cookies. add_action( 'init', 'wpse_93797_cookie' ); function wpse_93797_cookie() { if ( !isset ( $_COOKIE['wpse_93797_cookie_name'] ) ) { // Do your stuff. // Set your cookie so we don't do stuff the next time around. // Note that 0 makes the cookie expire at the end of the user's browser session. setcookie( 'wpse_93797_cookie_name', 'some-value-we-did-stuff-btw', 0, '/' ); } } Manual for cookies on PHP.net Also maybe helpful: How can i set , get and destroy cookies in wordpress?
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "users, actions, init" }
Using Schema with `the_excerpt` I'm currently developing a WordPress site and want to use Schema, I have been some what successful so far but have now hit a stone wall. I want to use: `itemprop="description"` to the `<p>`the_exerpt`</p>`. Since I was able to the itemprop easily to `the_post_thumbnail` using: `<?php the_post_thumbnail('post-thumbnail',array('itemprop'=>'image')); ?>` I assumed this would be a easy task, but turns out its slightly more complex for the exerpt tag. I have tried the following with no success: 1. `<?php the_excerpt('excerpt',array('itemprop'=>'description')); ?>` 2. `<?php the_excerpt('the_excerpt',array('itemprop'=>'description')); ?>` Currently my excerpt in `functions.php` looks like: function new_excerpt_more($more) { global $post; return '...<a class="small button secondary" href="'. get_permalink($post->ID) . '" itemprop="url">Continue Reading</a>'; } add_filter('excerpt_more', 'new_excerpt_more');
Not the best solution but this works fine: <?php remove_filter('the_excerpt', 'wpautop'); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "functions, excerpt, html5, html" }
Limit popular posts by days I am using this get_posts array to retrieve top 15 popular posts by comments. The problem is that it shows those all those highly commented posts from the day posts were added into blog. So, the list sometimes changes but most of the time remains same. How can I limit/show posts of the last 7 days? This would show most commented posts of the last week. Thanks Here is my code: global $post; $args = array( 'orderby' => 'comment_count', 'order' => 'DESC' , 'numberposts' => 15); $popular_posts = get_posts( $args ); foreach( $popular_posts as $post ) : if (has_post_thumbnail()) { ?> <li> <div class="widgetimg"> <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('widgetimg-thumb'); ?></a> </div> </li> <?php } endforeach; ?>
Here is a function which show the posts of last 7days or you can change it according to your requirement. function filter_where($where = '') { //posts in the last 7 days $where .= " AND post_date > '" . date('Y-m-d', strtotime('-7 days')) . "'"; return $where; } add_filter('posts_where', 'filter_where');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "posts, get posts" }
Really simple query giving error in SQL syntax I'm sure this is a simple oversight but I cannot seem to narrow it down: global $wpdb; $tablename = $wpdb->prefix . "icrm_folders"; $sql = $wpdb->prepare( "SELECT * FROM %s", $tablename ); //$sql results in SELECT * FROM 'wp_icrm_folders' $result = $wpdb->get_results( $sql ); This seems to result in nothing! My debugger shows an error on $wpdb object under last_error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''wp_icrm_folders'' at line 1 Now I ran the query `SELECT * FROM 'wp_icrm_folders'` directly in phpmyadmin and that gives me an error because wp_icrm_folders is inside `'` the query executes fine if I remove the apostrophes or replace them with the grave accent/character. PHP Version 5.3.3-7 MySQL Version 5.1.63 WordPress 3.5.1
Don't use `$wpdb->prepare` with table names. `prepare` will quote your table names that will result in incorrect SQL. It is unnecessary overhead as well. Your table name should never, and in your case isn't, be user-supplied data. You have no need to escape it. 'prepare' is for use on user-supplied data, such as data from a form or a `$_GET` parameter. You have no user-supplied data so all you need is $wpdb->get_results("SELECT * FROM {$tablename}");
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "plugin development, wpdb, sql" }
Theme Translation? I've download a theme called Contango from Wordpress Themes Repository. The theme have a folder called "languagues" and have a file called "contango.po". I could open that file and do translation, but nothing changed. * How could I translate this theme into my own language? Thanks so much and apologize for my newbie question?
Translation files must be named {locale}.po (e.g. `en_US.po` in order to be recognized. Rename your language translation file accordingly. See more in the Codex: i18n for developers.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes, translation" }
How to use get_post_custom function on the blog page? First, I have a static page for homepage and for blog page too. I created a custom box for pages to setup unique background image for the pages. My idea is working on all page templates, but on blog page something wrong. **header.php is same on all page** <head> {...} <?php $values = get_post_custom( $post->ID ); ?> <style type="text/css"> body { background-image:url("<?php echo $values['background_image_meta'][0]; ?>"); } </style> {...} </head>
The basic problem is that there is no variable `$post` in your `header.php`. That variable might exist in the **global** scope, but your code operates in a function scope of `load_template()` which was called by `get_header()`. So you have four options: 1. Import the global variable into your function with the `global` keyword. global $post; // make sure everything is set up as a post object $post = get_post( $post ); $values = get_post_custom( $post->ID ); 2. Use `get_queried_object_id()` to get the ID, similar to hepii110’s suggestion. $values = get_post_custom( get_queried_object_id() ); 3. Use `get_the_ID()`. This does almost the same as version 1. $values = get_post_custom( get_the_ID() ); 4. Call `get_post_custom()` without the post ID. It will try to find the correct ID automagically. $values = get_post_custom();
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "metabox" }
Running Wordpress from MySQL Cluster with HAPRoxy I'm trying to install a wordpress installation where the DB will sit on a MySQL cluster (Galera/Percona XtraDB Cluster) and connected through HAProxy. Everything outside of the Wordpress install seems to work fine. Using the mysql client to connect to the database with a username and password works just fine. The Wordpress install is on the same server as the HAProxy. That works fine from command line when I do this: mysql -u wordpress -p<password> -h <haproxy ip> -D wordpress However, from the install GUI page, it constantly takes me to the "DB connection failed" page. Can anyone shed some light on where the issue might be? Here is what I'm attempting to use in the install from: database name: wordpress username: wordpress password: <password> database host: <ip of haproxy server> table prefix: wp_ Thanks for any suggestions!
SELinux was contributing to the problem. The main issue was that an HTML page was attempting to talk to another port on the localhost. I would not have seen the problem if the HAProxy was running on a separate host. The log was revealed in /var/log/messages, where I should have checked but did not considering I didn't expect it. Fail on my part. The log looked like this: `setroubleshoot: SELinux is preventing the http daemon from connecting to network port 3306 For complete SELinux messages.` SELinux should not have been running to begin with, so I simply disabled it: `echo 0 > /selinux/enforce` To maintain this state upon reboot, simply edit the SELINUX line in /etc/sysconfig/selinux to say `SELINUX=permissive` rather than `SELINUX=enforced`. This will log alerts but not stop any processes. To disable SELinux completely, just replaced it with `SELINUX=disabled` instead.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "mysql, installation" }
How to delete old posts' edits to save space? I need to delete old edits and autosave, they have grown overtime, and are not needed anymore, seeing this post: < it states: > If you have no use for the post revisions and autosaves then disable them in wp-config and WordPress will clean them up on its own but I can't find exactly where to edit. using wordpress 3.5
You'll need to edit `wp-config.php`. To set posts to retain a set number of revisions: define('WP_POST_REVISIONS', 3); To disable post revisions completely: define('WP_POST_REVISIONS', false );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "posts, customization" }
Using Nonces for AJAX that only retrieves data Does it make sense to use a nonce on an AJAX action that only returns data and doesn't alter data on the server side? I understand they are important if you are saving data or changing something on the server but if you are just receiving data like a post or metadata, is a nonce really needed?
No, it is not needed. If you want to show the data to some users only, you can use `current_user_can( 'some_capability' )` to restrict the access.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 4, "tags": "ajax, nonce" }
rewrite_rule() not preserving the query string We have added a custom rewrite_rule to our site to allow for a pretty inbound link to be parsed and handled properly. Links are constructed as `domain.com/meetings/faculty/someIDnumber` add_action( "init", "pleasing_permalinks" ); function pleasing_permalinks() { add_rewrite_tag( '%hash%', '([^&]+)' ); add_rewrite_rule( 'meetings/faculty/([^/]+)/?$', 'index.php?p=1598&hash=$matches[1]', 'top' ); //flush_rewrite_rules(); } Rewrite Analyzer approves of the above but when we test with actual links in the browser, the embedded ID number is not preserved. What are we missing here?
If `faculty` is a child page of `meetings`, the rule should be: add_rewrite_rule( 'meetings/faculty/([^/]+)/?$', 'index.php?pagename=meetings/faculty&hash=$matches[1]', 'top' ); `pagename=meetings/faculty` instead of `p=1598` EDIT- or alternately: add_rewrite_rule( 'meetings/faculty/([^/]+)/?$', 'index.php?page_id=1598&hash=$matches[1]', 'top' ); `page_id=1598` instead of `p=1598`
stackexchange-wordpress
{ "answer_score": 7, "question_score": 3, "tags": "url rewriting, rewrite rules" }
How to shorten length of auto generated password sent during registration? is there a way to shorten the length of the 'auto generated password' which is sent during registration of a new user? I would like to shorten this password to 5 characters max and also remove the numbers '0' and '1' as they can be confused for letters 'O' and 'L'. My users are not very tech savvy and most don't know how to copy and paste a password. They type each character instead which can be time consuming and frustrating at the same time which is why I am looking to shorten the password. My wordpress version is: 3.5.1
Use the `random_password` hook. It will trigger on new registrations once a random password has been generated. add_filter('random_password', 'modify_the_pass'); function modify_the_pass($pass) { $pass = substr($pass, 0, 6); // make $pass six characters return $pass; // return our new $pass }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "password" }
How to use post_class function? I would like to use this function, but I don't know correctly what is the perfect way.. The code: <li id="post-<?php the_ID(); ?>" <?php post_class(get_the_content() == "" ? "no-content" : ""); ?> <?php post_class(has_post_thumbnail() ? "" : "no-image"); ?>> There are two if statements. Currently only the first working, the second not but if I remove the first `<?php post_class(get_the_content() == "" ? "no-content" : ""); ?>` the second working. How can in combine these lines?
Use the `post_class` filter to test multiple conditions: function wpa_post_class( $classes ) { global $post; if( ! has_post_thumbnail() ) $classes[] = "no-image"; if( get_the_content() == "" ) $classes[] = "no-content"; return $classes; } add_filter( 'post_class', 'wpa_post_class' ); Then your html will just be: <li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "post class" }
Links are not working on All Plugins Page I apologigize for the question, as it sounds silly. But I am forced to ask this question, as I didn't find it's answer anywhere. I have about 3 sites on WordPress, and 2 are working absolutely fine. But the 3rd one have some problem with links. I mean, If I go to **All Plugins** page, and click on **Activate** or **Deactivate** or **Delete** , then nothing happens. However if I copy the URL by mouse right clicking (and copying url), and visit after pasting it in browser, then it works properly. I have WordPress 3.5.1 with theme twenty twelve on all sites. I have also tried changing theme and removing all plugins, but still the problem exists. Can someone knows the resolution of this issue.
Steps you can take to resolve this issue: * Download Fresh Install of WordPress from Wordpress.org * Deactivate All Plugins * Deactivate Theme-Twenty Twelve and Try Activating some other Basic theme like Twenty Eleven * Disable Browser Ad-Blocker Add-ons (if any) Hopefully your problem will get solved by taking the above steps.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "links" }
How safe is it to delete old posts edits to save database space? After this question: < There is an answer that suggests deleting past edits directly from database, which would be nice, because I could create queries to delete specific edits only. But, Is this safe? Why?
The revisional feature of WordPress is only for users. That means, that if you don't need them old revisions, you can safely delete them. The system actually doesn't care.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, database, customization" }
How can I get an XML export of my 1K+ posts WordPress instance? I'd like to export my database to XML because the import script to my new blog already supports getting data from that. A database backup or wordpress clone is not that useful in this case. The problem is that using the builtin export button times out after 90 seconds. I have ssh access to the server and am not afraid to use it :) I don't really know php but I can muddle around with help. Given Problem: Create a cron job to export posts to a WordPress XML file on server I think that the export_wp function might be what I want, I just don't know what to do with that...
You guys give up too easily :) This worked for me: <?php require(dirname(dirname(__FILE__)) . '/wp-load.php'); require(ABSPATH . 'wp-admin/includes/admin.php'); require('includes/export.php'); ob_start(); export_wp(); $xml = ob_get_clean(); file_put_contents('out.xml', $xml); echo "done" ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "php, export, xml" }
Cleared wp-cache and file is still not updated I did all the following: * Deleted the cache in the WP Super Cache settings * Added `define('DISABLE_CACHE', true);` in my wp-config.php * Deleted my 'cache' folder under 'wp-content' However a theme php file is still not updating. Can anyone help me?
I found where the problem was. Everything was working correctly, but I was uploading the wrong version of the php file in question. User error, indeed, but in the process I learned a lot about the WP cache.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "cache, wp config, plugin wp supercache" }
How can I upload SVG images using the media uploader? I really love using SVG images as I can scale them as big or as small as I want. However, WordPress won't allow me to upload them using the media uploader. How can I change this? !media uploader error
You need to filter the allowed upload file types and add the SVG filetype to the list: function allow_svg_upload_mimes( $mimes ) { $mimes['svg'] = 'image/svg+xml'; return $mimes; } add_filter( 'upload_mimes', 'allow_svg_upload_mimes' ); _Also onGitHub_
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "uploads" }
How to let custom post type posts show in standard post archive (like in homepage)? If I, for example, create a custom post type named 'tutorial', how do I get it to also show up in places like "Recent posts" , etc?
Hooking the following function with the `pre_get_posts` filter will add one or more CPTs to the regular archive pages: function wpse94041_cpts_in_archives( $query ) { if( is_category() || is_tag() ) { // more conditional tags possible, if applicable $query->set( 'post_type', array( 'post', 'tutorial' // add as many CPTs to this array as you like )); } return $query; } add_filter( 'pre_get_posts', 'wpse94041_cpts_in_archives' ); Your theme's _functions.php_ file would be a good fit for the above.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, posts, archives" }
Modifying Custom Post Type after registration (will it affect content?) I have a CPT (defined in `functions.php`) that I have set to as non-hierarchical. A lot of content has already been uploaded into the database. If I change the definition to `'hierarchical' => true`, will the change affect any of the posts in that CPT?
No, it will not. It changes just the interface in the post editor: you get the page attributes box to select a parent. All existing post have already a value for the parent: `0`. You can find it in the `post_parent` property of each post. The only thing that changes now is the ability to change that value.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, functions, hierarchical" }
Problem with update_user_meta() meta_value I am trying to insert a large number of user in to the wordpress db using wp_insert_user(). After inserting each user, I am trying to add an user meta for each user. I am doing like this: $meta_value = //data from an API (e.g.: 19, 34, 1290 etc) $user_id = wp_insert_user( $new_user_data );// it works fine update_user_meta( $user_id, 'my_meta_key', $meta_value ); //does not work When I run it, user get inserted, but not the meta. When I try like below, it works: $user_id = wp_insert_user( $new_user_data );// it works fine update_user_meta( $user_id, 'my_meta_key', '1290' ); //it works I have over 1000 users, I need to insert, so I need to insert the meta dynamically as well. Any idea how can I overcome this? Thanks.
I fixed it doing like below: $meta_value = //data from an API (e.g.: 19, 34, 1290 etc) $meta_value_string = "". $meta_value; $user_id = wp_insert_user( $new_user_data ); update_user_meta( $user_id, 'my_meta_key', $meta_value_string ); Now it works fine.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "users, user meta" }