INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
Disable auto hide of the login form on Woocommerce's checkout page I'm in the process of trying to style a checkout page in Woocommerce and need the login form to be visible all the time when the user is not logged in rather than initially hidden then toggled on and off. What I have discovered is that the login form is generated by Woocommerce's `woocommerce_login_form` function and then hidden on document load by `checkout.js` on line 83 `$('p.password, form.login, .checkout_coupon, div.shipping_address').hide();`. Since this is a core file of Woocommerce and will be overwritten on update I don't want to edit that one line of code but I cannot seem to find any better way of preventing it from hiding the login form. Since this occurs after my own Javascript files I cannot even simply show the form again. Are there any better ways I can try and prevent the form from being hidden?
If you use a custom theme, you can create your own `shop/form-login.php`, and Woocommerce will use that. Then you can change the class names or add custom JavaScript. Upgrades for the core are still possible.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery, plugins" }
Mamp pro permalink issues. Pages keep reverting to index.php So I pulled a site down to my local machine to do some work on it. Copied the files, find/replace on the database to update the url, added a host. Everything worked fine until I changed the permalink settings. Now every page uses the index.php template in my theme folder instead of the page.php. Of course it works fine when you use the default settings, but not any others that require htaccess directives. I have tried everything I can think of including changing the AllowOverride None to All in the httpd.conf. Anyone else have any ideas? I am at a complete and frustrated loss. Edit: Here is my htaccess file: # BEGIN WordPress <IfModule mod_rewrite.c> RewriteEngine On RewriteBase / RewriteRule ^index\.php$ - [L] RewriteCond %{REQUEST_FILENAME} !-f RewriteCond %{REQUEST_FILENAME} !-d RewriteRule . /index.php [L] </IfModule> # END WordPress
Okay. I got it working now. Turns out it was one or both of my custom taxonomies I had added on with my custom content type. I knew it had to do with my custom content types or taxonomies because, if I took them out and reset the permalinks, everything worked fine. The names for these two taxonomies where type and year. I simply changed the names to media_type and media_year and everything is humming along just fine now. I guess Wordpress uses certain names and you have to be careful what you use because it can break everything.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "theme development, functions, permalinks" }
Exclude category I want to exclude a category from showing in a function, but cannot figure out how to do it for my specific code as below. I want to make it so that any post that is in the "featured" category, does not display - but all other posts do. $args = array( 'posts_per_page' => 4, 'category_name' => 'featured'); $last_5_posts_query = new WP_Query( $args ); while($last_5_posts_query->have_posts()) : I just cannot figure out where or how to add the exclude operator, which i assume is by adding a - somewhere. Thanks.
To exclude a category, you need to know its ID. You can then exclude it like this (please not the minus before the ID): $args = array( 'posts_per_page' => 4, 'cat' => -the_category_id_to_put_in); The WP Query class reference has more information if you need it: <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 0, "tags": "php, functions" }
Placeholders in Jetpack Contact Form In HTML5 you can use placeholders in your forms to name fields or guide the users. I would like to use this in Jetpack forms but it seems it doesn't support it. You can add a default value like `default="Your name"`, but the user will then have to delete this text before writing. With placeholders the field is cleared when you start writing. Any workarounds in JavaScript maybe?
You can do this by means of jQuery (which means this is rather a jQuery/JavaScript question). Put the following in one of your (already included) JS files, or create a new JS file and enqueue it, or hard-code it in between `<script>...</script>` tags: jQuery(document).ready(function($) { $('#my-form-field').attr('placeholder', 'Please enter your name...'); });
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "forms, plugin jetpack" }
month name translation I use the birdtips theme and it formats the post date as $birdtips_posted = date(__('Y. F j.', 'birdtips'), strtotime(get_the_time("Y-m-d"))); where Y. F j. is already rewritten to reflect my language. As far as I understand, __ is the translation function, but how can I tell Wordpress that I use Hungarian, and will it translate month names automatically, or I should give the names in a .po file?
Use `date_i18n()`: date_i18n( 'Y. F j.', strtotime( get_the_time( "Y-m-d" ) ) ); From the function’s description: > Retrieve the date in localized format, based on timestamp. > > If the locale specifies the locale month and weekday, then the locale will take over the format for the date. If it isn't, then the date format string will be used instead. A timestamp is a UNIX timestamp, a single number, for example 1366784091.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 0, "tags": "date, translation" }
Add user settings to specific roles Is it possible to do this? I already know about get current_user_can(), which does not work like I need. I'd like to be able to use an array if there are multiple roles. // Check roles to only add fields to necessary users function check_role( $user ) { $user_role = get_user_role($user->ID); if($user_role == 'author') { return true; } else { return false; } } add_action('show_user_profile', 'check_role'); add_action('edit_user_profile', 'check_role'); if(check_role()) { add_action('show_user_profile', 'add_user_fields'); add_action('edit_user_profile', 'add_user_fields'); add_action( 'personal_options_update', 'save_user_fields' ); add_action( 'edit_user_profile_update', 'save_user_fields' ); }
On the profile page exists a global variable `$profileuser`. The member `$profileuser->roles` is an array of all roles for that user. <?php # -*- coding: utf-8 -*- // Plugin Name: personal_options add_action( 'personal_options', 'print_user_roles'); function print_user_roles() { global $profileuser; print '<pre>$profileuser->roles = ' . htmlspecialchars( var_export( $profileuser->roles, TRUE ), ENT_QUOTES, 'utf-8', FALSE ) . '</pre>'; } Output: $profileuser->roles = array ( 0 => 'administrator', 1 => 'editor', ) Use this list to compare the roles.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "php, user roles, conditional content" }
Is there an action for when permalinks are rebuilt? In my plugin, I have a list of titles and permalinks in the options table. It's updated every time my custom post type is saved. Since I'm saving permalinks the option data can become bad if the user changes their permalink structure. I need a action that I can hook into that happens whenever the permalink structure is updated. Is there one?
The action is `update_option_permalink_structure`. You get the old and the new value as parameters. add_action( 'update_option_permalink_structure' , 'my_custom_function', 10, 2 ); function my_custom_function( $oldvalue, $_newvalue ) { // do something } There are also the actions `update_option_category_base` and `update_option_tag_base`.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 4, "tags": "permalinks, hooks, actions" }
Disable widgets on specific posts I run a horror related blog. Google is upset with me for displaying adsense in a sidebar widget for one specific post number (4603) that contains an article about an 18+ topic. How can I disable the widgets for a specific id?
I'd recommend the plugin Widget Logic to handle all your needs. You can just add logical tags to the individual widgets on the sidebar. <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "widgets, filters, sidebar, adsense" }
contact 7 plugin stops some pages from working properly I started to use contact 7 plugin and I'm having a slider and some effects on other images when i activate the plugin they stop working this is the web page I don't understand what it do! if it stops the javascript or css files but I searched in the files if it has the same names and stopping them from working but it have different names i tried to add this code to function.php so i could add jQuery by the right way but it gave me server error jQuery(document).ready(function(){ function my_init() { if (!is_admin()) { // comment out the next two lines to load the local copy of jQuery wp_deregister_script('jquery'); wp_register_script('jquery', ' false, '1.3.2'); wp_enqueue_script('jquery'); } } add_action('init', 'my_init'); });
i found the solution i just added all scripts together
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, css, javascript" }
Screen options on a different computer Is it possible to keep dashboard screen options (for instance, not showing custom fields) across computers?
They do work across many computers, as long as you're logged in with the same username. If they don't, try clearing your browser cache.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "screen options" }
Echo Messages By Checking current_time() Before asking for help I would like to clarify that I don't have advanced skills on PHP. What I want to achieve is to display different messages for every period of time that I set **_(I need this to LOOP every day)_**. After reading this -> < I tried to check: $my_time = current_time('mysql'); if ($my_time >= 14 && $my_time <= 16) { echo 'Do your homework'; } else if ($my_time > 14 && $my_time <= 18) { echo 'Clean up the house'; } else if ($my_time > 18 && $my_time <= 20) { echo 'Go Shopping'; . . . . . } else { echo 'Lets start over!' } Where 14, 16, 18, 20 is the time (24hour format). However this did not work. When I echo current_time('mysql'), it returns the date and the time so even if it could work, it wouldn't loop because of the date, right? Thanks in advance.
You would just need to format the time that is returned by current_time() with the php date() function like this: $my_time = date('G', current_time('timestamp')); The param 'G' tells the function you just want to have the hour part (0 to 23) of the date. Have a look here: <
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "date time" }
Make this jQuery toggle snippet target each list item individually I'm currently using this little jQuery toggle snippet to show/hide child categories using the wp_list_categories function; $('.sidebar ul.children').hide(); // Start by hiding child categories $(".sidebar li.parent-item").hover(function () { $(".sidebar ul.children").slideToggle("slow"); But currently hovering over any list item with the class `parent-item` makes every child menu toggle. Is there a way to make it work only on the list item that is hovered over?
Use $(".sidebar li.parent-item").hover(function () { $(this).find("ul.children").slideToggle("slow"); });
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "jquery, categories" }
W3 Total Cache benefits without using plugin? W3 Total Cache isn't compatible with WPTouch. Is there a way to get the benefits of W3 Total Cache without using the plugin?
Did you already try adding all the mobile user agents to the "Rejected user agents" list in w3tc? I use this list for this purpose (not created by me and certainly not complete but enough for my purpose): iphone ipod ipad aspen incognito webmate android dream cupcake froyo blackberry9500 blackberry9520 blackberry9530 blackberry9550 blackberry9800 webos s8000 bada That's a common workaround that almost anyone uses to have w3tc and WPTouch working together. * ** _Edit_ *** You wild need to reformat the list to have one per line to insert it in w3tc.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugin w3 total cache, cache, plugin wptouch" }
How to query wp_postmeta table for any specific meta_value? I am using following code in the theme files to get some output from the DB: <?php $querystr = "SELECT DISTINCT meta_value FROM $wpdb->wp_postmeta WHERE 'meta_key' LIKE 'movie_name' ORDER BY meta_value ASC"; $movie_names = $wpdb->get_results($querystr, OBJECT); echo sizeof($movie_names); ?> <ul> <?php foreach ( $movie_names as $movie_name ){ ?> <li><?php echo $movie_name->meta_value; ?> </li> <?php } ?> </ul> Above code's result is "0" at the frontend. But when I am running the same query i.e. SELECT DISTINCT meta_value FROM wp_postmeta WHERE 'meta_key' LIKE 'movie_name' ORDER BY meta_value ASC in DB then it's returning 6 rows. Please help me in finding the problem in the code.
`$wpdb->wp_postmeta` is wrong. Always use just `$wpdb->postmeta` – without further prefixes. So... global $wpdb; $querystr = " SELECT DISTINCT meta_value FROM $wpdb->postmeta WHERE meta_key LIKE 'movie_name' ORDER BY meta_value ASC "; $movie_names = $wpdb->get_results( $querystr, OBJECT ); if ( ! $movie_names ) { $wpdb->print_error(); // Get the last error message for debugging } else { // Do something awesome with the movies }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "meta query" }
Internet Explorer seperating lists differently in Twitter Widget Pro than all other browsers I am having some trouble with the Twitter Widget Pro Plugin - for some reason in internet explorer if the first tweet has a link, it will make the link its own list item and add a bunch of extra padding above it. I have tried using different twitter feeds, changing around the widget settings but haven't had any luck figuring out what might be causing this. Any ideas would be much appreciated. Here is the link to see it - < Thanks!
The mark-up surrounding the widget is malformed. IE isn't handling this as well as other browsers. <h1>Twitter</h1><h2><a href=" <div><h2><span class='twitterwidget twitterwidget-title'> Note the opening anchor tag before "Follow". This is never closed.
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugins, list, twitter, browser compatibility" }
How do I use inline SVG in WordPress I am trying to put in an SVG inside my post, but it seems WordPress removes the content. e.g. <svg xmlns=" version="1.1" height="190"> <polygon points="100,10 40,180 190,60 10,60 160,180" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;"> </svg> Gets rendered to <svg xmlns=" version="1.1" height="190"></svg> Is it possible to do this without a plugin like raw_plugin
According to this post, if you put all the svg block in **one line** , it will be rendered. This should work: <svg xmlns=" version="1.1" height="190"> <polygon points="100,10 40,180 190,60 10,60 160,180" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;"> </svg>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "posts" }
Is there a limit to the number of options you can store in one settings field of wp_options? I have a theme with an options page. And on that page there are 1083 options. I've noticed that the last 13 are not saving. They _were_ saving at one point, but after I added new options above them, they stopped working. I suspected that I may have run up against some kind of option limit or limit on the array so to test that, I removed 7 options above the last 13 and sure enough 7 of them saved after that. I've been trying to find information about this but have been unable to do so. Does anyone know if you can only have 1070 options in one settings field? It's not an issue with the database longtext memory limit. These are simple 1's and 0's and hex color values and other CSS type stuff. The export of the field is only 33k.
The limit is probably not WordPress specific, but caused by PHP. `max_input_vars` might be set to 1000, so not all fields might reach WordPress. You can store 4,294,967,295 or 4GB (232 – 1) characters in one option, so I don’t think this is your problem. If it is, you should consider a separate table.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "options, settings api" }
Can't Auto-Update, but permissions are good? Normally wordpress will auto-update fine without a fuss, but now throws the old ftp credentials form up in my grill. I haven't changed any permissions in between updates, even running `chmod` and `chown` recursively to be sure, but still wordpress wants the ftp. Out of the few wordpress installations i run, this is the only one playing hard-to-update. I'll resort to a manual update if i have to and hope it fixes itself, but it'd be great to know what's the beef.
If you're pretty sure about that the file owner of wordpress folder is as same as that one who runs apache. (use `ps aux|grep 'httpd'` or `ps aux|grep 'apache'`) Here is a **lousy** solution for you: function force_use_direct_fs($method,$args){ if($method != 'direct') $method = 'direct'; return $method; } add_filter('filesystem_method','force_use_direct_fs',10,2); **Why Would Wordpress Request FTP Credentials** wp-admin/includes/file.php In function `get_filesystem_method` Wordpress will determine the proper filesystem method by comparing the file owner of a temporary file to the user who runs the web server. Here is the code: if( getmyuid() == @fileowner($temp_file_name) ) $method = 'direct'; That's why I still think the cause is the wrong file owner permission.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "customization, automatic updates" }
Get Product id from order id in Woocommerce I am having trouble with Woocommerce product details and order details relationship. I'm not able to find the product ID of a related order ID on the _View Orders_ page of the Woocommerce theme. I simply want to get the product content and permalink etc on _View Orders_ page. I tried searching in `wp_postmeta` but had no luck.
## WooCommerce 3.0+ you can get the order items of an order by $order = wc_get_order( $order_id ); $items = $order->get_items(); then if you loop through the items, you can get all the relevant data: foreach ( $items as $item ) { $product_name = $item->get_name(); $product_id = $item->get_product_id(); $product_variation_id = $item->get_variation_id(); } a good tip is to check how the admin order pages get the data, you'll find many answers there! ## Pre-WooCommerce 3.0 $order = new WC_Order( $order_id ); $items = $order->get_items(); foreach ( $items as $item ) { $product_name = $item['name']; $product_id = $item['product_id']; $product_variation_id = $item['variation_id']; }
stackexchange-wordpress
{ "answer_score": 91, "question_score": 44, "tags": "plugins" }
How to show a under construction page for a domain but still be able to work on index.php? I installed a WordPress for a domain name. When I use this domain name will point to `index.php` in my template. I want show a under construction page for this domain name, but the other hand I still want work on `index.php` in my template.
You can filter `template_include` and include a special file for users who are not logged in: /* Plugin Name: T5 Under Construction */ add_filter( 'template_include', 't5_uc_template' ); function t5_uc_template( $template ) { $uc_template = dirname( __FILE__ ) . '/under-construction.php'; if ( ! is_user_logged_in() ) return $uc_template; if ( ! current_user_can( 'administrator' ) ) return $uc_template; return $template; } The file `under-construction.php` could be a plain HTML file; it doesn’t have to be a PHP file.
stackexchange-wordpress
{ "answer_score": 11, "question_score": 5, "tags": "templates" }
Lightbox on wordpress post page I am building WordPress admin plugin. In which I have a metabox with 10 checkboxes (It can be more than that). At below there is submit button. My requirement is: (A) open a lightbox when some one clicks on submit button. (B) In this lightbox I want to show all selected checkbox values with checkboxes. (C) Again, On this lightbox there would be a submit button. On clicking this form needs to be submitted with selected checkboxes values. The lightbox will work as confirmation window, Any help much appriciated.!enter image description here
Before anything... to get a good answer, you need to provide a good question. Code examples would help a lot. You can use jQuery to accomplish what you need. Suppose your checkboxes are in a list. 1. You can assign an ID to the list UL. 2. You can use jQuery to run through every element in that list and see if the checkboxes are checked $("#checked li:checkbox").each(function(){ if($(this).is(':checked')){ //from here you can put the results found in an array, // or just append to a hidden div that you can target with the lightbox plugin you're using. } }); The idea is to build a hidden DIV that you can use to open as a lightbox. The submit button would have to trigger your form to submit the data to either a table you created in your database, or add it to an existing wordpress table. I hope this helps you get it started.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, wp admin" }
wordpress login blank screen i wanted to make an offline copy of my live website on my pc so i installed xamp and installed on it wordpress and exported the database and took a copy of files on fttp and after i have done eveything and i wanted to make open my live website to edit something it gives me a blank page when i open "www.sitename.com/wp-admin" but when i open "www.sitename.com/wp-login.php" it open put when i insert username and password it also gives me blank page i opened the wp-config and i found that dp host became **"localhost"** i think this is my problem but how can i get my dbhost back is there a way to find it
i found the problem there was space in function.php
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp admin, localhost, wp load.php" }
Disable custom taxonomy on admin bar I created a custom taxonomy and i want to disable the taxonomy to show on the admin bar below my custom post type. How do i disable it?. The reason i want to disable is because the user is not allowed to add a category.
Did you have a look in the Codex? The option your are searching for is '`public`' Just add it as an argument in your call to `register_taxonomy()` like this: $args = array( 'public' => false, ... [your-other-arguments] ... ); register_taxonomy( 'genre', array( 'book' ), $args ); Docs go here: > **public** > > (boolean) (optional) Should this taxonomy be exposed in the admin UI. > > Default: true <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "custom post types, categories, custom taxonomy" }
Changing the post date and time with function What function can be used to update a post's post date and time to the current date & time?
Call `wp_update_post()` with a special value for `'post_date'` and `'post_date_gmt'`: $time = current_time('mysql'); wp_update_post( array ( 'ID' => 123, // ID of the post to update 'post_date' => $time, 'post_date_gmt' => get_gmt_from_date( $time ) ) );
stackexchange-wordpress
{ "answer_score": 30, "question_score": 9, "tags": "posts, functions, date" }
How do I only load js on the post-new.php and post.php pages in admin? I have some script that is loading in the admin. I only need it to load on the new post and edit posts screens. What is the best way to do this?
Check the page and enqueue your script accordingly: global $pagenow; if (! empty($pagenow) && ('post-new.php' === $pagenow || 'post.php' === $pagenow )) add_action('admin_enqueue_scripts', 'enqueue_my_scripts'); function enqueue_my_scripts() { wp_enqueue_script(...); } // function enqueue_my_scripts
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugin development, javascript" }
I can't change the body background-color through style.css Using a child of Twenty Twelve, I've been adding color to all the major containers (#main, #content, #secondary, etc.) using #arbitrary-id { background-color: #dedede; } This works for everything but body. I should be more clear: it changed the body background color until I messed with the background color in "Appearance -> Background". Now no matter what I try, I can't override that. Looking in the HTML of the page and inside the `<head>` I see: <style type="text/css" id="custom-background-css"> body.custom-background { background-color: #e6e6e6; } </style> Naturally, I tried to change the color using that selector, but since it's generated internally, that trumps the external CSS. I'm at a total loss for how to do this. How do I change the background color of the body using CSS?
It sounds like you just need to remove support for the custom background color. remove_theme_support( 'custom-background' ); You will probably need to hook it to get it to run after the parent `functions.php` function disable_bg_wpse_97248() { remove_theme_support( 'custom-background' ); } add_action('after_setup_theme','disable_bg_wpse_97248',100)
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "theme twenty twelve, custom background" }
Using page-id-{ID} from body_class() in local dev, versus live staging Not sure this is a question suitable for this forum, but I'll try: I think it is pretty convenient targeting elements in css/jQuery for a specific page by using the page-id-{ID} generated by body_class() in a template. But this gets problematic when developing on a local dev machine and then transfering to a staging server for your customer where the page id's is not the same. How do you handle this?
You could use slugs instead of IDs. Taken from the Starkers theme (add it to your functions.php): add_filter( 'body_class', 'add_slug_to_body_class' ); function add_slug_to_body_class( $classes ) { global $post; if( is_home() ) { $key = array_search( 'blog', $classes ); if($key > -1) { unset( $classes[$key] ); }; } elseif( is_page() ) { $classes[] = sanitize_html_class( $post->post_name ); } elseif(is_singular()) { $classes[] = sanitize_html_class( $post->post_name ); }; return $classes; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "theme development, jquery, css, local installation" }
Multiple post queries -category,posts per page,orderby I originally had this query on a posts category page: <?php $page_query = new WP_Query('post_type=post&cat=145'); ?> Which worked, but it only displayed the first 4 posts. So I wanted to display all the posts from the category, as well as change the posts per page limit, as well as set the orderby for good measure. However, this query returns EVERY post on my site, regardless of category: <?php $page_query = new WP_Query('post_type=post&cat=145'. '&posts_per_page=-1&cat' . '&orderby=date&order=asc'); ?> Seems like it should work in theory. Any ideas what I'm doing wrong?
You are passing the `cat` parameter twice-- the second time is empty. $page_query = new WP_Query( 'post_type=post&cat=145'. '&posts_per_page=-1&cat' . // <-- here '&orderby=date&order=asc' ); Maybe it is just me, but I find those query-string-like parameters hard to read and hard to keep straight. I'd advise you to create a proper array. $page_query = new WP_Query( array ( 'post_type' => 'post', 'cat' => 145, 'posts_per_page' => -1, 'orderby' => 'date', 'order' => 'asc' ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "query posts" }
How to loop through custom posts in admin edit screen How can I access the loop that displays all the custom posts in a custom post type's `edit.php` page? Is there some sort of hook for this? I want to do some condition checking on the data that is being pulled during the loop and it doesn't seem like WP offers any obvious solution.
Yes there is some sort of hook for this: manage_posts_custom_column Pseudo code: function my_cpt_custom_column( $column ) { global $post; if ( 'my_cpt' == get_post_type( $post ) ) { switch ( $column ) { case 'title': // do stuff with $post->post_title echo $post->post_title; break; case 'some-other-heading': // do stuff break; } } } add_action( 'manage_posts_custom_column', 'my_cpt_custom_column' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types" }
How to include custom field in shortcode (do_shortcode) in theme file To cut out a few steps and make it easier for authors, I have included a custom field for authors to enter details (may include HTML). I want to add the custom field to a shortcode in the theme. From multiple sources, I have a few sets of code, but the custom field is not displaying: <?php if ( get_field('test_field') ): $testfield = get_field("test_field"); ?> <?php echo do_shortcode('[shortcode]'. $testfield . '[/shortcode]'); ?> <?php endif; ?> I have also tried: <?php if ( get_post_meta($post->ID, 'test_field', true) ) { echo do_shortcode('[shortcode]'. printf(get_post_meta($post->ID, "test_field", true)) . '[/shortcode]'); } ?> I'm sure it is a simple solution, but I can't figure it out.
removed printf <?php if ( get_post_meta($post->ID, 'test_field', true) ) { echo do_shortcode('[shortcode]'. get_post_meta($post->ID, "test_field", true) . '[/shortcode]'); } ?>
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "custom field, shortcode" }
next_posts_link returns same content of 1st page Pagination seems to work fine... I have 21 posts... and it will go to 3 pages... however... every page shows 10 posts and the same content as the first page.... <?php $temp = $wp_query; $wp_query= null; $args = array( 'post_type' => 'a-reports', 'post_status' => 'publish' ); $wp_query = new WP_Query( $args ); if ( $wp_query-> have_posts() ) { while ($wp_query->have_posts()) : $wp_query->the_post(); ?> <a target="blank" href="<?php the_permalink(); ?>">Report</a> <?php endwhile; <?php next_posts_link('Older Entries »'); //clear again $wp_query = null; //reset $wp_query = $temp; ?>
In order to get pagination working with secondary Loops, you have to pass the `$paged` parameter to `WP_Query`, other wise the query does not know which set of posts to load and will load the first set, page 1, every time. I got it to work by adding `'paged' => $paged` inside the `$args = array();` $args = array( 'post_type' => 'a-reports', 'post_status' => 'publish', 'paged' => $paged, )
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, wp query, loop, navigation" }
Remove Adminstrator Hyperlink from a user having role to add and see users I have create a user role using Advance Access Manager wordpress plugin having role to see, add and remove users name as site_admin. When user login with his Id he is able to see the adminstrator and edit his profile. I remove that thing by using this code. Remove Ability for Other Users to View Administrator in User List? But the problem is the 'Adminstrator' hyperlink is still there. I want to remove that 'Adminstrator' hyperlink and in 'All' hyperlink the total count should be all user except the Adminstrator. It shows `All(3) | Adminstrator(1)| Subscriber(1) | site_admin(1)` I want to remove 'Adminstrator' Hyperlink from this links and set count for 'All(2)'. Thanks in advance.
I think something like this should work just fine: function my_views_users($args) { $hidden_role = 'administrator'; // it will hide filter with role 'administrator' - you can change it to some other role $users_counts = count_users(); $total_users = $users_counts['total_users'] - $users_counts['avail_roles'][$hidden_role]; $args['all'] = "<a href='$url'$class>" . sprintf( _nx( 'All <span class="count">(%s)</span>', 'All <span class="count">(%s)</span>', $total_users, 'users' ), number_format_i18n( $total_users ) ) . '</a>'; unset($args[$hidden_role]); return $args; } add_filter('views_users', 'my_views_users'); Of course you should add some if statement to disable this code, when user is logged in as admin (you don't want to hide users from admin, I guess).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, user roles" }
Wordpress theme options framework, I can't read them in my templates I successfully created my theme options page using this framework: < The problems Is that when, for example, I try to load the Option: 'logo_image' global $options; var_dump($options); /* dumps NULL */ and foreach ($options as $value) { if (get_settings( $value['id'] ) === FALSE) { $$value['id'] = $value['std']; } else { $$value['id'] = get_settings( $value['id'] ); } echo $$value['id']; /*prints nothing*/ } And echo get_option(‘logo_image’); /* also prints nothing */ This is how I am calling the framework in my functions.php if ( !function_exists( 'optionsframework_init' ) ) { define( 'OPTIONS_FRAMEWORK_DIRECTORY', get_template_directory_uri() . '/inc/' ); require_once dirname( __FILE__ ) . '/inc/options-framework.php'; } What am I missing?
If you've done everything correctly during the setup, then you should be able to load the logo_image option like this: $my_theme_prefix_option = of_get_option('logo_image');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme options, options, framework" }
How to edit php code in WordPress Post file? I have a wordpress page. In that wordpress page, user will have access to the following Window to `Publish` their Post in to the webpage. !enter image description here If the user enters an URL in any of the three filed I have marked in red above, my php code will look in to those URLs and determine if they are spam or not. Therefore, I want to put my php code inside the `Publish` button, so I can either disallow or allow the post after my php code run and determine if those URLs are spam or not. Can you please tell me the name of the wordpress file I should edit in order to put my php code in. I am new to wordpress and don’t know too much about their file structure.
You should never ever modify WordPress Core files. WordPress has an Plugin API (< that allows you to modify WordPress to your liking without changing Core code. In your case, the solution is to check the contents of the custom meta box fields before they are saved via the save_post action. If the content is not valid, you can display a message on the post screen using the admin_notices action.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "php, filters, filesystem" }
Screen Options JavaScript Code I want to know, what script drives the "screen options" animation toggle in WordPress. I'm referring to the options menu that slides out when the admin clicks the "Screen Options" link near the upper right corner of the window in the Post, or Page, or Categories, etc. – and slides back in when the same link is clicked again. Would appreciate it if someone knowledgeable could show me the exact location of that JavaScript code snippet.
This is in `wp-admin/js/common.js` or `wp-admin/js/common.min.js`: // Scroll into view when focused $('#contextual-help-link, #show-settings-link').on( 'focus.scroll-into-view', function(e){ if ( e.target.scrollIntoView ) e.target.scrollIntoView(false); }); Found with a search for `show-settings-link` in the complete source. :)
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "jquery, wp admin, javascript, jquery ui" }
Replace query_posts with pre_get_posts I have a static front page that checks if the user is logged in, and if he/she is a number of x posts from a specific category is displayed. For that I was using this code: query_posts('cat=2&showposts=5'.'&orderby=date&order=desc'); while (have_posts()) : the_post(); the_content(); endwhile; Now I found out that's not right to use `query_post` and that I should use `pre_get_posts` instead. I've tried to do this but somehow my page breaks down saying that my server is configured incorrectly.
Without seeing the broken code it is hard to say, but your filter should look something like this: function pregp_wpse_97354($qry) { if (is_front_page() && is_main_query() && is_user_logged_in()) { $qry->set('cat',2); $qry->set('posts_per_page',5); $qry->set('orderby','date'); $qry->set('order','DESC'); } } add_action('pre_get_posts','pregp_wpse_97354'); You mentioned something about the user being logged in, which your code does not check for, but I threw that in. This will run before the theme templates load so if this is conditional on the user being logged in you need to include that check in the filter callback.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "query posts, pre get posts" }
Display post date as 04/26/2013 I want to modify the date display of the post entries from current format: April 26, 2013 to this: 04/26/2013 Where in the code can I make this change? Thank you in advance!
the_time( 'm/d/Y' ); or the_date( 'm/d/Y' ); Note, `the_date()` will not print the same value twice. If a second post would get the same output you get nothing. If your theme doesn’t set a fixed value, like Twenty Twelve … get_the_date() … then the format is taken from your settings in _Settings/General Settings_ : !enter image description here You can change the format here, no need to change the theme.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "date" }
Display message depending on capability outside loop I want to display a unique message on the post (single.php) page **outside the loop** on author box. I want the message to be different depending on the author's capabilities. So for instance, if the author can `manage_options` then echo `this is admin`, else if the author can `edit_others_posts` then echo `this is editor` and finally else `this is contributor`.
Use `global $authordata`: Testing for roles: global $authordata; if ( in_array( 'administrator', $authordata->roles ) ) { echo 'Hello Admin!'; } elseif ( in_array( 'editor', $authordata->roles ) ) { // echo something else } Or testing for capabilities: if ( ! empty ( $authordata->allcaps['manage_options'] ) ) { echo 'The author can manage options'; } elseif ( ! empty ( $authordata->allcaps['edit_others_posts'] ) ) { // echo something else }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, php, author" }
Why is this search form not submitting when button is clicked? I've got a search form on my page, which works perfectly fine when I enter the text and press enter, however it doesn't submit anything when `.submit-search` button is clicked, why is that? note: `value="2"` is there for specific use. <form action="<?php echo home_url(); ?>" class="search-form" method="get"> <input class="search-input" type="text" value="Search..." name="s" id="s" onblur="if(this.value == '') this.value = 'Search...'" onfocus="if(this.value == 'Search...') this.value = ''"> <input class="submit-search" type="button" value="2"> </form>
I suggest you use `<input type="submit" />` or `<button type="submit" />`. `<input type="button" />` is valid but doesn't submit the form by default (without you adding any ajax/js magic to it.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "search, forms" }
Display category page number links for older posts I was given a task to move the content and certain familiar navigation elements from an old WP-based website to the new one, based on the latest version of WP. The blog page of the old site has the number links to the old posts near the bottom of the page: How can I create the same links in TwentyTwelve category page? Thank you in advance for your help!
First, that old site is _not_ any version of WordPress. Second, don't hack TwentyTwelve, make a child theme. if you hack it, your changes will be lost when the theme is updated. Third, the easiest way to achieve pagination like that would be WP-PageNavi.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "links" }
Creating Features List in Wordpress Post I want to create features list in wordpress post. I know how to do in CSS but I was wondering if it can be done by using a short code or a plugin?. Like [features_list] Item 1 Item 2 [/features_list] Example: !enter image description here
Convert the items in the shortcode into an array, and return a list: add_shortcode( 'features_list', 'shortcode_features_list' ); function shortcode_features_list( $atts = array(), $content = '' ) { $content = trim( $content ); if ( '' === $content ) return; $items = explode( "\n", $content ); $items = array_map( 'trim', $items ); return '<ul class="features"><li>' . join( '</li><li>', $items ) . '</li></ul>'; }
stackexchange-wordpress
{ "answer_score": 2, "question_score": -1, "tags": "plugins, php, shortcode" }
Code for Recent Posts Widget I want to make changes to code of the Recent Posts widget – could anyone please tell me where that code is located? Thank you in advance!
The default Recent Posts Widget code is in `includes/default-widgets.php` but you should not be hacking Core code. Copy that function to your theme's `functions.php`, rename it, and create your own customized widget.
stackexchange-wordpress
{ "answer_score": 9, "question_score": 8, "tags": "widgets, recent posts" }
"is_new_day()" alternative for years? I don't believe there's a `is_new_year()` function in WordPress, as an alternative for `is_new_day()`. I'm trying to display the year only once for each set of posts, what would be the best way to do this? Should I just check the date manually with PHP in the loop or are there any better ways?
You could create a helper function that returns a year number only once per year: function get_unique_year( $post_id = 0 ) { static $last = 0; $post_id || $post_id = get_the_ID(); $year = get_the_time( 'Y', $post_id ); if ( $year === $last ) return; $last = $year; return $last; } Then fetch your posts and use that helper: $posts = wp_get_recent_posts(); // or any other function returning posts foreach ( $posts as $post ) if ( $year = get_unique_year( $post->ID ) ) print "Year: $year<br>";
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "functions, date time" }
Post Editor not working on WordPress 3.5.1 Recently i have updated my wp site to the latest version and since then post editor not working, **What i have tried:** * Disabled all plugins. * Installed "Use Google Libraries". * Disable all plugins except "Use Google Libraries". * Re-install WordPress from the update panel. **Followed some solutions on WordPress support:** Adding this line in wp-config.php Solution #1: define('SCRIPT_DEBUG', true); Solution #2: define('CONCATENATE_SCRIPTS', false ); i have tried all of the above methods and none of them worked for me. please help me with this issue because i can't able to update my website :(
Well this is embarrassing. I found the culprit, it was one of my theme :( Enabling Twenty Twelve solves the visual editor issue. Sorry guyz and thanks for the support.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "wp admin" }
Which files get updated in a plugin update? When a user updates a plugin from the WordPress admin panel, does every plugin file get overwritten, or just the ones that have changed from the previous version? For example, let's say that a plugin has 3 files: a.php, b.php, and c.php Version 2.0 has changes to a.php and b.php; c.php was unchanged. However, the user made a change to c.php before updating to 2.0. Does the user lose his changes?
When you update a plugin you just get a new Zip-file containing the whole plugin. You don't get the information which files in that archive changed. That's the reason why all files are overwritten.
stackexchange-wordpress
{ "answer_score": 8, "question_score": 4, "tags": "plugins, updates" }
Getting the top level permalink using get_post_ancestors() I have a function for displaying **the title** of the top-level page of the current sub-level page. It's working quite well, but I can't figure out how to also link to the same top level page that is displayed. function my_page_ancestor() { global $post; if( !is_front_page() ) { $parents = get_post_ancestors( $post ); $top_parent_link = get_permalink( end($parents) ); echo '<a href="' . $top_parent_link . '"><span class="pageAncestor">' . get_the_title( end($parents) ) . '</span></a>'; } } I've tried `get_the_permalink()` inside the function, but it just breaks. **Edit:** I've corrected the function above, and it now works as I wanted.
You may want to try get_permalink() ie: `get_permalink( end($parents) )`. :-)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, sub menu" }
How to make title for home to be News, but if page has parent then its name else just post/page name Made own template from scratch and tutorials. This is showing description of post/page Title and in home its showing website name. <h3><?php is_home() ? bloginfo('description') : wp_title(''); ?></h3> I wanted to change that if home page then that it writes News and if page then its name but if page is subpage then parent name.
Put this in your `functions.php`: function my_title() { if (is_home()) echo 'News'; else { global $post; if ($post->post_parent) echo get_post($post->post_parent)->post_title; else echo $post->post_title; } } // function my_title and then use `<?php my_title(); ?>` anywhere you want. The above code prints **News** on the home page, for child posts the name of their respective parent, and the post title otherwise. If you want to do this **for pages only** (no other post types), then use this: function my_title() { if (is_home()) echo 'News'; else { global $post; if ('page' === $post->post_type && $post->post_parent) echo get_post($post->post_parent)->post_title; else echo $post->post_title; } } // function my_title
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "pages, bloginfo" }
How to make only posts show date Made template but how to make date to show only in posts not anywhere else? <div class="date"><strong><?php the_date(); ?></strong></div> This makes date to show in Home, Pages but i need only for posts. Something like if is post then the_date(); ?
There are two options: 1. Create a separate `single.php` for posts and show the date there only. 2. Use a condition: if ( is_single() ) { ?><div class="date"><strong><?php the_date(); ?></strong></div><?php }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "posts" }
Limit Custom Crawler to front end only I am using the following custom walker to hide the Login and Register pages from my navmenu created with wp_get_nav_menu_items..... function wpse31748_exclude_menu_items( $items, $menu, $args ) { // Iterate over the items to search and destroy if ( is_user_logged_in() ) { $registerpage = get_page_by_title( 'Register' ); $loginpage = get_page_by_title( 'Login' ); foreach ( $items as $key => $item ) { if ( $item->object_id == $registerpage->ID ){ unset( $items[$key] ); } elseif ( $item->object_id == $loginpage->ID ){ unset( $items[$key] ); } else{} } return $items; } else { return $items; } } add_filter( 'wp_get_nav_menu_items', 'wpse31748_exclude_menu_items', null, 3 ); It works fine but it is also affecting the menus page within the dashboard, is there a way to limit the crawler to only affect the front end?
You can try the `!is_admin()` so your code would be: function wpse31748_exclude_menu_items( $items, $menu, $args ) { // Iterate over the items to search and destroy if ( !is_admin() && is_user_logged_in() ) { $registerpage = get_page_by_title( 'Register' ); $loginpage = get_page_by_title( 'Login' ); foreach ( $items as $key => $item ) { if ( $item->object_id == $registerpage->ID ){ unset( $items[$key] ); }elseif ( $item->object_id == $loginpage->ID ){ unset( $items[$key] ); } } } return $items; } add_filter( 'wp_get_nav_menu_items', 'wpse31748_exclude_menu_items', null, 3 );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "walker" }
Jetpack stats and caching strategy I'm thinking about hosting a WordPress website with agressive caching/optimization strategies (like varnish, microcache, ngx_pagespeed, etc). But I still want Jetpack stats to work alright. What should I pay attention to? How does jetpack-stats count visits? * tracking images? * AJAX calls? * internal WP hooks? Depending on its strategy, I'd probably have to tweak my cache configuration...
Let me quote what's mentioned in the official FAQ of WordPress.com Stats plugin (JetPack statistics module uses this plugin as the base)... > The plugin collects stats via a javascript call, so as long as the JS call is on the page stats will be collected just fine, whether the page is cached or not. In short, you don't have to worry about JetPack stats. It works irrespective of the caching layer/s used.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "cache, plugin jetpack, nginx" }
How to style first post differently with 'get_template_part'? I need help in styling the first post differently than the rest. What makes this differently is that I'm using this get_template_part in order for infinite scroll to work on my site. This is what I use on index.php <?php while (have_posts()) : the_post(); get_template_part( 'content', get_post_format() ); endwhile; ?> which will load the loop from content.php. This was my old loop: <?php if (have_posts()) : ?> <?php $post = $posts[0]; $c=0;?> <?php while (have_posts()) : the_post(); ?> <?php $c++; if( !$paged && $c == 1) :?> <-! first post --> <?php else :?> <-! the rest --> <?php endif;?> <?php endwhile; ?> <?php endif; ?> Thanks for the help.
Got it to work! <?php if ( 1 > get_query_var( 'paged' ) ) { ?> <?php if ( is_first_post() ) { ?> first! <br /> <?php the_title();?> <?php the_excerpt();?> <?php } else { ?> <?php the_title();?> <?php the_excerpt();?> <?php } ?> <?php } else { ?> <?php the_title(); ?> <?php the_excerpt();?> <?php } ?> You can see it in action - < Next question I have (same topic) is can this be cleaned up to make it simply as the code underneath is_first_page are duplicates <?php } else { ?> <?php the_title();?> <?php the_excerpt();?> <?php } ?> <?php } else { ?> <?php the_title(); ?> <?php the_excerpt();?> <?php } ?> Thank you so much for the help!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop" }
Changing taxonomy term by slug (wp_update_term) What I am trying to accomplish is to update a taxonomy term name using its slug rather than the $term_id Wordpress does this by: <?php wp_update_term( $term_id, $taxonomy, $args ) ?> Is it possible to do this via the slug instead? <?php wp_update_term( get_term_by( 'slug', $value, $taxonomy, $output, $filter ) ) ?> I've been stuck on this for a while - but no success. The default taxonomy terms are created by a plugin. I am creating a secondary plugin to change the taxonomy terms created by the 'parent' plugin. Thanks! Roc. \--- Edit --- Should mention that I am not able to update the term by id because the taxonomy id changes based on when the plugin is activated, and if other tags exists before it can be created.
As you hinted in your question, you could use `get_term_by()` to return an object or array containing the term's id, then use it to update that term. Something like this should work: $your_term = get_term_by( 'slug', 'your_slug', 'your_taxonomy' ); if ( false !== $your_term ) { wp_update_term( $your_term->term_id, 'your_taxonomy', $args ); } References: < <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "custom taxonomy, taxonomy, terms, slug" }
Keeping 'current-menu-item' highlight of navigation menu? The navigation menu of my site is generated via wp_nav_menu( array( 'theme_location' => 'primary') ); Some menu entries are category pages (say `/category/news/`). This page contains links to the next level, single post posts (say `/news/123/`). I noticed that the menu is only highlighted ('current-menu-item' class) when the category page is the current. How can I make the menu stay highlighted when viewing single post pages (`/news/123/`)?
You can target the `.current-menu-parent` class in your CSS to keep the category highlighted when viewing single posts.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "menus" }
"set_front" => false on custom post type breaks wp_list_categories links My question is related to this one. I would like my post permalinks to be prefixed by `/blog/`, but I don't want this prefix to be applied to my custom post type _portfolio_. In other words, I expect post links to use `/blog/` and portfolio links to use `/portfolio/`. This is why I set `set_front` to `false` for this post type and set my permalink structure to `/blog/%postname%/`. This almost works, except that a `wp_list_categories` call in my page header prints broken links. My skill taxonomy links have the form `/portfolio/[SKILLNAME]`, but this function is outputting `/blog/portfolio/[SKILLNAME]`, which leads to a 404 page. Any thoughts on what might be going on here? I already tried clicking _Save changes_ on the Permalinks settings page to force a flush of the rewrite rules.
The parameter you are using is wrong. There is no `set_front` parameter when you register a Custom Post Type. The appropriate parameter is `with_front`. > 'with_front' => bool Should the permastruct be prepended with the front base. (example: if your permalink structure is /blog/, then your links will be: false->/news/, true->/blog/news/). Defaults to true > > <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "permalinks, url rewriting" }
How to increase maximum number of sidebars support? How can i use more than 20 sidebars in wordpress. I'm working on a big information portal, and I need big amaunt of sidebars (about 40, I guess). So I have 20 sidebars now and when I add one more it overrides one of the previous entered. I searched the web about similar problems, but I found nothing ... Can somebody help me get out of this situation? Link to the site
Just tried it on a test install with twenty-something sidebars, all works fine. Note that `id` parameter should be unique between all of them. `name` doesn't have to be, but it's nice to keep it unique as well so as to avoid confusion in the admin UI. register_sidebar( array( 'name' => 'twenty-three', 'id' => 'sidebar-23', 'description' => 'dummy description', 'before_widget' => '<aside id="%1$s" class="widget %2$s">', 'after_widget' => '</aside>', 'before_title' => '<h3 class="widget-title">', 'after_title' => '</h3>' ) );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "sidebar, register sidebar" }
Number of displayed posts I have tried many things to solve this problem. So I have a plugin which displays projects assigned to users in a widget. It displays projects as posts. The problem is that it only displays `5` projects on the page. I am sending a code which display posts: $projects = get_posts(array('post_type' => 'projects')); One guy told me to change it to $projects = get_posts(array('post_type' => 'projects', 'number posts' => 10)); which should help but it didnt. Anyone have idea how to solve it ? I can send whole code if it's needed.
The WordPress function `get_posts()` supports: 'posts_per_page' => 10, 'numberposts' => 10, so you should use: $projects = get_posts(array('post_type' => 'projects', 'numberposts' => 10)); instead of $projects = get_posts(array('post_type' => 'projects', 'number posts' => 10)); If you want to show all posts, you can use 'posts_per_page' => -1 You can read more about this in the WordPress Codex: <
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, get posts" }
How to modify category.php to list posts alphabetically? As the title says. Would be grateful for your help. Thank you.
Try to do all theme modifications in functions.php whenever possible. It keeps the theme files clean and uncluttered. Here's an example using the `pre_get_posts` action: function order_category_archives( $query ) { if ( is_category() && $query->is_main_query() ){ // is_category() can specify a category, if necessary $query->set( 'orderby', 'title' ); $query->set( 'order', 'ASC' ); } } add_action( 'pre_get_posts', 'order_category_archives' ); Notice that this uses `is_category()` to modify the query only if we're looking at a category archive page. An optional parameter can be added to specify which category (or categories) this should be limited to. Finally, we use `is_main_query()` to avoid modifying any additional queries that may be on the page.
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "categories" }
Hide widgets/plugins from dashboard I have two plugins in the dashboard, SEO Wordpress and Custom Content Type Manager, and for security reasons I want to hide these from dashboard. How to do that? I tried to hide the SEO Wordpress with this: // Remove Admin Dashboard menus function wp_admin_dashboard_remove_menus() { global $menu; $restricted = array(('Comments'), __('Users'), __('Updates'), __('wpseo_dashboard')); end ($menu); while (prev($menu)){ $value = explode(' ',$menu[key($menu)][0]); if(in_array($value[0] != NULL?$value[0]:"" , $restricted)){ unset($menu[key($menu)]); } } } add_action('admin_menu', 'wp_admin_dashboard_remove_menus'); Tried many combinations like: __('wpseo') __('wp-seo') __('wp_seo') But the SEO menu did not hide.
## Wordpress SEO If you want to remove the admin menu: !wpseo you can do that with: function hide_wpseo() { remove_action('admin_menu', 'zeo_options_menu'); } add_action( 'init', 'hide_wpseo'); where it will be removed for all users. ## WordPress SEO by Yoast To hide the admin menu: !admin menu and the admin menu bar: !admin menu bar one can use: function hide_yoastseo() { remove_action('admin_bar_menu', 'wpseo_admin_bar_menu',95); remove_menu_page('wpseo_dashboard'); } add_action( 'admin_init', 'hide_yoastseo'); where it will be hidden for all users. ## Custom Content Type Manager Here one can hide the admin menu: !admin menu from all users with: function hide_cctm() { remove_menu_page('cctm'); } add_action('admin_init', 'hide_cctm');
stackexchange-wordpress
{ "answer_score": 5, "question_score": 1, "tags": "dashboard, admin menu, admin bar" }
Set default text for the editor in new posts I was wondering, is it possible to set default text to appear inside "text" part of the wysiwyg located on Create post page? So every time you click add new post that text would be there waiting for you?
There is a filter named `default_content`. It does exactly what the name says. :) Example: add_filter( 'default_content', 't5_preset_editor_content', 10, 2 ); /** * Fills the default content for post type 'post' if it is not empty. * * @param string $content * @param object $post * @return string */ function t5_preset_editor_content( $content, $post ) { if ( '' !== $content or 'post' !== $post->post_type ) { return $content; } return 'This is the <em>default</em> content. You may customize it.'; } As you can see, the post type is already available, so you could set different defaults for different post types. Related filters are `default_title` and `default_excerpt`. They work the same way. You can also send someone a link with parameters for `content`, `post_title` and `excerpt`: Output: !enter image description here
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "editor, customization" }
Determine which template-{slug}.php is being loaded I am trying to make a personal plugin that does specific things based on what is loaded. In this example, in my action method I want to perform one function if the currently loading page is using the `template-blog.php` template, if it's a single blog post (loading `single.php` do a second function, anything else do a 3rd function I am not quite sure what method I need to use, and so far Google is not pulling up the right methods. I have been trying get_current_template(), get_template() get_page_template(), but none of them pull the stuff I am looking for above.
Using `body_class()` on the body tag would probably be the easiest way to tell which template is in use. <body <?php body_class(); ?>> Depending on which page you are on, it will output similar to this <body class="page page-id-10 page-template-default logged-in"> Where `page-template-default` is the template in use. It's also useful for blog posts and custom post types.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom post types, plugin development" }
Alter the reset password link after clicking on the reset password option in WP, we're getting this link wp-login.php?action=rp&key=[theKey]&login=testing> instead of getting this can we alter it to something link to out custom page?
Try this add_filter( 'lostpassword_url', 'lostpass_url_fix'); function lostpass_url_fix( $link ){ return ' } Just replace the example.com with any url you want
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, reset, password" }
Access $_POST data after redirect How can I access `$_POST` data after a page redirect? I guess there is some way to tell WordPress to pass all `$_POST` data to the redirected address, like it does with `$_GET` data, using Rewrite Rules, but how?
Redirects are GET requests usually, and the browser doesn’t send the POST data for those. That’s not something WordPress can change. You could create a session, or – better – process the POST data first, _then_ redirect. In your plugin, you could do: add_action( 'plugins_loaded', 'process_post_data', 0 ); function process_post_data() { // Read raw POST data, not touched by WordPress $data = file_get_contents( 'php://input' ); // then redirect }
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "url rewriting, rewrite rules" }
Page Template Dropdown - Missing In WordPress MultiSite I am using WordPress Multi-Site and on the page edit screen I am completely missing the Page Template drop down. I have tried looking in Page Options and it's missing from there as well. If I enable the same theme in standard WordPress then the page templates show up Anyone any ideas?
Problem resolved, turns out there was references to BuddyPress is my theme which were causing a conflict My theme was originally a BuddyPress theme, I had since ditched BP and was using the theme as a standard WP theme. Still lingering in the template information file was.... Template: bp-default Tags: buddypress With these tags the theme still functioned but the templates were not being displayed, removed them and everything is fixed
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "multisite, page template" }
get_search_link() redirects to 404 template page I built a custom theme, and in it, there is a 404.php page and a search.php page. Elsewhere in the template, I wanted to link to the search page directly. So, I used the get_search_template() function to get the search page link, which results in a link like this: < When I click the link, I get sent to the 404 page template. Why is it going to the 404 page template instead of the search page template?
Confusingly WordPress does not have a concept of a simply _search_ page, it only has concept of _search results_ page. The difference is critical because search without search query 404s as you are seeing. If you want dedicated search page you would have to implement it as custom one, see Codex > Creating a Search Page.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "templates, search, 404 error" }
Restrict query_posts by Date? To display the most popular posts based on page views I am using this code (source): <?php query_posts('meta_key=post_views_count&orderby=meta_value_num&order=DESC'); if (have_posts()) : while (have_posts()) : the_post(); ?> <li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endwhile; endif; wp_reset_query(); ?> I would like to restrict the query to return posts from a certin date (i.e. the last seven days) and I am unsure how I would achieve this.
I've done something in the past using custom fields. Maybe this can get you going in the right direction? This is done directly after the `<?php while ( have_posts() ) : the_post(); ?>` <?php $currentdate = date("Ymd"); $expirationdate = genesis_get_custom_field('_racedate'); $expirestring = str_replace("-","",$expirationdate); if (is_null($expirationdate)) { $expirestring = '30005050'; //MAKE UN-EXPIRING POSTS ALWAYS SHOW UP; } else { if (is_array($expirationdate)) { $expirestringarray = implode($expirationdate); } } //else if ( $expirestring + 1 > $currentdate ): ?> This will actually show up everything that has been posted (in my case, future races) and a day after the "racedate", the post would disappear from the loop (it still remains in the dashboard).
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "query posts" }
Transient unique names What would be the correct way to assign a different name to each transient for each instance of a plugin used as a widget or shortcode?
Transients have practical limitation on key length (45 symbols or something like that), so using dynamic keys tends to come with risk of ending up with keys too long and having it break down. One of common practices is to form unique string (for example combination of plugin name and type of data being saved, etc) and hash it with `md5()` to use as transient key of fixed predictable length. For clarity could use plugins name to prefix md5 hash instead, so it's clear where transient comes from, when seeing it in database.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "plugins, id, transient" }
Modify search function in WordPress (TwentyTwelve) I want to remove "Search for" text from search form in TwentyTwelve, to wrap in in a div for styling, and probably to play with php a bit – and I'd appreciate some advice on how to do that best. My "sub-questions within a question": 1) Where is the main search function is located? 2) Should I create a separate custom file, add code to functions.php - or is it okay in this case to just edit the original search function? Thank you in advance for your help!
Modify the `searchform.php`, or create one in a child theme (recommended), and you should be able to modify the form all you want. This is the file that `get_search_form` looks for and is the file used by the default search widget, though it is not listed in the Template Hierarchy. # Reference: <
stackexchange-wordpress
{ "answer_score": 6, "question_score": 3, "tags": "functions, customization, search" }
Unregister Nav Menu with fallback? I am trying to create a child theme so theme updates are much easier. I want to remove the parent theme menus and add my own. I know I can modify the header.php file (where these menus exist) and edit the wp_nav_menus directly, but I'm trying to avoid using as many theme files as possible, so I'm trying to accomplish this in my functions.php file. Using unregister_nav_menu I am able to remove the menu from the parent theme location as such: function RR_remove_parent_theme_menus() { unregister_nav_menu( 'top-menu' ); unregister_nav_menu( 'header-menu' ); } add_action( 'after_setup_theme', 'RR_remove_parent_theme_menus', 20 ); This works great for "top-menu" but "header-menu" is coded in the parent theme with a custom fallback. Is there any way to override a custom (or a default) menu fallback using unregister_nav_menu or something else?
You can filter `'wp_nav_menu_args'`, set an invalid `theme_location` and the magic function `__return_false` as fallback: add_filter( 'wp_nav_menu_args', 'override_parent_args' ); function override_parent_args( $args ) { if ( 'header-menu' === $args['theme_location'] ) { $args['fallback_cb'] = '__return_false'; $args['theme_location'] = 'ticky_tacky'; } return $args; }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "functions, menus, child theme" }
Why Jetpack is missing the "Feedbacks" menu item? Is there a known issue that would prevent the "Feedbacks" menu item from showing? I have two wordpress installs, one has the menu item the other doesn't. They both have the same plugins, theme, and scripts.
To get the `Feedbacks` admin menu with the **Jetpack** plugin installed !enter image description here one has to make sure the `Contact Form` is activated through the **Jetpack** setup page `/wp-admin/admin.php?page=jetpack`: !enter image description here
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "admin, plugin jetpack" }
If 'editor' is empty, then Is there a way to write a php conditional in WordPress that says: `"If 'editor' is not filled out (i.e. empty), then, do some code..."` I know it's sort of a strange request but basically I have a portfolio set up where if I don't fill out the editor for a post (i.e. project), I don't want a certain link to show.
I'm using something of the sorts for delivering some standard default text if the post content is empty. Give this a whirl: <?php if( $post->post_content != "" ) { //do something or show content } else { //do something else }?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php, conditional tags" }
WooCommerce - PrettyPhoto appending URL with #prettyPhoto For some reason the PrettyPhoto script that WooCommerce is now using is adding #prettyPhoto to the end of URL's once it's been opened in that page. See here for an example Also, when you close the lightbox down it takes 2 or 3 clicks of the back button to get back to where you were previously. Anyone have any idea why?
That is a … feature of this script, called _deeplinking_. It should be fixed already, maybe you missed an update? As you can see in that commit, you can disable it by editing `assets/js/prettyPhoto/jquery.prettyPhoto.init.js`. Add deeplinking: false … to all calls of `prettyPhoto({});`.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery, plugins" }
Are uploads directories created on a schedule? I have a cron job that alerts me to modified files on a couple of WordPress installs. Two of them alerted me tonight to the creation of apparently empty folders like /home/foo/public_html/wp-content/uploads/2013/05 Is there a scheduled job in WordPress to create the next month's upload directory on the last day of a month?
I believe by default these folders are created by user interaction, however, it's possible that a plugin may be calling a function to create these monthly upload folders. > Note that using this function will create a subfolder in your Uploads folder corresponding to the queried month (or current month, if no $time argument is provided), if that folder is not already there. You don't have to upload anything in order for this folder to be created. That's according to the the Codex > Function Reference > `wp_upload_dir()`. Maybe you could get more detailed logs to determine how they're created...I'm not real familiar with server administration.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "cron, wp cron, uploads" }
Add a select-option to the default widgets I would like to add an extra feature to one of the default widgets so that the user can choose from the select-field to either align the widget to the left, center or to the right. !enter image description here !enter image description here How would I be able to achieve this without tampering with any of the files outside of my themes directory?
The default widgets do not offer any hooks for that. You have to replace the default widget and add your field to the new class. The other option would be using JavaScript to insert the field, and a filter for `'update_option_widget_' . $widget->id_base` to save the value. I think the separate class is the cleaner approach.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, functions, widgets, sidebar, select" }
Are Post IDs Unique Across all Post Types? I thought Wordpress post IDs were only unique within each post type, so that the first instance of each post type would have an ID of 1 and they would count up from there. In order to get a specific instance of a custom post type, you would have to designate that post type in the query. But according to this answer on another question, post IDs are actually unique to each post, regardless of post type. I checked in the posts table for the site I'm working on now, and sure enough the post IDs are unique. But I'm sure I read somewhere (a couple years ago) that they weren't. Did Wordpress change the way it sets post IDs, or have I just been wrong this whole time?
All post types are stored in the same `posts` table, so they have to use different post IDs. That was always the case, since the the post type `page` was introduced 2005 with version 1.5.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 2, "tags": "custom post types, id" }
Wordpress admin not changing language I'm struggling to get a nb_NO version of the wordpress admin interface. Here's what I've done so far: * Installed latest wordpress from wordpress.org * Moved installation from root to wp/ - site working fine * Edited wp-config.php to define('WPLANG', 'nb_NO'); * Went to wp-admin and clicked "Re-install now" on the 3.5.1–nb_NO update. The update runs with no errors, but the admin is still in english. I've tried with different languages as well with the same result. What am I doing wrong? Moving the wp core to wp/ should not brake the language installer..?
The problem was that I had changed the 'WP_CONTENT_DIR' directory, and Wordpress did not have writing permission to the new content folder, so it couldn't create the 'WP_CONTENT_DIR'/languages folder. After creating the languages folder in my new WP_CONTENT_DIR directory Wordpress did the language upgrade successfully.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "wp admin, language" }
unit testing admin password I'm writing up unit tests for my plugin and I need a logged in user to test, but I can't find the admin password anywhere. Does anybody know what the default admin password is? I'm extending the `WP_UnitTestCase` and taking the tests from < My code at the moment: <?php require_once('myPlugin.php'); class MyPluginTest extends WP_UnitTestCase{ function setUp(){ wp_signon(array( 'user_login' => 'admin', 'user_password' => 'no_idea' )); } } any help would be appreciated.
The password is … `password`. You can see that in `includes/install.php`: wp_install( WP_TESTS_TITLE, 'admin', WP_TESTS_EMAIL, true, null, 'password' ); The last parameter is the admin password.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "unit tests" }
Resetting menu_order to 0 for posts in PHPmyAdmin? Installed a plugin that allows the re-ordering of posts from any post type / category / tag using a drag/drop interface. After some time of using, my post order went haywire and new posts began to appear in a jumbled order. The plugin's native _reset_ button resolved this, but the old posts are still jumbled (only for two particular categories). Plugin author suggested updating **menu_order** to 0 only for the post type in question and I have a few questions: 1. I can't seem to find the appropriate field, which table would I look in? 2. Post types just cover posts, pages and all custom post types, right? If I'm only having this issue with a category, I still have to reset the menu_order of the entire parent post type? 3. I see the menu_order filter in the Codex, but I thought this was only for top level menu order, not the order of actual posts?
This piece of mySQL code should do the trick. Go into PHPmyAdmin, click the SQL tab and paste this code: UPDATE wp_posts SET menu_order = 0 WHERE post_type = 'my_post_type'; This should set `menu_order` for all posts of the post type of your choice to 0.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 1, "tags": "phpmyadmin, menu order" }
How does Show Posts based on a keyword search work in WP_Query I am wondering how the search go through by defining 's' parameter in WP_Query. For example if I have a post assigned to "East" term in taxonomy "Direction", the post didn't mention any "East" or "Direction" word in the post content or title. When I define the 's' value as "east" (no other parameter defined) in the WP_Query, can wp_query found the post? Sorry for my bad English, hope you understand. Thanks
WP search is rather simplistic. After some processing on search query, it adds condition to SQL query looking for `LIKE` (contains) match in title or post content. So natively assigned taxonomies are not searched. So you will either have to use additional code (or third party plugin) or use third party search solution (Google Custom Search Engine is rather popular).
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "wp query, search" }
the_post_thumbnail() get the URL to the "medium" sized image In the script below, I need to get the URL path to the "medium" size image in the "data-responsive" attribute. Its currently returning the thumbnail size. the_post_thumbnail("thumbnail", array( 'itemprop' => 'image', 'class' => 'alignleft', 'style' => 'margin:5px 15px 10px 0;', 'data-responsive' => wp_get_attachment_thumb_url(get_post_thumbnail_id($post->ID),'medium') ) ); I want the thumbnail used as the default image, however, I need to write the URL to the medium sized image so that I can use that in media queries to swap the image to higher res on larger devices.
`wp_get_attachment_thumb_url()` does not accept size as argument. You might be looking for `wp_get_attachment_image_src()`, but I am not sure on top of my head - too many functions in that corner.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, post thumbnails" }
One Child Functions.php for Multiple Child Themes I have a wordpress setup that I use for clients with around 30 or so child themes that they can choose from. Each child theme has it's own functions.php file currently. Is it possible to setup just one child functions.php and call it from all the separate child themes? My reason for wanting this functionality is I find myself continually making changes to the functions.php and I have to do it to all 30+ themes every time.
Well, I'd say that you need a custom plugin. All the rationale is in this Q&A: Where to put my code: plugin or functions.php? Also related: * Where do I put the code snippets I found here or somewhere else on the web? * Create a Functionality Plugin Instead of Using Functions.php And answering to the Question, create the following file `/wp-content/themes/common-functions.php`, and paste what you need in it. And inside the child theme `functions.php` use: require_once ( TEMPLATEPATH . '/../common-functions.php' ); or require_once ( WP_CONTENT_DIR . '/themes/common-functions.php' );
stackexchange-wordpress
{ "answer_score": 6, "question_score": 4, "tags": "functions, child theme" }
How to get a value from comment meta I've add the field **country** in the comment form. Working nice and I can see the value in the table commentmeta. !enter image description here Now I try to display this value in my comment list. In my **single.php** I call the list of comments: <?php wp_list_comments('type=comment&callback=format_comment'); ?> In my **functions.php** I format the comment: function format_comment() { ?> <div class="comment"> <p><?php comment_author(); ?></p> <p><?php get_comment_meta( $comment->comment_ID, 'country', true ); ?></p> <p><?php comment_date('Y/m/d - g:i A'); ?></p> <p><?php comment_text(); ?></p> </div> <?php } ?> So... to get the value for the meta **country** I use <?php get_comment_meta( $comment->comment_ID, 'country', true ); ?> Without success…
Looking at the Codex entry for `get_comment_meta()`, it appears that when the `$single` argument is set to `TRUE` (as you have done), the function returns a string. Try throwing an `echo()` into the works: <?php echo get_comment_meta( $comment->comment_ID, 'country', true ); ?>
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "comments, meta value, comment meta" }
Is there a quick way to view the wp-cron schedule I'm trying to work which plugin is triggering wp-cron. I know about the code: < , but I'd prefer to do something in the sql backend rather than write a plugin.
Why don't you just create a cron job, make a database dump and look where the info about the cron job is kept? That's what I did. As suspected, WordPress 3.5.1 keeps its cron jobs in the `{wp}_options` table under the name `'cron'`. SELECT * FROM `wp_options` WHERE `option_name` LIKE '%cron%' Or through functions.php: $cron_jobs = get_option( 'cron' ); var_dump($cron_jobs);
stackexchange-wordpress
{ "answer_score": 44, "question_score": 29, "tags": "wp cron" }
preg_replace and comment_form_defaults this was kinda of a joke at the beginning but now I'm wondering if it's possible to use regex with the hook comment_form_defaults. Here is what I'm looking for : function remove_default_allowed_tags( $defaults) { $defaults = preg_replace('/<p class="form-allowed-tags">(.*?)<\/p>/','', $defaults); return $defaults; } add_filter('comment_form_defaults', 'remove_default_allowed_tags', 2); I know it can be easily done with something like this : `$defaults['comment_notes_after'] = ''; return $defaults;` But I just want to know if I can use my regex in this context and if not, why. Thanks for your answer(s).
You can use regex anywhere you have a string to manipulate. That is basic PHP. There is nothing special about WordPress that changes that. But why use regex when there are other options? As much fun as it is, regex is tricky and easy to get wrong, and there is significant overhead to using it. What you are doing generates an "array to string conversion" `Notice`, by the way. `preg_replace` will accept an array of strings as the third parameter but `$defaults['fields']` is an array so you get an `Notice` so it wouldn't work as expected if you tried to alter that field.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "regex, allowedtags" }
Video uploaded with the native media uploader gives Error 404 I created a `shortcode` to make an HTML5 player insert into my post, but my problem is when I attempt to view a video that I've uploaded with the native `Media Uploader`, I get a file not found error. The test video I used is an `.mp4`. Is there a block on using videos in the `Media Uploader` that needs to get removed? This does not appear to be a file permission issue, because the file uploads. When I browse the remote server via FTP, I see my file was added into the `/wp-content/uploads` directory. Any reason why it wouldn't show up by accessing the file from the browser directly?
Ok, I found the problem. It wasn't a `Wordpress` problem, but a server issue. I had to add the file extension `.mp4` with MIME type `video/mp4` in the MIME types of the IIS server. Here is the link I found with the steps to correct the issue: < 1) Select the site to configure in IIS, right click and select "Properties" 2) Under HTTP Headers Tab, select "File Types" under the MIME Map section and select "New Type" 3) Type ".flv" as the associated extension and "video/x-flv" as the content type or "flv-application/octet-stream" I'm not sure on which one gives here. 4) for .mp4 files type ".mp4" as the extension and "video/mp4" as the mime type (this one I tested personally) 5) Select "OK", 6) type services.msc, find the "World Wide Web Publishing Service" and click on the restart icon on top or open up and choose restart
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "media, 404 error, media library, videos" }
Are links allowed in the Upgrade Notice section of a plugin's readme.txt file? I'm working on an updated version of an existing plugin. In the readme.txt file, I'll be adding an entry to the "Upgrade Notice" section, which will show up in users' Plugins admin page when the new version gets released. I see from the official readme.txt format that this field is limited to 300 characters. My question is, are links allowed in this field? I would like to link to a forum post about the new version. I realize I could put a URL in the field in any case, but I was wondering if I could put a link in the field using the Markdown syntax and make the link clickable on the users' admin screen.
I haven't confirmed the behavior of the Plugins admin screen, but using the official readme.txt validator, I see that the validator has stripped away the link that I put into the Upgrade Notice section. Judging from that, it looks like the answer is no.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins" }
Adding a gallery to my first theme I have been spending a lot of time the past few months researching on how to create my first theme. That said most tutorials/books only discuss static sites and I want to go about this well prepared. I would like to add a gallery only on my home page. I have already created an HTML5 mockup of the gallery using jQuery so a plugin right now is not an option. 1. I wanted to know if the best way to execute this is to create a custom page and only code my gallery into it? 2. Is there a better alternative?
WordPress has rather convoluted logic for front and home page (which often, but not always are the same thing). It depends on your needs what approach is best to take - for example are you making this as theme for private use or public redistribution, do you want page customized completely or just add elements to it. The documentation materials on this topic are: * Template Hierarchy > Home, Front page display * Creating a Static Front Page
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, themes, gallery" }
How do I avoid having duplicate of plugin in trunk? I published a plugin and then installed it into a test site to check it was published OK. The copy that was installed contains: * plugin.php * readme.txt * trunk/plugin.php * trunk/readme.txt The trunk folder is redundant and other plugins don't seem to come duplicated. How can I avoid the plugin files getting downloaded twice?
I do not know which OS and/or software you use but regarding SVN it's quite simple : $ svn co Then you just have to add your files in trunk and/or maybe in assets (banner,screenshots). Then : $ svn add trunk/* and or : $ svn add assets/* Last step is : $ svn ci -m "initial upload" That's pretty much what I use to release plugins on wordpress.org, hope this will help :)
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, svn" }
Enque Javascript in Footer? I currently enque jQuery like so - how do I move this to the footer instead? // Enque: jQuery if (!is_admin()) add_action("wp_enqueue_scripts", "my_jquery_enqueue", 11); function my_jquery_enqueue() { wp_deregister_script('jquery'); wp_register_script('jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null); wp_enqueue_script('jquery'); }
The fifth parameter is `$in_footer`. You have left that out. Add that parameter, set it to `true`. wp_register_script( 'jquery', "http" . ($_SERVER['SERVER_PORT'] == 443 ? "s" : "") . "://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js", false, null, true ); But I echo the concern expressed by @Andrew in a comment. You can cause yourself trouble by deregistering/replacing the core libraries. ## Reference <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "jquery, wp enqueue script" }
Featured image for news page Is it possible to display a featured image on a news page that uses index.php? I'm currently using wp_query to display posts from a specific category on the news page. Each post has his own featured image which isn't displayed on the index/news page but only for the post itself. If i place `<?php the_post_thumbnail();? >` before the query it displays all featured images for the posts shown on the news page but not the featured image which I've setup for the news page itself. How can I solve this? If it's even possible as the codex says that the featured image is only for post and pages. The news page is a page but uses index.php instead of page.php.
If I am reading your question correctly, the problem is that when you set a page so that it has a an archive Loop on it `$wp_query` and the `$posts` variable are set to for the index Loop and not for the page the are on. To get information about that page you need `get_queried_object`. Two lines will show your featured image. $obj = get_queried_object(); echo get_the_post_thumbnail($obj->ID); One line if your PHP is recent enough echo get_the_post_thumbnail(get_queried_object()->ID); Obviously you will want to do something a bit more complicated to check for errors and avoid notices, but basically that is it. Be careful with `get_queried_object`. It returns very different information depending on the type of page you are on-- index, single, author archive, tab archive, etc.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post thumbnails" }
User defined password at registration - registration email sends auto generated pass Updating some meta fields on registration and providing the user the option to pick a password yet the registration email sends the auto generated password. User defined password works and not emailed pass. add_action( 'user_register', 'jwh_register_extra_fields', 100 ); function jwh_register_extra_fields( $user_id, $password = '', $meta = array() ) { $userdata = array(); $userdata['ID'] = $user_id; if ( $_POST['password'] !== '' ) { $userdata['user_pass'] = $_POST['password']; } $userdata['first_name'] = $_POST['first_name']; $userdata['last_name'] = $_POST['last_name']; $userdata['user_url'] = $_POST['user_url']; $new_user_id = wp_update_user( $userdata ); }
Welcome to WPSE. You can use wp_insert_user, you don't need to hook onto anything. Assuming here they fill out a form with a name, username, email and password field, and you capture it however you want. $name_array = explode(' ',$_POST['name']); $user = array( 'user_login' => $_POST['username'], 'user_pass' => $_POST['password'], 'user_email' => $_POST['email'], 'first_name' => $name_array[0], 'last_name' => $name_array[1], ); $user_id = wp_insert_user( $user ); wp_new_user_notification( $user_id, $_POST['password'] );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "user registration, user meta, password" }
Insert data in custom table during new post creation I want to in insert data in my custom db table when creating a post. Suppose there are three categories (php, wordpress & jquery). When i create a post in wordpress, i want to insert post id and category id in my custom database table. How can i do this job?
You hook a function to `save_post` (for saves and updates) or `publish_post` for publication only. The second hook is really a variable hook of the form `{$new_status}_{$post->post_type}` so it will be different if you aren't dealing with a `post` post type. function do_on_publish_wpse_98177($id) { // your code; $id is the post ID } add_action('publish_post','do_on_publish_wpse_98177'); Make backups and test thoroughly on a development server. It is easy to break things with these hooks. You can use `$id` to pull information from the database including category information. You can also access the `global` `$_POST` if you need it but these hooks run after the post save so if something has altered (another function) the data saved to the database `$_POST` might be out of sync. See also: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, custom post types, posts, wp query, database" }
Reference external file as a function In my functions.php I have the following code: add_action( 'admin_menu', 'jp_create_admin_pages' ); function jp_create_admin_pages() { add_menu_page( 'Members', 'Members', 'manage_options', 'members', 'admin-members.php'); } In the same folder, I have another file called admin-members.php with the following code: <span>Hello Admin World!</span> However, I am getting a PHP error saying that this is an invalid callback (it works when I replace the 'admin-members.php' parameter with the name of a function in functions.php). How can I reference an external file as a callback so that this will work?
You can’t. Create a function that loads that file: function load_admin_page_file() { require 'admin-members.php'; } Then use that function name as callback argument. In PHP 5.3 you can use a lambda: add_menu_page( 'Members', 'Members', 'manage_options', 'members', function() { require 'admin-members.php'; } );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "admin, admin menu, callbacks" }
Why my plugins are updating automatically? I have a wordpress site with a few plugins. I had to make some custom changes on a plugin (not a best practice), and of course I don't want to update that plugin. But for some reason all my plugins have been updating themselves automatically without asking. ( Is that even possible ?!!). I have never had this behavior before. I know that some plugins will show a notification whenever a new version is available and then I must click to update it. My question is: **Is it possible that my plugins are updating without asking?** or perhaps this could be a security issue and I might have an unwanted admin updating the plugins ? \-- Edit -- I think I found my problem. I posted the answer. Thanks for all the others answers, they helped me to rule out other possibilities.
I found my problem: Once I have updated a plugin through the wordpress admin section once, it will continue to update it automatically whenever there is a new version of this plugin. I didn't know this behavior. I was hoping I would need to click the 'automatically update' message on the plugin every time I wanted to upgrade it. I guess i was wrong. Thanks for all the others answers, they helped me to rule out other possibilities.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "security, updates, automatic updates" }
Using one slug/post-name for multiple pages I'm creating a website and I'd like to be able to reuse the same slug/post name in the page's url. ex using `/%category%/%postname%` foo.com/bar/page foo.com/barz/page // Will not work. Instead it will use page-2. I've done some research and it doesn't look like it's possible to do what I want. Before I give up on trying to get the url structure to work like I would like, I figured I would reach out to the WordPress community to see if anything has changed in a newer release to allow this behavior. I'd really like to avoid using `%post_id%` at all costs because I don't think it looks very nice in the url.
This is not natively possible, since in your example permalink structure posts are detected by slug alone, and not combination with category. Essentially category info gets simply discarded. If your requirements involve only one (few) of possible endings for URL you might achieve this _relatively_ easy using endpoints, see `add_rewrite_endpoint()`. However in generic scenario slug collisions won't work.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "permalinks" }
Add <span> within the <li> output of <? wp_nav_menu() ?> Im currently printing out: <?php wp_nav_menu( array( 'theme_location' => 'primary' ) ); ?> Which outputs: <div class="menu"> <ul> <li class="current_page_item">Frontpage</li> <li class="page_item page-item-2">etc</li> </ul> </div> In my original HTML setup ive got an `<span>` within the `<li>` which looks like this: <div id="menu"> <ul> <li> <span> <a href="#">Menu1</a> </span> </li> Any ideas on how to adjust this?
Use the arguments `before` and `after`: wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu', 'before' => '<span>', 'after' => '</span>' ) ); To see how these arguments are used, look at the method `start_el()` in `Walker_Nav_Menu`: $item_output = $args->before; // 'before' $item_output .= '<a'. $attributes .'>'; $item_output .= $args->link_before . apply_filters( 'the_title', $item->title, $item->ID ) . $args->link_after; $item_output .= '</a>'; $item_output .= $args->after; //'after'
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "menus, navigation, walker" }
Programatically add options to "add new" custom field dropdown How can I add pre-defined options to the "add new" custom field dropdown? !enter image description here Here's two examples of automatically adding and showing new custom fields: 1. WordPress: Adding Default Custom Fields on New Posts 2. Auto create custom field That's close to what I want to do; my goal is to add pre-defined options to the "add new" custom filed dropdown, but not have them show as fields until the blogger adds them. I'd like to know how to do this without using a plugin.
You cannot do that with pure PHP, because the fields are fetched from existing fields, and there is no hook. But you can use JavaScript, check if the post type supports custom fields and the field does not exist already – and insert it: <?php # -*- coding: utf-8 -*- /* Plugin Name: Extend custom fields */ add_action( 'admin_footer-post-new.php', 'wpse_98269_script' ); add_action( 'admin_footer-post.php', 'wpse_98269_script' ); function wpse_98269_script() { if ( ! isset ( $GLOBALS['post'] ) ) return; $post_type = get_post_type( $GLOBALS['post'] ); if ( ! post_type_supports( $post_type, 'custom-fields' ) ) return; ?> <script> if ( jQuery( "[value='demo_data']" ).length < 1 ) // avoid duplication jQuery( "#metakeyselect").append( "<option value='demo_data'>demo_data</option>" ); </script> <?php }
stackexchange-wordpress
{ "answer_score": 7, "question_score": 12, "tags": "functions, custom field" }
Enable Minify in W3Total Cache using NGINX I am having an issue with enabling minify with the W3TC plugin. I am using a LEMP stack and cloudfront as a CDN, and all of these features, except for the minify work fine. In order to enable fancy permaplinks in WP I added `/index.php?q=$uri&$args` to the `try_files` line in sites-available and now all of the permalinks are `/index.php/postname/` which I think may have something to do with these errors.
Try using the following for your rewrite rules: location / { try_files $uri $uri/ /index.php$is_args$args; } Using that schema, you can manually remove `index.php` from your Permalinks settings without breaking anything. Nginx will now check any URI for its existence as a file on the filesystem, and then a directory on the filesystem, and if neither of those return a valid entry it hands off the entire URI to index.php to process, complete with any query strings if any are present. For W3 Total Cache, try the following: W3 Total Cache Minify Rewrite Error with Wordpress on nginx
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "permalinks, plugin w3 total cache, nginx" }
Require re-login when logged-in user attempts to access restricted page I need to restrict access to certain frontend pages, based on a user_meta field. All works fine, except when the user is already logged in but with the wrong credentials. In that situation I would want them to be redirected to the login form (with a message encouraging them to logout and login again with suitable credentials - I can do that bit). Instead, the user ends up with the "redirecting in a way that will never complete" message. I think the only bit of my code that's relevant to this issue is: if(!$user_is_approved) { wp_redirect(wp_login_url( get_permalink() )); exit; } What's the best way of achieving this?
Thanks to @s_ha_dum I eventually tracked the issue down to the following line in my `wp-config.php` file... @define('ADMIN_COOKIE_PATH', '/'); Commenting this out solved the problem Ironically, I've tended to include this line as a standard preventative measure against login redirection loops. (Can't remember where I first got this from, but there's some lively debate on the topic here.) I suppose this illustrates the dangers of using magic incantations without really understanding what they're doing..
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "login, wp redirect, content restriction" }
Include WooCommerce 2's prettyphoto scripts on all site pages So when WooCommerce updated to version 2 they replaced the fancybox lightbox scripts with prettyphoto. I would like to use this on all my wordpress site's pages, not just the product pages, but the scripts are only loaded on a product page. I have a jQuery script to add the relevant css class to my image links but I need a filter/hook to make sure the actual scripts are loaded. Can anyone help?
Try adding this to your theme's function.php. It worked for me, hope it helps. // PRETTY PHOTO // add_action( 'wp_enqueue_scripts', 'lightbox' ); function lightbox() { global $woocommerce; $suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min'; { wp_enqueue_script( 'prettyPhoto', $woocommerce->plugin_url() . '/assets/js/prettyPhoto/jquery.prettyPhoto' . $suffix . '.js', array( 'jquery' ), $woocommerce->version, true ); wp_enqueue_script( 'prettyPhoto-init', $woocommerce->plugin_url() . '/assets/js/prettyPhoto/jquery.prettyPhoto.init' . $suffix . '.js', array( 'jquery' ), $woocommerce->version, true ); wp_enqueue_style( 'woocommerce_prettyPhoto_css', $woocommerce->plugin_url() . '/assets/css/prettyPhoto.css' ); } }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "images, hooks, plugins" }
Insert <ul> Into Sub-child Menu This code displays a list of child categories of the parent category while a user is on a child category or single post. The styling around this list is displaying even when a list isn't being generated. Take a look here where you'll see an empty black box \- I've colored it black simply to make it stick out. Not relevant, but this code is impacted by another code in my functions.php. How do I correctly insert the tags into this code and prevent a list from being generated when no child categories exist? <?php $categories = get_the_category(); echo '<ul style="background:#000">'; foreach($categories as $category){ $parent = $category->parent; if($category->parent == 0){ } else{ wp_list_categories("child_of=$parent&title_li"); } echo ''; } ?>
Check that you actually have categories before creating the list, and move the lines that echo the `<ul>` inside the conditional. $categories = get_the_category(); if (!empty($categories)) { foreach($categories as $category){ $parent = $category->parent; if($parent != 0){ echo '<ul style="background:#000">'; wp_list_categories("child_of={$parent}&title_li"); echo '</ul>'; } } } This will generate multiple lists, not just one. Here is a version that `echo`es only a single `<ul>`. $categories = get_the_category(); $catli = ''; if (!empty($categories)) { foreach($categories as $category){ $parent = $category->parent; if($category->parent != 0){ $catli .= wp_list_categories("child_of=$parent&title_li&echo=0"); } } if (!empty($catli)) { echo '<ul style="background:#000">'.$catli.'</ul>'; } }
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "categories" }