INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
How can I change the default wordpress password hashing system to something custom? Can I change the default wordpress password hashing system by overriding the wp_hash_password function from plugin? If yes, then what will happen to old stored passwords in DB? How will they be validated for login?
Just figured it out. So thought to leave the solution here, if someone else need it: To change the default hashing system, need to overwrite wp_hash_password() function: (can be done in a plugin) if ( !function_exists('wp_hash_password') ){ function wp_hash_password($password) { //apply your own hashing structure here return $password; } } Now you will need to overwrite wp_check_password() to match your hashing structure: (can be done in a plugin as well) if ( !function_exists('wp_check_password') ){ function wp_check_password($password, $hash, $user_id = '') { //check for your hash match return apply_filters('check_password', $check, $password, $hash, $user_id); } } Please check wp_check_password
stackexchange-wordpress
{ "answer_score": 12, "question_score": 7, "tags": "password" }
How to do an event when any user updates their profile? I want to call a function, whenever any user update their profile. How to do that?
It seems as if the hook `personal_options_update` might be what you're looking for. add_action( 'personal_options_update', 'my_custom_func' ); function my_custom_func( $user_id /* if you need that */ ) { ... }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "updates, profiles" }
Add a class to post_class if more than one post shares same meta_value_num I would like to be able to add a class such as `.samedate` to posts that share the same `meta_value_num` from a custom meta box. So for example: Say two posts share the same custom meta box value for a date entered as `2013/11/03`... If those two posts have the same meta value number, then add the class to those posts.
add_filter('post_class', function($classes){ global $wp_query; static $meta = array(); // first call gathers meta values if(!$meta) foreach($wp_query->posts as $post) $meta[$post->ID] = get_post_meta($post->ID, 'your_meta_key', true); // $wp_query->post should be the global (current) $post object $this_meta = $meta[$wp_query->post->ID]; if($this_meta){ $counts = array_count_values($meta); if($counts[$this_meta] > 1) $classes[] = 'your_class'; } return $classes; }); _(untested)_
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, custom field, metabox, post meta, post class" }
Hide prices and checkout functionality in woocommerce I know this question might be too broad, but I'm looking for a bit of direction. My client has a woocommerce store with 30-40 products. For whatever reason they do not want to sell online anymore, but they want to retain the product pages, information, etc. on their website. Is there a way, using hooks or otherwise, to hide things like prices, add to cart button, etc. in woocommerce? Or should I just edit the php template files?
luckily woocommerce has many hooks, this removes prices and buttons: remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_add_to_cart' ); remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_price', 10 ); remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_add_to_cart', 30 ); remove_action( 'woocommerce_after_shop_loop_item_title', 'woocommerce_template_loop_price', 10 ); you can dig into `content-product.php` and `content-single-product.php` if you need to remove more stuff. I can imagine there's more than just the prices/buttons you want to hide/remove though (like pages/functions), this tutorial gives you some pointers
stackexchange-wordpress
{ "answer_score": 23, "question_score": 18, "tags": "plugins, themes, woocommerce offtopic" }
How to create custom WooCommerce 2.0 templates I'm working on a site for a client who is using version 2.0.1 of WooCommerce plugin and I'm lost as to how I can create new page templates for it. With previous versions of the plugin is was simple, you just copied files from the "templates" folder into your theme folder and boom! But now, that folder is gone. The WooThemes documentation is still being updated to reflect the upgrade to 2.0 so that's no help. Any assistance would be more appreciated.
Actually, the templates folder is still included in WooCommerce, just like before. Just copy its contents to yourtheme/woocommerce and, hey presto, it works! N.B. This doesn't work when you use the woocommerce_content() function in a woocommerce.php. WooThemes actually have a good primer page that they even link from a nag after you have installed WC2.0.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins" }
ABSPATH not working! Any idea why? This is what in my wp-config.php : if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); I am calling from plugin/pluginName directory to : require_once( ABSPATH . 'wp-includes/user.php'); But it is returning: Warning: require_once(ABSPATHwp-includes/user.php) [function.require-once]: failed to open stream: No such file or directory in /home/------/wp-content/plugins/---/---.php on line 43 Fatal error: require_once() [function.require]: Failed opening required 'ABSPATHwp-includes/user.php' (include_path='.:/usr/lib/php:/usr/local/lib/php') in /home/------/wp-content/plugins/---/---.php on line 43 Any idea why I am having this error? Any solution? Thanks.
If you just need that class included, and your script is located in the plugin directory, like `/wp-content/plugins/pluginName/script.php`, then you can do: require realpath('../../../wp-includes/class-phpass.php');
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "include, paths" }
Finding and removing duplicates within WP Arrays I'm looking to see if it's possible to find and remove duplicates from the arrays generated below. I've tried `array_unique` `array_merge` and they haven't worked. $category = get_the_category(); $tags = wp_get_post_tags($post->ID); As an example, there is a potential that the word "Apparel" may appear in both Category and Tag for the post. With the "raw" method above, Apparel would appear twice in my output. I'm only looking to include it once. At this point in time, I believe it is ok if both lists are merged and all words are part of 1 output. Example: `%23Apparel %23Auto %23Mens` Then, once the output is generated, I need to add HTML URLEncode %23 to the beginning of each word. Would appreciate your input.
If you only want to collect the category+tag names into the output, you can try this <?php global $post; $words=array(); $tags = wp_get_post_tags($post->ID); foreach($tags as $tag){ $words[]="%23".$tag->name; } $cats = get_the_category($post->ID); foreach($cats as $cat){ $words[]="%23".$cat->name; } $words=array_unique($words); echo implode(" ",$words); ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, array, categories" }
Create archives by author role I have a site that will have some custom roles (capabilities), and I would like to have archives that list authors based on their role. authors.php list the profile of one author, but there is no template for listing authors, right? Is a custom template the only way to do this? I would rather not have empty pages that just serve as holders for my archives. Thanks
You may be able to abuse `add_rewrite_endpoint` for this purpose, depending on exactly what you want to do. Some examples: // add an endpoint // http:domain.com/role/ // http:domain.com/role/foo/ function wpa_add_role_endpoint(){ add_rewrite_endpoint( 'role', EP_ALL ); } add_action( 'init', 'wpa_add_role_endpoint' ); // check if a role parameter exists, like: // http:domain.com/role/foo/ function wpa_role_query( $query ){ if( $query->get('role') ){ echo $query->get('role'); // echoes 'foo' // modify the query $query->set( 'somevar', 'someval' ); } } add_action( 'pre_get_posts', 'wpa_role_query' ); // check if role is in query vars array, like: // http:domain.com/role/ function wpa_role_parse( $query ){ if( array_key_exists( 'role', $query->query_vars ) ) die('role query'); } add_action( 'parse_request', 'wpa_role_parse' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "archives, author template" }
Most efficient way of deleting post I have a cron job set to remove a (sometimes large) number of posts from my database. Of course, I also need to remove all associated data such as custom fields. This is the function I'm currently running, but it's taking a bit long to delete everything. Would it maybe be more efficient to make a direct SQL query? /** * Delete all items * */ function myplugin_delete_all_items() { $args = array( 'post_type' => 'my_post_type', 'posts_per_page' => -1, ); $items = new WP_Query( $args ); if ( $items->have_posts() ) : while ( $items->have_posts() ) : $items->the_post(); $postid = get_the_ID(); $purge = wp_delete_post( $postid, true ); endwhile; endif; wp_reset_postdata(); }
Yes, but unless you have total understanding of your system and it is going to be frozen at that state, this can be dangerous. 1. Can you be sure that you know all the places in the DB where the post is referenced? There is the post table, the metadata table, taxonomies, and plugins. If you figure it all out, are you sure you no one will install some new plugin which uses additional tables 2. If you use caching plugins, how will the information be deleted from the cache? In addition, the risk, even if it is small, is probably pointless as cron processes take place away from the eye of the user so it doesn't matter much how much time they take.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, database, performance" }
Avoiding page loop I'm doing a custom page that has multiple wp query calls, the thing is that I don't need the main query that is I don't need anything from the page contents, so in order to save load time I was wondering how to tell wordpress not to fetch anything from the db ?
I would highly recommend you to make one of those wp query calls the main query & all others as secondary queries. That will make your life much easier in the long run. If you absolutely want to disable the main query, wordpress doesn't have a direct filter for that. You can however do a trick to achieve that 1) hook into `parse_request` action 2) Examine the request variables to determine if you are on the correct page 3) If you are not on the correct page, use `return;` & let wordpress go its normal route 4) do your custom wp query calls & output the HTML 5) use `die();` to stop php execution This should work, however you should note that, since wordpress never got a chance to populate the global variables, accessing them directly or via some core wordpress function will have unexpected results. Next, some plugins may also have problems. Make sure you carefully test all of the code you're using.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, pre get posts" }
How to use WP_Query() on single.php? I'm using `WP_Query()` to pull out a few posts under a specific category "Featured" to display at the bottom of any post. So I added `<?php if (function_exists('getEditorPicks')) getEditorPicks();?>` in single.php. In functions.php, I have wp_reset_postdata(); $args = array('cat' => 4176, 'posts_per_page' => 5); $query = new WP_Query($args); //return $query->query_vars; if ($query->post_count>2) { while ($query->have_posts()) { $query->the_post; echo the_title(); } } wp_reset_postdata(); However, it takes forever for the page to load now and it simply exhausts memory in the end. What am I missing here?
$query->the_post; should be: $query->the_post(); The first is trying to fetch a property named `the_post` rather than invoking the function so the post never advances, and your loop is infinite.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp query, loop, single, memory" }
Write query according to post_meta I have a front-end form which stores some data related to that post and adds that post to their `favorite` posts when the user clicks on it. So now my concern is when the user clicks on the favorite posts template it should only see their favorite post. $args = array('posts_per_page' => 20, 'paged' => $paged, 'post_type' => 'post', 'post_status' => 'publish' ); This is my query right now. How can I modify it that it only show those post which the user mark as favorite? add_post_meta($postid, 'favpost'.$userID, $postid); This is how the user marks their favorite post. Can anyone guide me on how I can get my data base on `post_meta`?
change the $args to this: $args = array( 'posts_per_page' => 20, 'paged' => $paged, 'post_type' => 'post', 'post_status' => 'publish', 'meta_query' => array(array('key'=>'favpost'.$userID, value=>'1', 'compare' => '=')) ); That is if the post_meta value is 1 when the user select that post as it favorite, or it could also be 'true' you will have to check that value on the custom fields area of the post edit.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "post meta" }
How we count the user draft posts I am trying to use the total posts count currently i am using the this query $args=array( 'author' => $userID, 'post_type' => 'post', 'post_status' => $poststatus, 'posts_per_page' => 212 ); <?php echo count_user_posts($args); ?> `$poststatus` have 2 options `draft` and `publish`. But when i run this query one condition work good and that is `publish`. but when i try to run `draft` it not showing correct count of draft posts. So tell me where i am wrong in the query.
The function `count_user_posts` only accepts a user ID so you arguments are never taken in consideration. Here is a simple function to get the count by status function count_user_posts_by_status($post_status = 'publish',$user_id = 0){ global $wpdb; $count = $wpdb->get_var( $wpdb->prepare( " SELECT COUNT(ID) FROM $wpdb->posts WHERE post_status = %s AND post_author = %d", $post_status, $user_id ) ); return ($count) ? $count : 0; } Usage: <?php echo count_user_posts_by_status('draft',$userID); ?>
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "count" }
'Easy Table' Plugin has float issues Good day I am using the easy table plugin and I have a problem with floats with it: Any content I add below the table floats to the right of the table. Now I can solve this by using a <div style="clear: both"></div> but isn't there a more 'user-friendly' way of doing it? That way my clients (with no html/css experience) can use the tables without problems... Table Shortcode Code: [table caption="Just test table" width="500" colwidth="20|100|50" colalign="left|left|center|left|right"] no,head1,head2,head3,head4 1,row1col1,row1col2,row1col3,100 2,row2col1,row2col2,row2col3,20000 3,row3col1,,row3col3,1405 4,row4col1,row4col2,row4col3,23023 [/table]
You should take a look at the CSS the table uses. Right now it probably uses `float:left` values. Use Firebug or a similar tool to check if this is the case, and try to edit the CSS.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "plugins" }
How to get current pages menu text? Is there an easy way of outputting the current pages menu text? I am looking for something like <?php echo get_the_title(); ?> But for the current pages menu text.
You can get a Menu's entire item list with wp_get_nav_menu_items(). Then, loop through them all and test against the current post_id, and voila, you have all your data. <?php $menu_items = wp_get_nav_menu_items( 'main-menu' ); foreach( $menu_items as $item ) { print_r( $item ) ; // see what you can work with // carry on }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus, walker" }
Is it safe use wp_editor in public contact form I'm going to make a contact form for my site, and i want to use WYSIWYG editor (wp_editor) in my form message field. Here is my question, is that safe use wp_editor in public though disable media button? something like this: Thanks.
It should be fine and secure, as Horttcore mentioned it isn't making any database or backend changes it is simply displaying the tinymce editor. There are other plugins you could use of course but I don't see any problems doing exactly what you are doing. To answer your other question, I believe the text/visual switch is stored in a cookie so only you would see this change and only if you switched it on the public form yourself - other people changing it on the public end won't change your settings for text/visual on the backend.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "security, wp editor" }
SSL Certificate and WordPress One of my clients has decided to install an SSL certificate for his website/domain. I have developed a WP website for them it's ready to be deployed. We are currently accessing it via the IP address and it works fine. Normally I just change the URL settings via admin (2 options) and run a search and replace throughout the database, and that's all that's needed. Should I be doing anything else for SSL? I assume the URL should also start with https:// in the admin settings right?
There is no need to hardcode anything and/or alter database entries. I'd highly recommend you'd check out the following plugin: WordPress HTTPS \- it's quite versatile and will handle everything for you.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "ssl" }
What is $interim_login? I found an `$interim_login` variable within the `wp-login.php` file, and I'm not sure what it does or what it is. The documentation around the interwebs is pretty sparse. What is `$interim_login`?
The variable `$interim_login` is `TRUE` when the log-in session of a user expires while she is working in the back end, for example during an auto-save action. In this case a message asking to log in again appears at the bottom of the editor: > !enter image description here The same can happen in the theme customizer. The `$_REQUEST` variable that switches the log-in form to _interim_ is `interim-login`. Note how the underscore is replaced with a dash for no obvious reason.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 9, "tags": "login, authentication" }
What exactly is ReAuth? Searching for " **WordPress Reauth** " and the like all result in folks who are having problems with `ReAuth=1`. What exactly is ReAuth?
`ReAuth=1` is required when your login `Cookies` are no longer valid, WordPress will force validation for your browser. if ( $force_reauth ) $login_url = add_query_arg('reauth', '1', $login_url); > * Add reauth=1 flag to login url when auth_redirect() redirects to wp-login.php after the auth cookie fails validation wp-login.php clears cookies and forces log in if reauth=1. > * If reauth=1 wp-login.php does not attempt to redirect to wp-admin, even if the cookie seems good. > > > Basically, this forces reauth/login whenever auth_redirect() does not think the user is logged in. This should resolve the situation where one cookie seems good but another does not. \--- Ryan via Trac 12142 To fix issues with this you can clear your cookies and change your Security Keys, or use `wp_set_auth_cookie`. Some reference: < <
stackexchange-wordpress
{ "answer_score": 8, "question_score": 7, "tags": "login, authentication" }
Customizing a permalink Good Day All I have a featured slider on the home page that can call a category from which it gets its featured content. Now, for each featured slider, I made a post with category 'featured'. Now the problem is, that currently when you click on the featured slide, you get directed to its originating post with category 'featured'. <h2 class="featured-title"><a href="<?php echo esc_url($arr[$i]["permalink"]); ?>"><?php echo esc_html($arr[$i]["title"]); ?></a></h2> Now, what I would like to achieve is to change that dynamic link (above) to point to a specific category, and the category it should point to is exactly the same as the title that makes up this link - (title = h2 featured-title text) So the dynamic url should point to in the above link... Is that possible? Thank you! Thank you
try this: <h2 class="featured-title"><a href=" echo strtolower(str_replace(" ","",$arr[$i]["title"])); ?>"><?php echo esc_html($arr[$i]["title"]); ?></a></h2>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, navigation" }
Woocommerce - Print Product's Custom Field In Email In Woocommerce 2.0, I need to print a custom field on the New Order email. It is a meta/custom field each product has named "longsku" (which is normally hidden.) This needs to be included in the email-order-items.php email template but I am not certain what syntax is necessary to print it. For instance, variations are printed like so within the email template: echo ($item_meta->meta) ? '<br/><small>' . nl2br( $item_meta->display( true, true ) ) . '</small>' : ''; Does anyone have experience printing custom fields from products (not from actual checkout) in the email templates?
the longsku is regular wordpress post meta, so you can simply call that with get_post_meta. get_post_meta takes three arguments: * post_id (which is already available in $_product)] * meta key ('longsku' in your case) * and a boolean to return a single string (true). if not set, it returns an array, but since the meta key is just a single value you can use true this should do the trick for your longsku: echo get_post_meta($_product->id,'longsku',true);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "customization, plugins" }
Why are you using add_action for shortcode? I would like to create `shortcodes`, but some tutorials write about to use `add_action`: add_action( 'init', 'register_shortcodes'); But I read another tutorial where the author didn't use it, only put this to `functions.php`: add_shortcode( 'recent-posts', 'recent_posts_function' ); Which is the best method, and why to use `add_action`?
If you take a look at the Codex page about `add_shortcode()` you won't see anything about the need of an `add_action()` before you can use `add_shortcode()`. So, you can just put your `add_shortcode()` directly into your `functions.php`. This is what I do too. See this article - WordPress Shortcodes: A Complete Guide about the use of shortcodes and best practices.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 8, "tags": "shortcode, actions" }
add_menu_page() with variable function How can I use `add_menu_page()` functions some variable function ? add_menu_page('My page','My page','manage_options','my_page', 'func' ); $func = function() { echo "Done !"; }; I know I can use like function func() { echo "Done !"; }; But how can I use like $func = function() { echo "Done !"; }; to call it ?
You have to declare the closure before you call `add_menu_page()`: $func = function() { echo "Done !"; }; add_menu_page('My page','My page','manage_options','my_page', $func ); Note you need PHP 5.3 to do that.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "functions, variables, add menu page" }
W3 Total Cache CSS & JS files GZip issues Having checked my site with google page speed and gzipwtf.com I have noticed that my css and js files are not getting compressed (although html is). Have tried unchecking " Prevent caching of objects after settings change " and have thus removed query strings from these files but that has had no effect. Have also tried adding the following (both above and below wordpress rules) in htaccess to no effect also: # BEGIN GZIP <ifmodule mod_deflate.c> AddOutputFilterByType DEFLATE text/text text/html text/plain text/xml text/css application/x-javascript application/javascript </ifmodule> # END GZIP Would any one have any advice as to what I may be able to do to rectify this? Many thanks
Thanks to @Pothi Kalimuthu I checked with my hosting company to see if mod_deflate was enabled, and it wasnt. This was the problem. I mistakingly believed that it was by incorrectly reading the results of phpinfo.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "htaccess, plugin w3 total cache" }
wordpress get meta value by meta key How to get the meta value by meta key I want to get the value by the meta key. This is what I have tried so far: $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => -1, 'meta_key' => 'picture_upload_1' ); $dbResult = new WP_Query($args); var_dump($dbResult); but I am not receiving the meta value
`WP_Query` selects posts and not meta value that is way you are not getting the value. You can use the returned post ID to get the value something like: $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => 1, 'meta_key' => 'picture_upload_1' ); $dbResult = new WP_Query($args); global $post; if ($dbResult->have_posts()){ $dbResult->the_post(); $value = get_post_meta($post->ID,'picture_upload_1',true); } which will get the meta value of the last post published which has a custom field named `picture_upload_1` another thing you can do is create a query your self , something like: global $wpdb; $value = $wpdb->get_var( $wpdb->prepare("SELECT meta_value FROM $wpdb->postmeta WHERE meta_key = %s LIMIT 1" , $meta_key) );
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "plugins, plugin development, meta query" }
get_posts() and filters I've added a custom filter function for `the_posts` filter in a plugin. add_filter('the_posts', 'posts_filter'); function posts_filter() { … } This works pretty well in the main loop, that means the posts are filtered in the way I defined in the `posts_filter` function. But I am calling `get_posts()` within an ajax request to get some posts. And there the filters aren't working. `query_posts()` or custom `wp_query` don't work too. So the question is: How can I get posts beside the main loop which are filtered by `the_posts` filter?
`the_posts` does work for all queries including the main query as well as custom queries but doesn't work when using `get_posts()`. This is because `get_posts()` automatically suppresses all the filters. If you want to use the filters even when using `get_posts`, you can pass an extra key `'suppress_filters' => false` in the array you pass as argument to `get_posts()`
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "filters" }
Get custom thumbnail sizes If I use: add_image_size('main_image', 750, 375, true); to add additional thumbnail size. Then how can i get that size if i have only key `main_image`.
This is answered here: Get post thumbnail size global $_wp_additional_image_sizes; // Output width echo $_wp_additional_image_sizes['main_image']['width']; // Output height echo $_wp_additional_image_sizes['main_image']['height'];
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "images, post thumbnails" }
wp e-commerce single-product template giving 404 this page was working initially, and then I made some changes which *** _didn’t_ *** appear, and then it just stopped showing that page altogether. I have tried deleting my `wpsc-single_product.php` and replacing it with the default one provided but it still just shows 404. My category page does the same, in fact the only pages I can get to work are the ones that are actual pages (checkout, transaction results etc.) - this made me think it could be a url rewrite problem but considering it was working before and I haven’t made any changes to my .htaccess or infact any other file it probably isn’t. Shouldn't it default to the `wpsc-single_product.php` file that is in the plugin directory anyway - like it did before I copied the file over in the first place? What could have made this happen?! Please help? Thanks in advance for any help or advice, Billy
I fixed this in the end. There is a button in the wpsc settings page under presentation to flush the theme cache. Caption: > If you have moved your files in some other way i.e FTP, you may need to click the Flush Theme Cache. This will refresh the locations WordPress looks for your templates. Simple, and hard to miss, but I managed to!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "templates, 404 error, plugin wp e commerce" }
Retrieving custom field value with get_post? There's no mention of custom fields values in Get_post's codex page. Is it impossible to use get_post to get a custom field value of some post, and if so, is it necessary to perform a whole loop just for that?
All of the custom field functions accept the post id as a parameter. You can use all those functions directly without the need to actually retrieve the post itself.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, get post" }
How do I use fetch_feed() to pull in a large number of posts? When I use fetch_feed() to pull in posts from a feed, even if I set the maximum posts variable to a very high number, it will only pull in 10 posts. I want to pull in all the posts and then paginate the way I would for my regular blog posts. I thought maybe it was set to the number in my Reading settings, but I changed it to 30 with no change. There are definitely more than 10 posts in the feed I am trying to pull in. Is this possible or is this inherently limited for this function?
It sounds like your source feed is showing only 10 posts. So, regardless of what you pit for get_item_quantity, only 10 posts will show, max. If you're pulling posts from a WordPress site, you can adjust how many posts are included in the RSS feed in Settings -> Reading. Change this value: "Syndication feeds show the most recent"
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rss, feed" }
Alternative to new_to_publish Hook for Custom Statuses I am looking for the right hook to use for sending out an email notice when a post is inserted. However, I am using custom statuses (in this case 'holding') which doesn't seem to get hit with the new_to_holding hook, so was hoping someone knew of an alternative that gets fired when a post is inserted or perhaps a reason why that hook isn't working right.
new_to_holding doesn't exist as a post status transition - you need to use the generic transition_post_status action. Something like (untested): add_action('transition_post_status','my_holding_function', 10, 3); function my_holding_function( $new_status, $old_status, $post ) { if ( 'holding' == $new_status ) { // do stuff } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "hooks, wp insert post, post status" }
Troubleshoot "You do not have sufficient permissions to access this page." I recently changed the database table prefix from wp_ to something else, for security reasons. Since then, I am unable to reach /wp-admin, instead receiving > You do not have sufficient permissions to access this page. I read this question, and I renamed `wp_user_roles` to `myprefix_user_roles`. This did not resolve the problem, even after clearing my browser cache and cookies. How do I resolve this?
Changing the db prefix on a WordPress installation requires more than simply changing the prefix on the tables. There are also options that use the db prefix in the options tables. You'll need to update them as well. Specifically the `wp_user_capabilties` and the `wp_user_level` keys in the `{db_prefix}_options` table. See the following tutorial for further information: > ### How to Change the WordPress Database Prefix to Improve Security > > The smartest way you can protect your database is by changing the database prefix which is really easy to do on a site that you are setting up. But it takes a few steps to change the WordPress database prefix properly for your established site without completely messing it up. **Example SQL Queries** UPDATE new_usermeta SET meta_key = REPLACE(meta_key,'old_','new_'); UPDATE new_options SET option_name = REPLACE(option_name,'old_','new_');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "permissions" }
How to add active class to separate page link? I'm using the Wordpress Bootstrap theme as my base theme. It uses the following code to add the class "active" to any links in the header if the user is currently on that page: add_filter('nav_menu_css_class', 'add_active_class', 10, 2 ); function add_active_class($classes, $item) { if($item->menu_item_parent == 0 && in_array('current-menu-item', $classes)) { $classes[] = "active"; } return $classes; } However, I have multiple pages that I want to display as "active" when the user is not actually on that specific page. For example, users may sometimes be on "tutorials-by-topic" (Tutorials by Topic) but I want the link titled "Tutorials" to be displayed as the active link. I have four pages I want to do this way. I have tried different conditionals, etc. in the add_active_class function but I've had no luck. Any guidance? Thanks!
Not the cleanest solution, but I use something like this for a few instances of current page menu highlighting for pages that aren't child/parent related in any way: <?php if (is_page('tutorials-by-topic') { ?> <script type="text/javascript"> jQuery(function($) { $(document).ready(function() { $('#menu-main-menu li.menu-item-1319').addClass('current-menu-item'); }); }); </script> <?php } ?> You have to look at the source to get the correct menu-item-xxxx for the page that you want to highlight as current in the menu.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "menus" }
Allow certain part of a page to be easily updated for client? My client has asked me to create an about me section which will include a picture, job title and description for each team member as floated elements. They also want it to be as easily updateable as adding a post to a blog. So if they wanted to add a new team member within the same page, they will want to upload the image and enter text into the job title and description box and click publish. Then the new member will appear next to the existing ones. As a newbie to WP, how would I go about achieving this? I've heard of custom post types but I can't find any tutorials on displaying data in one page. Any tutorial links or advice would be highly appreciated.
I found this WpTuts+ article about Custom Post Types for you. This is an article that will explain what exactly Custom Post Types are and how to accomplish creating one. This will help you along. Also, I found this wpbeginner article about creating custom archive pages. You can use this article to create the custom page wich will show each team member.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, dashboard" }
go to home page when i select default in select-box I'm new for WordPress. I'm using following code, <div id="cat_list"> <?php wp_dropdown_categories(array('show_option_all' => 'Categories') ); ?> </div> And my JavaScript is, <script type="text/javascript"> var dropdown = document.getElementById("cat"); function onCatChange() { if ( dropdown.options[dropdown.selectedIndex].value > 0 ) { location.href = "<?php echo get_option('home'); ?>/?cat="+dropdown.options[dropdown.selectedIndex].value; } } dropdown.onchange = onCatChange; </script> If I select any Category means, that goes to correct page. But my requirement is, Will be go home page when re-select `Categories` (show_option_all). Any option is in WordPress? other what to do?
You can try this <script type="text/javascript"> var dropdown = document.getElementById("cat"); function onCatChange() { if ( dropdown.selectedIndex == 0 ) { location.href = "<?php echo get_option('home');?>"; }else if ( dropdown.selectedIndex > 0 ) { location.href = "<?php echo get_option('home');?>/?cat="+dropdown.options[dropdown.selectedIndex].value; } } dropdown.onchange = onCatChange; </script>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, categories, javascript, dropdown" }
How can I limit page parent dropdown to show only author's own pages? I'm trying to get the page parent dropdown (in page attributes) to show only pages that have been published by the author of the current page. This doesn't seem to work : add_filter( 'page_attributes_dropdown_pages_args', 'mwm_show_only_author_pages_in_attributes' ); add_filter( 'quick_edit_dropdown_pages_args', 'mwm_show_only_author_pages_in_attributes' ); function mwm_show_only_author_pages_in_attributes( $args ) { global $post; $args['author'] = $post -> post_author; return $args; } What am I doing wrong here ?
From the source code the function wp_dropdown_pages uses get_pages() and this function uses different attributes than WP_Query or get_posts(). It uses **authors** instead of **author**. Note from the codex: > authors (string) Only include the Pages written by the given author(s) Note: get_posts() uses the parameter 'author' instead of 'authors'.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp admin, author, page attributes" }
how to add version of style.css in wordpress How to add version of `style.css` in WordPress like below i can do in Joomla. <link rel="stylesheet" href="/templates/example/css/style.css?v=1.2"> i know that the `style.css` will load dynamically. please help me to how to do that.
Version number is a parameter of `wp_enqueue_style()`. As per the Codex, here are all the parameters that `wp_enqueue_style` accepts. wp_enqueue_style( $handle, $src, $deps, $ver, $media ); So for example to load a stylesheet with a version number you'd do the following: function wpa_90820() { wp_enqueue_style('my-styles', get_stylesheet_directory_uri() .'/my-styles.css', array(), '1.0' ); } add_action('wp_enqueue_scripts', 'wpa_90820');
stackexchange-wordpress
{ "answer_score": 20, "question_score": 20, "tags": "themes, css" }
wordpress remove views from action links in a custom post I have created a custom post type, but I want to remove the View link from actions, in the listing of the custom post. I have tried this snippet add_filter( 'post_row_actions',array(&$this, 'remove_row_actions', 10, 1)); public function remove_row_actions($action){ unset($action['view']); return $action; } But it throws > `call_user_func_array() expects parameter 1 to be a valid callback, array must have exactly two members in D:\wamp\www\wordpress\wp-includes\plugin.php on line 173`
You've got typo in your add_filter. Try this: add_filter( 'post_row_actions',array(&$this, 'remove_row_actions'), 10, 1); public function remove_row_actions($action){ unset($action['view']); return $action; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, posts, plugin development, filters" }
Show only one category in main query, issues on tag page I altered the following code from Ashfame: add_action('pre_get_posts', 'block_cat_query' ); function block_cat_query() { global $wp_query; if( is_home() || is_search() || is_tag() ) { $wp_query->query_vars['cat'] = '3'; } } This code DOES work to filter posts from category #3 only on the home, search and tag pages. However, I am utilizing <?php single_tag_title(); ?> in my header.php file and on specific tag pages, the tag title is not showing up. The page is instead showing the category title. This is only happening with this function in place, so I'm trying to figure out if there is another way of writing the function above that does not effect the use of `<?php single_tag_title(); ?>` on tag pages.
If the only issue you want to correct is the output of `single_tag_title`, you can correct the value via a filter by grabbing the tag query var directly: function wpa90852_fix_tag_title(){ $tag = get_term_by( 'slug', get_query_var('tag'), 'post_tag' ); return $tag->name; } add_filter( 'single_tag_title', 'wpa90852_fix_tag_title' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "categories, functions, wp query" }
Why does my taxonomy have a category style div id? I created two custom taxonomies. I created them using identical code and then finding and replacing the "name" with "name2". I've then looked at the post type page and there are two tag boxes to choose tags in. However, one div is called "namediv" and the other is "tagdiv-name2". This would suggest that one is a category and one is a taxonomy. I know that categories are kind of a taxonomy, but why is my custom taxonomy taking the form of a category? Thanks, Simon
WordPress uses the `category`-style meta box to handle `hierarchical => true` taxonomies and the post tags meta box for "flat" taxonomies. The CSS in the admin UI is just ... "grown", so names like those don't change until they really need to. `category` and `post_tag` btw are just `name`s for `_builtin => true` taxonomies.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, categories, custom taxonomy, tags" }
Set featured image randomly from Wordpress Database on post submission Basically every time that I publish a post I want that a random image from my wordpress database be set as the feature image for that post. Can someone help me with this please!
Here is a way: // listen for post being published add_action('publish_post', 'dreis_random_featured_image'); function dreis_random_featured_image() { global $post; // find one random image $args = array( 'post_type' => 'attachment', 'post_mime_type' => 'image', 'post_status' => 'inherit', 'posts_per_page' => 1, 'orderby' => 'rand' ); $random_image = new WP_Query($args); foreach($random_image as $image){ // set as thumbnail set_post_thumbnail($post->ID, $image->ID); } // reset loop to avoid weirdness wp_reset_query(); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, images" }
Using shortcodes to parse POST request (containing the data from a front-end form) I would like to allow my subscribers to post classifieds, which are nothing but a custom post type with a few metas for the price, etc. (The existing classifieds plugins I have tried are way too complex for my needs.) I would like to know if the following makes sense. * I define a [classifieds-form] shortcode displaying the form and I create a page (ie., a "page" post in the admin section) calling it. * The content of the form is POST'ed to another page which calls the [handle-classified] shortcode, which checks if the user is logged in, parses the $_POST data, and inserts the custom post (with a 'pending' status, until an admin validates it). Does this sound reasonable to you? Or would you recommend a more "standard" way of doing this? Thanks a lot!
Alway send submissions to the page the form is displayed. In your shortcode callback you can then display proper error or success messages. Sample: add_shortcode( 'classifiedsform', 'classifiedsform_callback' ); function classifiedsform_callback() { if ( 'POST' !== $_SERVER['REQUEST_METHOD'] or ! isset ( $_POST['classifieds'] ) ) { return classifieds_input_form(); } // process input show errors or success message } function classifieds_input_form() { // return a string with the form HTML } Make sure you don't use a reserved variable or WordPress will drop the content silently.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "custom post types, shortcode, forms" }
Check if current page is wp-admin I have created a common custom dashboard for my users located at "< I'm trying to redirect users to that custom dashboard only if they are NOT admins & if the page IS < The redirection function I have is: add_action( 'admin_init', 'redirect_so_15396771' ); function redirect_so_15396771() { if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) return; if ( current_page('is_admin()') & !current_user_can('delete_users') ) { wp_redirect( site_url( '/login/dashboard/' ) ); exit(); } }
You can test for roles with `current_user_can()`: if ( is_admin() && !current_user_can('administrator') ) { // redirect }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "php, functions, conditional tags, wp redirect" }
Using a page template without a page Does anyone know if it's possible to use a page template on a URL, even if a page doesn't exist for that page? When building sites, I create the relevant pages to ensure use of the templates, but then if the site admins later delete that page, it breaks the site. I'v read that it's possible to add custom URL rewrites, but is there a way to create a custom URL, but use a regular page template to render up the content (using get_header/footer() & other functions within the page)?
What I would advice, and have done myself when making WordPress sites for clients. Create a custom post type that they can’t get access to. You can achieve this by conditionally removing the post type from the admin sidebar. One of the ways to solve that problem is to add a custom capability to the user(s) that you would like to allow editing these critical pages, lets call the capability "edit_ciritical_page" Then in your function.php/file included from function.php/plugin file you say if (!current_user_can("edit_ciritcal_page") { remove_menu_page('edit.php?post_type=critical_post_type'); } If you don’t what to add the custom capability, you could also just check it based on the username/user email.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 5, "tags": "url rewriting, templates, page template" }
pre_get_posts for exclude category This code works perfectly function exclude_category( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'cat', '-1' ); } } add_action( 'pre_get_posts', 'exclude_category' ); But this code does not work at all $caid = "-1"; function exclude_category( $query ) { if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'cat', $caid ); } } add_action( 'pre_get_posts', 'exclude_category' );
`$caid` is unknown inside the function, unless declared global. $caid = '-1'; function exclude_category( $query ) { global $caid; if ( $query->is_home() && $query->is_main_query() ) { $query->set( 'cat', $caid ); } } add_action( 'pre_get_posts', 'exclude_category' ); **// Edit** Do you need the variable outside the function at all? If not, just move it inside the function, then you can ommit the `global`. **PHP** : Variable scope
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "pre get posts" }
get_the_category_list open in parent window I'm opening my posts in an iframe, and I'm using `get_the_category_list` to list post's categories. The problem is that when a user clicks on the category link, it opens in the iframe. How can I set the target for these generated links to be "_parent"?
`get_the_category_list` runs it output through the filter `the_category`. You could hook in there and change whatever you like. Something like this should work (untested): <?php add_filter('the_category', 'wpse90955_the_category'); function wpse90955_the_category($cat_list) { return str_ireplace('<a', '<a target="_parent"', $cat_list); } If you just need to have that list filter in certain spots, you can define the function above in a plugin or theme's `functions.php`, then add the filter, call `get_the_category_list`, and remove the filter. <?php // assume wpse90955_the_category was defined elsewhere and is already loaded add_filter('the_category', 'wpse90955_the_category'); echo get_the_category_list($some_sep, $parents, $some_post_id); remove_filter('the_category', 'wpse90955_the_category');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories, iframe" }
Show all parts in multipage post You can do a multipage post by using the `<!--nextpage-->` inside the post. The question is: How can I display the whole post (not paged) for this post.
Well, you can turn it off completely or use the following code along with some sort of conditional statement to switch it on or off. The multipage part is set up in the `setup_postdata()` function in `wp-includes/query.php`. There's an action at the end of the function called `the_post`. If you hook onto that and then modify the globals that are set up in the function you can undo the multipage config: add_action( 'the_post', function( $post ) { global $pages, $numpages, $multipage; $pages = array( implode( '', $pages ) ); $numpages = 1; $multipage = 0; } ); Add that to your functions.php or plugin and you're good to go.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "templates, pagination, nextpage" }
Hooking in to an archive page? I'm making a custom post type that I want to use in the form of a plugin - all pretty straight forward. However, I want the archive page for this post type to look slightly different in the content area - how would I achieve this without having to ask the end user to move files to their template directory? I hope that makes sense, if not please ask me to clarify further - I've not really been able to find anything in the codex, but maybe I'm looking in the wrong place.
Use `archive_template` filter in your plugin to override archive templates for a given post type, for example, `movies`: <?php function get_movies_archive_template( $archive_template ) { if ( is_post_type_archive ( 'movies' ) ) { $archive_template = dirname( __FILE__ ) . '/templates/movies-archive-template.php'; } return $archive_template; } add_filter( 'archive_template', 'get_movies_archive_template' ) ; See archive_template in Codex.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "custom post types, hooks" }
Disable permalink on custom post type I have created a custom post type, but I do not want it to have a permalink. By default, after entering the post title, it creates a permalink. I do not need them to be generated. From my reading, it is said that custom post type will have a permalink and there is no way of disabling it. Is there a way that I can prevent the ajax call that receives the permalink?
<?php add_filter('get_sample_permalink_html', 'my_hide_permalinks'); function my_hide_permalinks($in){ global $post; if($post->post_type == 'my_post_type') $out = preg_replace('~<div id="edit-slug-box".*</div>~Ui', '', $in); return $out; } This will remove: * Permalink itself * View Post button * Get Shortlink button If you want to remove permalink only, replace the line containing `preg_replace` with $out = preg_replace('~<span id="sample-permalink".*</span>~Ui', '', $in); ## UPDATE: `get_sample_permalink_html` has changed in version 4.4. Here is the updated and tested code: add_filter('get_sample_permalink_html', 'my_hide_permalinks', 10, 5); function my_hide_permalinks($return, $post_id, $new_title, $new_slug, $post) { if($post->post_type == 'my_post_type') { return ''; } return $return; }
stackexchange-wordpress
{ "answer_score": 7, "question_score": 6, "tags": "custom post types, permalinks, slug" }
Is there a good way to use CMS images with CSS I am building a responsive wordpress theme that allows for a custom banner image to be uploaded to each page. However, because of the responsive nature of the theme I need to set the images as background images using css to achieve the right effect. But, I do not want to throw random css styling into my html markup. Is there any to pull the image url from within the page template and drop it into a css file dynamically? I found an example of what I am looking to do here but without the slider functionality.: < It seems they are hard coding the images in the css file, but that is the visual effect I am going for. I just need to figure out how to tie this into the wordpress CMS. Any help would be greatly appreciated! Thank you!
The best way I found to solve this issue was to have PHP write the CSS styling I needed in-line. I know it is not best practice in terms of maintainability as it might be confusing to someone else coming into the project later on. However, it was a personal site so I will be the only one updating it. And it was the simplest solution to accomplish my needs. Hopefully there will be some kind of standards compliant solution to this in the future but for now this was the best I could come up with.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "images, css, cms, responsive" }
Redirect to a page if ancestors is empty I have this script to get the ancestors ID //Get root ID $post_id = $post->ID; $ancestors = get_post_ancestors($post_id); I would like to make a redirection if it's empty to a specific page ID so no one could be on a page with no ancestors. How ?
The simple answer is `wp_redirect($url);`, but it's a tricky beast to use as you can only use it before any page output. So basically, what you have would need to be right at the top of your page This example is making the assumption that you are using this in `single.php`? - $post_id = $post->ID; $ancestors = get_post_ancestors($post_id); if(empty($ancestors)) : // Not sure how $ancestors is returned, this assumes it's an array wp_redirect($url); exit; endif; See the Codex of `wp_redirect()` for more information.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "pages" }
How to throw the "We need ftp info" at a user I recently asked a question about an error I was getting for doing theme updates where the user did not have permission. I would like to write a credential check, much like how wordpress does theirs. essentially when you update WordPress you either have the worlds most insecure set up and it will just update when you click the button or it will do the smart thing and ask you for your ftp credentials. My theme is built on the same concept except I don't know how to ask you for your ftp credentials. Now I know there are wordpress functions that do the update of themes for you, except I check my version number in a custom way, I also get the zip from my hosting and I don't use wordpress theme repo for any of this, so the one quick fix function won't work. So my question is: **How do you write a custom credential check function that basically checks if you need ftp or not.**
simple function: protected function _cred_check(){ $aisis_file_system_structure = WP_Filesystem(); if($aisis_file_system_structure == false){ echo '<div class="alert"><strog>NOTE!</strong> We need your ftp creds before we continue!</div>'; return true; } return false; } then do: if($this->_cred_check()){ request_filesystem_credentials('your/link/to/your/update/page'); }else{ // your update stuff }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, updates, ftp" }
Show infos only to the author in the author.php I need to be able to show some informations only to the author in his profile viewable in the front end, for istance I need to add a text under the avatar that only the author, if logged in, can see. This text will inform them that they can change the avatar anytime by adding it in their profile page... I could also add some more details... Is there a way to achieve this? Thanks!
This one works for me... <?php global $current_user;<br> get_currentuserinfo(); if (is_user_logged_in() && (current_user_can('edit_others_posts') || $current_user->ID == $post->post_author) ) {my text goes here'); } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "author, profiles" }
Will I lose the pages I've created within a default WordPress theme when adding a new theme? Will I lose the pages I've created within the default WordPress theme when adding a new theme, or will a new theme accommodate the same structure and content already created? I'm new to WordPress and can't find the answer on Google.
WordPress is a content management system. Your content is saved in a database and is independent of whatever theme you choose to use to display that content. So, short answer: no.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "themes" }
Adding attributes to HTML tags in Contact Form 7 I want to validate a phone number and make sure the user enters all 10 digits. This can be done using the HTML5 pattern atribute: <input pattern=".{10,}" title="10 characters minimum"> How can I add this pattern attribute to my input tag in Contact Form 7 ? This what the mobile number input shortcode looks like: `[text* mobile id:field-mobile]`
You can use a `tel` shortcode to do this: [tel* id:field-mobile 10/10 "placeholder text"] This brings up the issue of browser support; if the browser in use does not support the `tel` input type, it will fall back to a plain text field. Source: < (halfway down the page)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin contact form 7" }
If contributor has published 2 or more posts then show otherwise hide If the contributor has already published two or more posts I show a maximum of 5 of them in the post-single.php using this code <?php echo do_shortcode('[latestbyauthor show="5"]'); ?> I have a text that introduces the code (other posts by the same author) This works fine if the contributor really has published 2 or more article but totally uselless if he has just one post. What I'm looking is a way to hide the text before the code by checking the total number of posts published, if 1 then hide and if 2 then show. Is it possible? Thanks!
Simpler than using the `$wpdb` class would be to use `count_user_posts()`. For instance: $min_posts = 2; if( count_user_posts( $post->post_author ) >= $min_posts ) { // display the user's posts } This assumes you're in The Loop, or at the very least that `$post` is a WordPress Post object. [above edited 2013-03-19 11:30 AM CDT] Note that if you're trying to count custom post types (and possibly pages, though I'm not sure), you'll need to use some `$wpdb` magic, but there's a code sample available at the Codex page for `count_user_posts()` (linked above).
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, author" }
WooCommerce custom query and paging: Not Found error I'm experiencing a problem with the following piece code: global $wp_query; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $filter_args['paged'] = $paged; $filter_args['posts_per_page'] = 2; $args = array_merge( $wp_query->query_vars, $filter_args ); query_posts( $args ); This code is located at **archive-prodcut.php** file, inside of my theme/woocommerce folder. It works correctly in order to show first 2 products and also to show WooCommerce pagination on the bottom. do_action( 'woocommerce_after_shop_loop' ); However, when I click on each of the pages I'm getting a "Not found" error. When I tried putting an echo on the top of the archive-prodcut.php file I realized that it doesn't load. The url looks like www.site.com/product-category/cat-name/page/2 Thanks in advance!
It has to do with the posts_per_page being 2 and the backend WordPress Settings being a greater value. If you set your WordPress Settings to 2 it will work. But you may not want all your pages to have two posts. In that case you can alter the query using the code in this answer, Pagination Throws 404 just for that archive page. Here is the code to put in your theme's function.php file. if( !is_admin() ){ add_action( 'pre_get_posts', 'set_per_page' ); } function set_per_page( $query ) { global $wp_the_query; if($query->is_post_type_archive('product')&&($query === $wp_the_query)){ $query->set( 'posts_per_page', 1); } return $query; } This changes the posts_per_page before running your query. Then when you get your posts it has your query with the dynamic variable posts_per_page. So if that number is 3, you will get your 3 products per page and no 404 error.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, theme development, pagination, woocommerce offtopic" }
Display all posts for taxonomy term across multiple custom post types I'm currently creating a website that uses several content types, (e.g. books, movies, shows) as well as a key taxonomy term (e.g. status, with values of owned and wishlist). My question is, in a custom template how do I create a loop that queries only one taxonomy value across multiple custom post types (i.e. a single list of all of the books, movies and shows on my wishlist.) The closest I could find was this post Using Query Posts With Multiple Post Types And A Taxonomy But unfortunately, I am having a hard time making it work as is in my template. And, ideally I'd prefer to use a wp_query instead of get_posts.
You can do this with an array of post types and a tax query for your term. The question you linked had special requirements as only one of the post types used the taxonomy. $args = array( 'post_type' => array( 'books', 'movies', 'shows' ), 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'status', 'field' => 'slug', 'terms' => 'wishlist' ) ) ); $wishlist = new WP_Query( $args );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom taxonomy, wp query, page template" }
Responsive Embeds using default embed shortcode Can someone explain how to make embed shortcode responsive? <
Originally posted by bainternet > take a look at this wordpress.org/extend/plugins/responsive-video-embeds Thats a perfect plugin.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "shortcode, embed, oembed" }
Canonicalization + Custom Post Types not working as expected I have an issue with Canonicalization where on Custom Post Types say for example: /custom-post-type/{post_id}/fake-post-name/ is loading up but not redirecting to : /custom-post-type/{post_id}/real-post-name/ It basically is allowing anything to be after post id and load that URL instead of redirecting to the correct one. Ive got my CPTs setup with custom rewrite rules using 'add_rewrite_rule' and associated my custom post links with 'post_type_link'. Have I missed a step somewhere? Many thanks. Just add to this the actual Canonical tag displays the correct url it should redirecting to. Will I need to add a filter to canonical_redirect and check the post_name of the CPT and see if it matches for the given post id and pass it back perhaps? Im not sure if this is needed/or way to fix it given the canonical in the is correct?
Think ive solved it and can't believe what it was! On my rewrite rule I had: add_rewrite_rule( 'custom-post-type/([0-9]+)/([^/]*)/?$', 'index.php?post_type=customposttype&p=$matches[1]', 'top' ); Adding in and passing the post_name for the custom post type got it to start redirecting. add_rewrite_rule( 'custom-post-type/([0-9]+)/([^/]*)/?$', 'index.php?post_type=customposttype&p=$matches[1]&customposttype=$matches[2]', 'top' ); Anycase for now its late and it seems to have started working :-) Now at least it forces the 301 from the fake post to the real post as was previously put in canonical meta. Don't know why but thought if the id was provided it would have worked without having to take in the post_name. Sometimes WP can really have you pulling your hair out!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, rewrite rules" }
Separate tags with semicolon Does anyone know if there is a way to change the callback function for a tag-like custom taxonomy so that it breaks terms after a semicolon instead of a comma? I realize I can rewrite the whole meta box, but I'd rather not if there's an easier way.
The tag delimiter is made translatable: $comma = _x( ',', 'tag delimiter' ); So this can be changed with a simple filter: add_filter( 'gettext_with_context', 't5_semicolon_tag_delimiter', 10, 4 ); function t5_semicolon_tag_delimiter( $translated, $text, $context, $domain ) { if ( 'default' !== $domain or 'tag delimiter' !== $context or ',' !== $text ) return $translated; return ';'; } Install as plugin; works without any side effects. What is tricky: changing the string _Separate tags with commas_ to say _semicolon_. You cannot use the same solution, because you don’t know the language of your users. Not sure how to handle that.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "custom taxonomy, metabox, wp admin" }
How to implement a JavaScript and CSS file for my WordPress homepage? I saw this Javascript feature tour file today, and was curious how I would go about implementing it on the homepage of a WordPress site. Ideally, I'd like to add it so it only shows up if and only if a user is on the homepage and have never been there before. I'm new to this though, and I'm not sure how to implement it. I found this previous question but I'm not sure how I would use it in this context. How would I use it on the homepage, and what files would I have to edit?
You would enqueue it, this is how Javascript is added to WordPress properly. This function would typically go in your theme's `functions.php` or in a plugin. function my_scripts_intro() { is_front_page(){ wp_enqueue_script( 'introjs','path to ..intro.js' ); wp_enqueue_style( 'introcss','path to ..intro.css' ); } } add_action( 'wp_enqueue_scripts', 'my_scripts_intro' ); To determine the state of the visitor you would probably want to use cookies. _ps. This questions is very common please use the search._
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "css, javascript" }
check if a file in a plugin folder exists from a locale installation I need to check if a file exist in my plugin dir: if (fileexists) { ... } else { ... } However, if in place of fileexists I use `file_exists(WP_PLUGIN_DIR . "/myplugin/myfile.ext")` it returns always true, whereas if I use `file_exists(plugins_url( "myfile.ext", __FILE__ ))` it returns always false, irrespective of the argument I use is a file that exists or not. I do not know if it is relevant to specify that I'm working in a locale environment. WP_PLUGIN_DIR returns `C:\Users\MyName\Documents\webserver\www\wordpress/wp-content/plugins/myplugin/myfile.ext` (and I see some slashes and some backslashes).
Use if( file_exists(plugin_dir_path(__FILE__) . 'myfile.ext') ) {} instead of if( file_exists( plugins_url( "myfile.ext", __FILE__ ) ) ) {} See plugin_dir_path in the Codex.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "plugins, local installation, plugins url, function exists" }
Custom Post Types relationships I have a custom post type for my videos. I need do related it with other post category. And i have 10 category Like this : Post Category - Video Category Tech Tech Marketing Marketing News News ..................... I want to do for this. I have a post Category Tech and I have custom post type Category(Taxonomy) Tech.. When I currently viewing Tech (Post) Category, How can i list (on sidebar) Tech videos?
From your question I gather your taxonomy term names match your category names. If this is the case and **always** will be the case, why not just query your custom post type by category slugs? Not sure what the exact name is, so I just made it `video`. // get category slug $cat = get_category( get_query_var( 'cat' ) ); $cat_slug = $cat->slug; // query your custom post type (video?), assuming // slugs match for your category name and taxonomy term name $my_args = array( 'post_type' => 'video', 'tax_query' => array( array( 'taxonomy' => 'your_taxonomy_name', 'field' => 'slug', 'terms' => $cat_slug ) ) ); $my_query = new WP_Query($my_args); while ($my_query->have_posts()) { $my_query->the_post(); // do the usual thing }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "custom post types, custom taxonomy, functions" }
wp_editor returns the shortcode and not render the output I built a plugin, and I would like to use shortcodes in the integrated wp_editor. I'm using echo to display the content of the wp_editor, so I think that's the problem why I can't use the shortcode. What's the method to do that? I'm using the following code for shortcode: add_shortcode('facebook', 'facebook'); function facebook($atts) { $options = get_option( 'social_options' ); return '<a class="socialmedia socialfacebook" href="'.$options["facebook"].'">Facebook</a>'; } ..and the following code to get the content of the wp_editor: <?php $footer = get_option('footer_options'); $footer_content = array($footer['footer_content_1'], $footer['footer_content_2']); foreach($footer_content as $content) { echo'<aside class="tab-content"> '.$content.' </aside>'; } ?>
try doing this <?php $footer = get_option('footer_options'); $footer_content = array($footer['footer_content_1'], $footer['footer_content_2']); foreach($footer_content as $content) { $content = apply_filters('the_content', $content); echo'<aside class="tab-content"> '.$content.' </aside>'; } ?> I once had the same issue and applying the content filter solved it
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "shortcode" }
wordpress url correction I have my wordpress site in a root folder like this "www.mysite/myblog/" so to get to the blog you have to go to "www.mysite/myblog/" I'm wanting to make it so that a user can go to "www.mysite" and it hits the blog. What do I need to do. All my images and everything have the ".../myblog/" path. I don't want to have to go through and correct all this because I'm sure that I'll mess something up. so basically wanting some help on how to do this. any advice would be great!
Copy the index.php and .htaccess file(Just copy it , do not move it ) from myblog directory to root directory. Open index.php file in any text editor and find the following code in the file. /** Loads the WordPress Environment and Template */ require('./wp-blog-header.php'); Replace it with the following code and save the file. /** Loads the WordPress Environment and Template */ require('./myblog/wp-blog-header.php'); Go to the General Settings page from settings section in the back end and change Site Address (URL) field to < as shown below in screenshot. !General Settings You can get more information on this settings from this page. You can access backend of site from this URL : < If you face any problem then let me know..
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "url rewriting, urls, site url, routing" }
replace current_page_item class in menu I want to replace below class with `active` class in menu: .current-menu-item and .current_page_item I am already using a menu callback which add a class `dropdown` in child menu: class foundation_navigation extends Walker_Nav_Menu { function start_lvl(&$output, $depth) { $indent = str_repeat("\t", $depth); $output .= "\n$indent<a href=\"#\" class=\"dropdown-toggle\"><span> </span></a><ul class=\"dropdown\">\n"; } function display_element( $element, &$children_elements, $max_depth, $depth=0, $args, &$output ) { $id_field = $this->db_fields['id']; if ( !empty( $children_elements[ $element->$id_field ] ) ) { $element->classes[] = 'has-dropdown'; } Walker_Nav_Menu::display_element( $element, $children_elements, $max_depth, $depth, $args, $output ); } }
Add this line at top of your display element function: add_filter('nav_menu_css_class', 'add_active_class_to_nav_menu'); Add this line at bottom of your display element function: remove_filter('nav_menu_css_class', 'add_active_class_to_nav_menu'); Add this function somewhere in your themes `functions.php`: function add_active_class_to_nav_menu($classes) { if (in_array('current-menu-item', $classes, true) || in_array('current_page_item', $classes, true)) { $classes = array_diff($classes, array('current-menu-item', 'current_page_item', 'active')); $classes[] = 'active'; } return $classes; }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "menus, callbacks" }
What should I put on my index.php? I had covered basically all the pages listed in the Template Hierarchy: 404_template archive_template author_template category_template tag_template taxonomy_template home_template front_page_template page_template search_template single_template attachment_template I'm using the front-page.php for my static front page and home.php for by blog index. So, with all that covered, what should I put into my index.php? Or can I leave it empty?
`index.php` is shown whenever wordpress doesn't find an appropriate page template. Generally people use it as the template for their site's blog. If you are absolutely sure that it will never be reached, you can leave it empty. Just make sure you have that file present, otherwise the theme will not work As a personal preference, when coming across this kind of situation, i just rename one of `archive.php` or `home.php` to `index.php` which will work just as well for almost all of the situations
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "templates, template hierarchy" }
How to set up a echo? My problem is that i don't know how to set up a echo I think. I need it to just wrap a if statement correctly around the code below Please Help...Thanks SO much <?php global $post; if(get_post_type($post->ID) == 'videos') { <video class="video" width="<?php echo get_field('width'); ?>" height="<?php echo get_field('height'); ?>" controls preload> <source src="<?php echo get_field('mp4'); ?>" media="only screen and (min-device-width: 960px)"></source> <source src="<?php echo get_field('iphone'); ?>" media="only screen and (max-device-width: 960px)"></source> <source src="<?php echo get_field('ogv'); ?>"></source> </video> <h2><?php the_title(); ?></h2> <?php echo get_field('content'); ?> } ?>
You can use get_post_type() function and pass current post id to it. global $post; if(get_post_type($post->ID) == 'videos') { // do this } _**Update_** <?php global $post; if(get_post_type($post->ID) == 'videos') { ?> <video class="video" width="<?php echo get_field('width'); ?>" height="<?php echo get_field('height'); ?>" controls preload> <source src="<?php echo get_field('mp4'); ?>" media="only screen and (min-device-width: 960px)"></source> <source src="<?php echo get_field('iphone'); ?>" media="only screen and (max-device-width: 960px)"></source> <source src="<?php echo get_field('ogv'); ?>"></source> </video> <h2><?php the_title(); ?></h2> <?php echo get_field('content'); ?> <?php } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -2, "tags": "custom post types, conditional content" }
Why can't I see my attachment page information for an image? I'm following a course where the tutor uploads an image to his media library. He adds attachment information. He then creates a new post and includes the image. When he clicks through, he gets the image with his attachment info below it. I however do not. I click through and I just get the image by itself. I'm sorry, I may be missing something obvious but I'm not sure what that is at this stage.
It sounds like you have selected `Media file` instead of `Attachment Page` in the `Attachment Display Settings`: !enter image description here
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, images" }
jQuery breaking my wordpress site I am including jQuery in my `header.php` file like this: <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script> But when doing this, it breaks my home page slider, it breaks my google maps ultimate plugins and some other things. When I exclude it, no custom jQuery runs on my page...only the slider works which must be using jQuery... So if jQuery is already running on my site (since I have jQuery easing in the theme etc..), why is custom jQuery code I add to my files in tags not working? However, when I include jQuery like I said above, my custom code runs, but it breaks other plugins... Why is that?
You _should not_ include jQuery manually. jQuery is included in WordPress by default, but isn't loaded on every page unless a plugin or theme requests it. This can be done using: add_action('wp_enqueue_scripts','my_scripts'); function my_scripts() { wp_enqueue_script('jquery'); } Here is function reference for `wp_enqueue_script` (the function) and `wp_enqueue_scripts` (the action hook). In addition to that, WordPress is using jQuery in no-conflict mode. This means you cannot use the normal `$()` function, but have to use `jQuery()` instead. For example, instead of this: $('selector').doSomething(); Use this: jQuery('selector').doSomething();
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "jquery" }
Adding define('WP_MEMORY_LIMIT', '64M'); by default? Before installing a big plugin I'm always scared of the blank page so I usually add define('WP_MEMORY_LIMIT', '64M'); to wp-config.php beforehand. I was thinking I could add it immediately after any WordPress install. Does this have potential downside?
The short answer is no. The long answer is "it is complicated". The memory limit is there to protect you from malfunctioning code eating all your available memory, something that will make your site less responsive for a while. (I tried to explain the issues around this setting here) This setting will not matter if your site doesn't handle a lot of traffic, or if you have a lot of available memory, otherwise you should ask yourself why do you use bloated plugins and look for alternatives. In any case you should try to set the lowest working limit and not go for 64M without trying lower limits first
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "memory" }
How to reset the plugins without deactivate the plugin function set_copyright_options() { delete_option('ptechsolcopy_notice'); delete_option('ptechsolcopy_reserved'); add_option('ptechsolcopy_notice','Copyright &copy;'); add_option('ptechsolcopy_reserved','All Rights Reserved'); } register_activation_hook(__FILE__, 'set_copyright_options'); Hi I use the code to make it plugin default while deactivate and activate plugin .But i need the options to make it using the reset button in the admin side to make it default without deactivate the plugin ?
You could make another function with will (re)set the default option values: function wpse_91307_set_option_defaults() { $options = array( 'ptechsolcopy_notice' => 'Copyright &copy;', 'ptechsolcopy_reserved' => 'All Rights Reserved' ); foreach ( $options as $option => $default_value ) { if ( ! get_option( $option ) ) { add_option( $option, $default_value ); } else { update_option( $option, $default_value ); } } } Then you could change your `set_copyright_options()` function into this: function set_copyright_options() { delete_option( 'ptechsolcopy_notice' ); delete_option( 'ptechsolcopy_reserved' ); wpse_91307_set_option_defaults( ); } When you hit the `reset` button, the only thing you have to do is execute the `wpse_91307_set_option_defaults()` function.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, functions" }
Using variable to display a page with a different stylesheet Is it possible to implement a different stylesheet for a page using a url variable, for example **Normal URL: www.example.com/page** Would use the normal stylesheet **Alternative URL: www.example.com/page?=alt** Would use an alternative stylesheet
if the url is `www.example.com/page?style=alt`, you can conditionally check the presence of `$_GET['style']` when you're including your styles. Add the following where you are enqueueing your syles(probably in `functions.php`): if(isset($_GET['style']) && $_GET['style']=='alt'){ wp_enqueue_script('alternate_style); else{ wp_enqueue_script('normal_style); }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "css, urls" }
Display term description on hover using get_the_term_list I have a custom taxonomy called services. Each service term will have a description. I am using get_the_term_list to show all the terms attached to each post. When hovering over the term link in the front-end I would like to show the term description just like WordPress does within the back-end when you hover over any link.
If you mean to add the description of the term as a title attribute which will show on hover then you can "fork" `get_the_term_list` function to a version that would add the title attribute, something like this should work: function get_terms_with_desc( $id = 0 , $taxonomy = 'post_tag', $before = '', $sep = '', $after = '' ){ $terms = get_the_terms( $id, $taxonomy ); if ( is_wp_error( $terms ) ) return $terms; if ( empty( $terms ) ) return false; foreach ( $terms as $term ) { $link = get_term_link( $term, $taxonomy ); if ( is_wp_error( $link ) ) return $link; $term_links[] = '<a href="' . esc_url( $link ) . '" rel="tag" title="'.esc_attr( $term->description ).'">' . $term->name . '</a>'; } $term_links = apply_filters( "term_links-$taxonomy", $term_links ); return $before . join( $sep, $term_links ) . $after; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, description, terms" }
Restrict admin access to certain pages for certain users As the title says, I'd like to restrict back-end access to certain pages for certain users. While doing a site with 45-50 pages, I realised it would be a much better user experience if the Page menu only listed those pages which the user should be able to change/update. I've tried the plugins below to no avail. Advanced access manager has the functionality but does not work/is buggy on 3.5.1. < < < < Code snippet in functions.php?
This code seems to work well for me (in functions.php): $user_id = get_current_user_id(); if ($user_id == 2) { add_filter( 'parse_query', 'exclude_pages_from_admin' ); } function exclude_pages_from_admin($query) { global $pagenow,$post_type; if (is_admin() && $pagenow=='edit.php' && $post_type =='page') { $query->query_vars['post__not_in'] = array('123','234','345'); } }
stackexchange-wordpress
{ "answer_score": 6, "question_score": 7, "tags": "pages, wp admin, user roles, user access" }
Post thumbnail not displaying in correct position I'm using the following as part of a shortcode I'm creating: $loop = new WP_Query(array('post_type' => 'client', 'posts_per_page' => $limit, 'orderby' => $orderby)); if($loop){ $preoutput = '<div class="outer">'; $postoutput = '</div>'; while ($loop->have_posts()){ $loop->the_post(); $output .= '<div class="box box-'.$columns.'"><h2>hello</h2>'.the_post_thumbnail(); $output .= '<div class="text"><h2 class="entry-title"><a href="'.get_permalink().'">'.get_the_title().'</a></h2>'.get_the_excerpt().'</div></div>'; $finaloutput = $preoutput . $output . $postoutput; } } However, the post thumbnail doesn't appear in the markup, it appears just at the top of the post - why would it do this?
You are using `the_post_thumbnail`, which directly outputs the thumbnail in an image tag. You need to use `get_the_post_thumbnail` instead, which returns the image.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "post thumbnails" }
Restrict access to certain dashboard pages based on user id I have a client who want's to be given admin access to the dashboard of the test installation of her website on my server. She hasn't paid me yet so I don't want her to be able to go into the themes menu, copy the theme code and run off without paying. So, is there a way that I can give her admin access while also blocking her from viewing the Appearance > Editor menu?
I would just disable the editor entirely. It is a dangerous tool anyway. I compare it to working on an airplane while its flying. Edit `wp-config.php` to add: define('DISALLOW_FILE_EDIT',true); You can reverse that by re-editing your `wp-config.php` and uploading over FTP (or maybe you have direct file access), as you should be doing anyway, but no one will be able to get to the editor to mess around with things.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "users, dashboard" }
Display one post in different formats conditionally I think I just coded myself into a corner. I am setting up a page with an image. The image is an imagemap with lots of links. When you click on the link, it opens a post in a colorbox. So far I have managed to get this part working using a combination of the Lightbox Plus and Post Template plugins. Unfortunately this involves assigning each post to a specific template. The template simply removes the title/image/menu. But this permanently alters the post display. I need to post to still show the full header if it is accessed through the normal menu or from a Google search. How can I display a post differently based on how it is accessed? OR - how can I insert just the post content into the colorbox window without using a custom page or post template?
A potential solution would be to first get rid of the Post Template plugin and just use the default `single.php` to render single post views. Then add a get variable onto the end of your imagemap links, so they're something like `domain.com/post-name/?view=lightbox` Then filter the `single_template` to load your lightbox view template when the GET var is detected: function wpa_lightbox_single( $template ){ if( isset( $_GET['view'] ) ) $template = locate_template( 'lightbox-view.php' ); return $template; } add_filter( 'single_template', 'wpa_lightbox_single' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "page template, post content" }
Order custom fields alphabetically I've been trying to order the custom fields alphabetically, but I can't get the ordered list I want... this is the code I'm using: <?php $vMarca = get_field('tienda_marcas' , false, false); $post_objects = get_posts(array( 'post__in' => $vMarca, 'order' => 'ASC' , 'orderby' => 'title' )); if($vMarca) { echo '<ul>' ; foreach($vMarca as $post_objects) { echo '<li>' . $post_objects . '</li>' ; } echo '</ul>' ; } ?> I need the custom fields to be ordered alphabetically.
It looks like you're trying to output the wrong stuff. You've ordered the `$post_objects`, not the `$vMarca`. Try using the `$post_objects` variable for your `if` and `foreach` statements thus: <?php $vMarca = get_field('tienda_marcas' , false, false); $post_objects = get_posts(array( 'post__in' => $vMarca, 'order' => 'ASC' , 'orderby' => 'title' )); if($post_objects) { echo '<ul>' ; foreach($post_objects as $post) { setup_postdata($post); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php the_content(); ?> } echo '</ul>' ; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, order" }
Wordpress Multisite local: wp-login.php refreshes on login Chrome Browser I just set up Wordpress Multisite on my local machine following this tutorial. When I try to login to the admin using Google Chrome, the page just refreshes. I've tried Firefox, and I'm able to login and use Wordpress Multisite normally and access the dashboard. I've tried clearing my cache, and using incognito mode in Google Chrome, to make sure that it wasn't a caching issue. Here are the steps I take to login: 1. I navigate to ` 2. I'm redirected to ` 3. I enter my username and password, then click 'Log in' 4. I'm redirected to ` I've also added to my wp-config.php as referenced here: define('WP_HOME',' define('WP_SITEURL',' Is there anything else I can try? I'd like to be able to use both Chrome and Firefox.
I solved my own problem. I installed WordPress MU Domain Mapping plugin, set the mapping my to home ip, 127.0.0.1, then added my site to domains with the domain name I wanted. The domain name in domains must match the site domain. Once all of that was done, I made sure the domain was also mapped in my hosts file. I hope this helps anyone else that runs into this issue.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "multisite, login, localhost, google chrome" }
How to filter posts by format and category via url? I figured out I can filter posts by format just by doing /type/{format} e.g. /type/gallery/ in the url. Looking for a way to filter by categories on top of this, something like /type/gallery/category/installation or /type/gallery/art. I've figured out the query, but I don't know how to handle the url bit: $galleryquery = wp_parse_args($query_string); $galleryquery['tax_query'] = array( array( 'taxonomy' => 'post_format', 'terms' => array('post-format-gallery'), 'field' => 'slug', ), array( 'taxonomy' => 'category', 'terms' => array('installation'), 'field' => 'slug', ), ); query_posts($galleryquery); Ideas? I'm guessing I have to intercept the permalink and somehow pass it to my query... Site is reachable here
I ended up with this: function when_rewrite_rules( $wp_rewrite ) { $newrules = array(); $new_rules['type/([^/]+)/category/([^/]+)/?$'] = 'index.php?post_format=$matches[1]&category_name=$matches[2]'; $wp_rewrite->rules = $new_rules + $wp_rewrite->rules; } add_filter('generate_rewrite_rules','when_rewrite_rules'); There is no need to add new query vars. You can get both taxonomies out of the box: categories are query-able with "?category_name=x" and post formats with "?post_format=x". Confusingly, post formats are a taxonomy, and **not** a custom post type, yet have the taxonomy of "type". E.g. you filter them like so: > mysite.com/type/gallery Seems like "/format/" would be a better taxonomy to avoid confusion with Custom Post Type.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "categories, permalinks, post formats" }
Editing the Backend Uploader So my boss wants me to edit the backend of his WP site so that he can add a video link from a site called vzaar, which hosts all of our content. I need to know where in the backend I can edit to allow this to happen. I dont need to know how to do it, just need to know what I'm looking for. Here is an image of where he wants the option !enter image description here
It's Post Meta Box / Custom Field. Try find it in functions files inside the THEME folder.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "admin, uploads" }
Calling a function from functions.php in header Been searching a lot for how to call a function in header.php where the function is in functions.php. How do I solve this? I have my function in functions.php like this: function testFunction() { echo "This is a test"; }
Simple! just call it `testFunction();` wherever you want between php tags. _But not a wp question_
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "functions" }
How do I rebind event after widget save I am writing a widget who's form elements have a click event attached to. I bind it using jQuery. However, after clicking `save`, the bindings gets lost. That is, clicking those elements doesn't trigger the function anymore. I tried using the `on()` jQuery method, as suggested here, but that doesn't help: var buttonsHolder=jQuery('#widgets-right .icon_buttons'); // save the array of big icons, for later reference, and assign them the click event var buttons=buttonsHolder.children('input'); buttons.on("click",function(){ openPanel(jQuery(this),jQuery(this).index()); }); I could put my `js` code inside the widget form, as suggested here. That does solve the problem, but I really prefer to keep my `js` code separated. What do I need to do in order to keep the click event of those elements working even after the `save` button is clicked?
Because the input box is getting rebuilt (or the entire form), I followed advice given me elsewhere, and instead of binding on() to an input box, I bind it higher up and use event delegation: jQuery('#widgets-right').on('click','.icon_buttons input',function(){ openPanel(jQuery(this),jQuery(this).index()); }); I still put some js variable declarations inside the widget form, but that's only for convenience, and it's only a few lines of code, so I don't mind it too much.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 4, "tags": "widgets, jquery" }
My template won't apply, theme still fallback to index.php I have a CPT that I want to list the post in the frontend of my website, so i've created a page that I assigned a template so i'll be able to modify the way it look. Here is my template declaration : /* Template Name: Book's author */ Further I have my loop. In my wp-admin under page i've changed the template of my page to Book's author, but on the front-end it's still showing index.php What I don't understand, is that list the book's author, but with my index.php ! Thanks for your help. John.
What you are doing, if I understand correctly, is overly complicated, is a bit of a hack around the Core functionality of CPTs, and is probably less efficient than letting the Core handle it. WordPress will generate an index listing for your post type if you register it appropriately. That is, if you register it with `'public' => true` as you can see in this example from the Codex: function codex_custom_init() { $args = array( 'public' => true, 'label' => 'Books' ); register_post_type( 'book', $args ); } add_action( 'init', 'codex_custom_init' ); WordPress will then use these two templates, if present, to display the content: > * single posts of a custom post type will use single-{post_type}.php > * and their archives will use archive-{post_type}.php > > > <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, templates" }
How to setup different permlalinks for posts and pages? I'd like to setup: www.mydomain.com/a-page/ www.mydomain.com/blog/category_name/ www.mydomain.com/blog/category_name/post_name/ www.mydomain.com/custom_post/post_name/ How would I do it? Thanks in advance
In Options » Permalinks just add a base for post permastruct. Ex: `/blog/%postname%/`. Make sure that your custom post types are registered with `'with_front'` => `false` in rewrite argument. See: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, posts, permalinks, pages" }
Two different archive pages showing the same content I'm trying to use Query Multiple Taxonomies with Ajax. It works with Ajax and it works without it. But unfortunately not at the same time. Basically I need an Archive page to show only the posts of my custom post type "filme" (to insert it with ajax) and another Archive page with the menue, header etc. to use it with the basic Query Multiple Taxonomies, if Javascript is disabled. I've already tried to create a page and an empty custom post archive and "convert it" by using a function hooked to 'pre_get_posts()' but without any luck. The problem is Query Multiple Taxonomies seems to need the main-query to work. I hope it's clear what I'm trying to do, It's a bit comprehensive. EDIT: I've tried to load the archive-page inside itself with AJAX too, but it was incredible slow, so I guess it's not the right way to do it.
Finally I found a solution. Maybe it could help someone else. In my archive-filme.php I just used the basic loop: <?php if ( have_posts() ) : ?> <?php while ( have_posts() ) : the_post(); get_template_part( 'content', get_post_format() ); endwhile; ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> Now I use a page with an custom-template. In the content-div I placed `include get_bloginfo( 'url' )'/filme/?' . urldecode( $_SERVER["QUERY_STRING"] )` The query_string, cause I need to pass some GET-variables to the page. For the ajax solution I used the checkboxes provided by Query Multiple Taxonomies and loaded the archive-filme.php into my content-div, again with the get variables. I'm really not sure if this weird text can help someone, but I hope so.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, ajax, archive template" }
Media Manager 3.5 custom options I need to change the values and hide some of the default media manager Attachment Display settings. Like setting the "Link to" to none, and hiding it so that the registered user can't change it. It would also be nice if I could delete the "size" option "original size from the dropdown. I googled a bit and it seems to be very tricky to make changes to the new media manager, therefore I found no solution so far.. I hope you can help me with some insights. Thank you!
I got the solution. I used the following script: Wordpress Media Manager 3.5 - default link to and altered it to my needs with this modification: (function() { var _AttachmentDisplay = wp.media.view.Settings.AttachmentDisplay; wp.media.view.Settings.AttachmentDisplay = _AttachmentDisplay.extend({ render: function() { _AttachmentDisplay.prototype.render.apply(this, arguments); this.$el.find('select.link-to').val('none'); this.model.set('link', 'none'); this.updateLinkTo(); this.$el.find('select.link-to').parent('label').hide(); this.$el.find('select.size option[value=full]').hide(); this.model.set('size', 'medium'); this.updateLinkTo(); } }); })();
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "media library, media settings" }
Disable "quick edit" only for non admin in functions.php I have this in my functions.php function remove_quick_edit( $actions ) { unset($actions['inline hide-if-no-js']); return $actions; } add_filter('post_row_actions','remove_quick_edit',10,1); to remove the quick edit link in the backend when scrolling the list of published posts. It works like a charm but it disable it even for the admin role. Is it possible to keep it showing only for the admin while still diabling for the rest? Thanks! **SOLVED thanks to jfacemyer!** This is the full code to add in functions.php function remove_quick_edit( $actions ) { unset($actions['inline hide-if-no-js']); return $actions; } if ( ! current_user_can('manage_options') ) { add_filter('post_row_actions','remove_quick_edit',10,1); }
Use `current_user_can` to wrap the `add_filter` call: if ( current_user_can('manage_options') ) { } else { add_filter('post_row_actions','remove_quick_edit',10,1); } `manage_options` is an Admin capability. If the current user can do it, he's an admin (on a vanilla WP installation). See: < and <
stackexchange-wordpress
{ "answer_score": 12, "question_score": 16, "tags": "quick edit" }
the_posts hook, which set of posts? I want to modify search results. Currently I hook to the_posts and check wp_query->is_search to determine if I am looking at the search results page. However, I noticed that the_posts is executed not only on the search results, but also on any excerpt list on the page (such as a listing of news items in the footer of the page.) How can I tell which the_posts call is which? Should I assume it's the 'first' one? or is there a better way?
I'd say it's perfectly fine to do it the way you're doing it now, that is function my_the_posts($posts, $query = false) { if( is_search() ){ // do your thing here } return $posts; } add_filter( 'the_posts', 'my_the_posts' ); Don't worry about those excerpts in the footer, even though they may be part of the search page (which the footer will be, obviously), they're part of a different query and so will not pass the `is_search()` test.
stackexchange-wordpress
{ "answer_score": 6, "question_score": 2, "tags": "plugins, hooks" }
Adding attachment file name to email link I'm doing up a photography site where each post is a photo project, and each post attachment will be displayed on its own attachment page (linked to from the main post page). On the attachment page, I want to give an email link, below the image. At the moment, the code is something like this: `<a href="mailto:[email protected]?Subject=Image: <?php the_title(); ?> - [FILE NAME HERE]">Get in touch about this image</a>` I want the subject of the email to include the _file name_ of the attachment (not title, not meta info, not attachment page URL). Is this possible? If so, how would I do it? Thanks.
You can get the original attachment filename via `wp_get_attachment_url`: echo basename( wp_get_attachment_url( $post->ID ) ); or in the form of the example you provided: <a href="mailto:[email protected]?Subject=Image: <?php the_title(); ?> - <?php echo basename( wp_get_attachment_url( $post->ID ) ); ?>">Get in touch about this image</a>
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "attachments, email" }
Allow Profile HTML for select users I know there are a ton of post out there about how to allow html in profiles. Most of these warn about the security risk of doing so. My thinking is there has to be a way to only allow users to use html for certain users. I tried this but It doesn't work. I think it's because you can't remove a filter from inside a filter. Any help would be awesome. add_action('edit user profile update', 'nifty_strip_html'); function nifty_strip_html($user_id) { if ($user_id == 2){ //if user id is 2 then allow html remove_filter('pre_user_description', 'wp_filter_kses'); } else{ return; //keep the filtered html } }
You can hook on an early action and apply the filter for your use case: add_action( 'load-profile.php', 'allow_profile_html_wpse_91564' ); function allow_profile_html_wpse_91564() { global $current_user; if( '2' == $current_user->ID ) remove_filter('pre_user_description', 'wp_filter_kses'); } The hook **`load-$pagenow`** runs in all default admin pages (i.e., not added by a third party), and it's declared in the file `/wp-admin/admin.php`. `$pagenow` is the PHP page running at a given moment. So, to target the page `/wp-admin/user-edit.php?user_id=2`, another hook is needed and also another conditional checking: add_action( 'load-user-edit.php', 'callback_function' ); function allow_user_html_wpse_91564() { if( isset( $_REQUEST['user_id'] ) && '2' == $_REQUEST['user_id'] ) remove_filter( 'pre_user_description', 'wp_filter_kses' ); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 3, "tags": "filters, security, profiles" }
get all sub categories without specify any category I have 2 levels of categories ( one sub-category only. No `sub-sub` category ). I need to get all sub categories without parent category. (I don't want to specify any parent category.) Example: p_cat1 s_cat1 s_cat2 p_cat4 p_cat3 s_cat4 s_cat5 s_cat7 from here, I need s_cat1 s_cat2 s_cat4 s_cat5 s_cat7 And, I need there to be a URL for each of those sub-categories. I want to give `<a>` for each subcategory. How do I do that?
You could use `get_categories()`. > Returns an array of category objects matching the query parameters. > > Arguments are pretty much the same as wp_list_categories and can be passed as either array or in query syntax. // Fetch parent categories $parent_categories = get_categories( 'parent=0' ); foreach ( $parent_categories as $parent_category ) { // Fetch child categories $args = array( 'parent' => $parent_category->term_id ); $categories = get_categories( $args ); foreach ( $categories as $category ) { printf( '<div>%s</div>', $category->name ); } } This is a very simple example of the code without extra parameters like `hide_empty`, `type` etc.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories" }
Redirect page to first post in custom post type I have a page, let's called it "Artists", that displays a list of posts in a custom post type, again "artists". How can I redirect pepole who visit the Artists page to the first post in the "artists" post type?
This is assuming that your page 'Artists' has an ID of 10, so change that as necessary. You can also amend the `$args` array as you wish to better suit your needs, if required. Here is the Codex for `WP_Query`, which shows that parameters that you can use. Finally, this needs to go right at the top of your page (before any output), otherwise you'll get an error about header information having already been output. if(is_page(10)) : $args = array( 'posts_per_page' => 1, 'post_type' => 'artists' ); /** Get the posts that match and grab the URL of the first post */ $posts = get_posts($args); $redirect_url = get_permalink($posts[0]->ID); /** Redirect to the specified URL */ wp_redirect($redirect_url); exit; endif;
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom post types, redirect" }
BuddyPress: What is the use of is_default_option field in wp_bp_xprofile_fields table? In BuddyPress, What is the use of is_default_option field in wp_bp_xprofile_fields table?
This is one of the things you won't find in the docs, but only in the source. The source code contains only one usage of this variable. This is in bp-xprofile-template.php line 493. // First, check to see whether the user-entered value matches if ( in_array( $allowed_options, (array) $option_values ) ) { $selected = ' selected="selected"'; } // Then, if the user has not provided a value, check for defaults if ( !is_array( $original_option_values ) && empty( $option_values ) && $options[$k]->is_default_option ) { $selected = ' selected="selected"'; } As you can see, it is used to pre-select an option in the case the user hasn't supplied a value yet.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 1, "tags": "buddypress" }
nonces in custom oop plugin How to use the `check_admin_referer` method with oop? If I use as it follows the function can not be called: class MyClass{ function __construct(){ if( isset($_POST['my_nonce_field']) && check_admin_referer('my_nonce_action', 'my_nonce_field')){ $this->update_item(); } } } $test = new MyClass(); The above leads to the following error message: Call to undefined function check_admin_referer()
`check_admin_referer` is a pluggable function which means it is defined after plugins are loaded so call your constructor or instantiate the object after or using `plugins_loaded` action hook. ex: class MyClass{ function __construct(){ if( isset($_POST['my_nonce_field']) && check_admin_referer('my_nonce_action', 'my_nonce_field')) $this->update_item(); } } add_action('plugins_loaded','newobj'); function newobj(){ $myclass = new MyClass; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "plugins, plugin development" }
How do I rename a category in the menu bar only? I'm surprised this hasn't been asked before, but I couldn't find it via search. I'd like to do: Full Category Name -> Text in Menu Bar Exercise Tips -> Tips Reviews of Exercise Equipment -> Reviews Industry News -> News So the menu bar looks like: `Tips | Reviews | News` But when you're in the actual category, it shows the full title. What I need is a "Navigation Name" field in the category setup screen. Is there a way to do this, perhaps with a plugin?
Actually this is pretty simple and straightforward: when you set up your menu (under **Appearance > Menu** ) you will find out you can add _Categories_ there. After adding them, click on the down-pointing arrow on the right of the navigation element, it will give you the possibility to change the _Label_ , while keeping the _Original_ visible to you, so you remember what it actually refers to. In order to make the Menu you just created appear in your theme, you have to look at the `wp_nav_menu` function. You can take to approaches to display your menu: 1. Either you **register your menu location** in your theme, and then fill up the menu in your dashboard. In this case you will use the `$theme_location` argument of the function. 2. Or you take the opposite direction: create a menu in your dashboard and use it in your theme, using the `$menu` argument, which accepts `id`, `slug` or `name`.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, categories" }
Why can't a WordPress network (multisite) in it's own folder use subdomains? If I'm setting up a brand new multisite installation with WordPress in it's own folder (say /wp/) why can't I configure the network to use subdomains instead of subfolders? Currently, if I try to setup the network with the WordPress core in it's own folder I'm not allowed to choose between a subdomain-based or sub-folder based network. I must use sub-folders. What are the technical reasons for this? I've scoured trac and Google for an answer to this question with no luck. A more detailed explanation than what is provided on < or < would be greatly appreciated. Thanks!
I figured it out. The fact is, a network can use subdomains or subfolders, even when WordPress is installed in it's own folder **as long as the main site's HOME URL is set to domain.com and not to the sub folder location**. **Here's an example:** I setup a clean install of WordPress using Mark Jaquith's WordPress Skeleton which places WordPress's core files at domain.com/wp/. However, when trying to run the initial install script, WordPress chokes on its own redirects. (It keeps trying to load domain.com/wp-admin/install.php instead of domain.com/wp/wp-admin/install.php. Maybe a bug report for another day?) To get around that, I manually typed in the correct path to the install script (domain.com/wp/wp-admin/network.php). By doing this, WordPress sets the HOME URL to `domain.com/wp` instead of just `domain.com`. (Which makes sense, really.) By changing the site's HOME URL to `domain.com`, I am now able to choose a subdomain or subfolder installation when setting up the multisite.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "multisite, subdomains" }
add_action on a specific page I found this script Wordpress Media Manager 3.5 - default link to and it works fine for me. But my problem is, that I have a custom wp_editor on the front end where I want it to work, but I can't find a way to activate it on this site.. Here is the code: add_action( 'load-post.php', 'wpse8170_media_popup_init' ); add_action( 'load-post-new.php', 'wpse8170_media_popup_init' ); which works fine in the wp backend media manager, but not in my custom wp_editor. The URL to the wp_editor is: ` And the page id is 360.. Do you have any idea how I could use the add_action on this page? Thank you!
In your theme's _functions.php_ file, or the like: add_action( 'your-custom-action', 'wpse8170_media_popup_init' ); In the page template used for the page in question: do_action( 'your-custom-action' );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "actions" }