INSTRUCTION
stringlengths
11
999
RESPONSE
stringlengths
0
999
SOURCE
stringlengths
16
38
METADATA
dict
wp_users user_status field I have found an answer to my question here but it's 7 years old. I simply want to know if I can use this column for my own purposes. I'm planning to use the `user_activation_key` column to store a hashed key upon user registration and set an inactive flag in the `user_status` column. This flag will prevent users from logging in until their e-mail address has been verified.
As far as I know it isn't used, but to avoid conflicts/problems, other plugins might use it, I'd go with adding a meta to the wp_usermeta table. There is a set of functions for handling that: * add_user_meta() * get_user_meta() * update_user_meta() * delete_user_meta() Shouldn't make a big difference for the functionality you want to implement, but you're on the saver side of things.
stackexchange-wordpress
{ "answer_score": 7, "question_score": 5, "tags": "database" }
foreach loop displaying below content summary I am trying to wrap my result with `<li>`, but when I do so as in the code, I get funny results, as the result display way below. do_action( 'woocommerce_after_shop_loop_item' ); $value = get_the_terms( $product->id, 'pa_package'); foreach ( $value as $values ) { echo "<li>"; echo $values->name; echo "</li>"; }
You can hook into the action like this: **Code:** add_action( 'woocommerce_after_shop_loop_item', 'wpse124226_wc_product_attribute_list' ); function wpse124226_wc_product_attribute_list() { $value = get_the_terms( $product->id, 'pa_package'); echo "<ul>"; foreach ( $value as $values ) { echo "<li>"; echo $values->name; echo "</li>"; } echo "</ul>"; } Take a look at the codex Plugin API to inform yourself about using hooks. BTW you can use woocommerce functions to get the attributes, especially `get_attributes`, take a look at the source at the woocommerce documentation. For an use-case take a look at the product-attributes.php file.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins" }
Too few arguments for printf() I'm having a problem making this printf print the time & date correctly within my theme. I keep getting "Too few arguments." <span class="entry-date"><abbr class="published" title="<?php the_time('Y-m-d') ?>"><?php unset($previousday); printf( __( '%1$s &#8211; %2$s', 'erudite' ), the_date( '', '', '', true ) ) ?></abbr></span> I have two strings in the printf(). %1$s and %2$s are meant to correspond to the_time and $previousday. Is: <?php the_time('Y-m-d')?> not serving here as a printable string? Or did I not form this correctly? Am I missing something obvious/subtle? It's been many years since I coded in PHP, and I'm rusty. TIA.
printf( __( '%1$s &#8211; %2$s', 'erudite' ), the_date( '', '', '', true ) ) expects two strings; you've only offered one (`the_date()`). If you want to use two strings, you have to give it two strings. If you want `printf()` to use `the_time()` and `$previousday`, you need to _tell_ it so: printf( __( '%1$s &#8211; %2$s', 'erudite' ), get_the_time(), $previousday ); for instance.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, errors" }
The Events Calendar Plugin - List View Background Colour Issue I'm trying to look for some help, I've got a WordPress website that I'm working on. I'm using this plugin called **The Events Calendar** , but in List View, the background keeps showing in transparency... Would somebody be able to help me trigger and find where in the code I can change the background color instead of having it in transparency? Here is the link: <
If I understand you correctly, you can add this code to #tribe-events-content.tribe-events-list in your stylesheet like so: #tribe-events-content.tribe-events-list { margin-bottom: 60px; background: #FFFFFF; /* ADD A BACKGROUND COLOR HERE */ } That will add a background to the Upcoming Events section so that the text is more easily readable. Here's a screenshot of the change.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, plugin development, jquery, css" }
Shortcode return $content vs do_shortcode($content) I think the title of my question says it all. When creating a shortcode, I've seen some people do `do_shortcode($content)` instead of `$content`. What is the difference? Another thing, let's say I have a shortcode `[hello]World[/hello]`. Wouldn't returning `do_shortcode($content)` result in `do_shortcode('World')`? From the codex, the examples given are as such, `do_shortcode('[hello]')` So what will returning `do_shortcode($content)` interpret? (in the case of `[hello]`) Any practical examples or clear explanations would be greatly appreciated. Thanks.
This is useful if you don’t know if the `$content` contains unknown shortcodes. Example **Your shortcode** add_shortcode( 'foo', 'shortcode_foo' ); function shortcode_foo( $atts, $content = '' ) { return 'Foo!' . do_shortcode( $content ); } Now your user might write something like this: [foo][bar][/foo] You have no idea what `[bar]` does or that it even exists. So you let WordPress handle that per `do_shortcode()`. If you don’t do that, `[bar]` will not be parsed as shortcode and showed as is instead.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "shortcode" }
How to turn off searching from URL and go straight to 404 page When I put something after my domain name that doesn't exist I am taken to my 404 page, for example: example.com/sdkjhfdsjk But if I put something that exists as an image I am taken to the page for that, for example: example.com/imagename How can I turn this off. I only want to be taken to pages or posts that exist. UPDATE: This has been marked as a duplicate but the accepted answer to that does NOT fix this. I added: remove_action('template_redirect', 'redirect_canonical'); to my themes `functions.php` but the same action happens.
Try function no_attachment_page() { global $wp_query; if ( $wp_query->is_attachment() ) { $wp_query->set_404(); status_header(404); nocache_headers(); } } add_action( 'template_redirect', 'no_attachment_page', 1 ); This should result in a 404 everytime you try to access to an attachment page.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "url rewriting, search" }
Get $curauth level I am trying to get the user level of the author that is displayed on an author page (not the current user that is logged in, but the user that is presented on the current author page that I am viewing) I am using this code <? get_currentuserinfo() ; global $user_level; if ($user_level >= 4) { include (TEMPLATEPATH . '/author_1.php'); } else { include (TEMPLATEPATH .'/author_2.php'); } ?> I tried to replace $user with $curauth but still no results, it is showing only one template for both. Any ideas? thank you
toscho is correct. User levels have been deprecated for a long time now. However, the following will get you the available information about the author of the posts on an author archive page. $author = get_queried_object(); var_dump($author); In that dump you should see everything you need, but use the `role` not the user level-- look in `$author->roles`. For example: $author = get_queried_object(); $allowed = array('author','editor','administrator'); $roles = array_intersect($author->roles,$allowed); if (!empty($roles)) { include (TEMPLATEPATH . '/author_1.php'); } else { include (TEMPLATEPATH .'/author_2.php'); } You should also almost certainly be using `get_template_part` instead of `include`.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "author template" }
Make a plugin work on specified domain only I am developing a custom WP plugin for a client and I wish to make sure that the client does not install it on any other domain other than the one specified. If the client tries to install the plugin on other domains, it should throw out an exception and plugin should get deactivated or self destruct. How can I make this happen? What is the code for this and where do I add it? Thanks!
You could use a combination of the file content and the domain to create a unique hash. Example: $md5 = md5( file_get_contents( __FILE__ ) . $_SERVER['HTTP_HOST'] ); if ( 'be5d38f32a5d4a897e6c878f0c2f1b14' !== $md5 ) deactivate_plugins( plugin_basename( __FILE__ ) ); Additionally, you could check each week per remote request to your server, if the hash is registered for that domain. But be aware, this can be changed very easily. There is just no way enforce a domain.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "plugins, domain, licensing" }
How do you make your theme Child Theme-able? I'm sorry if this is an obvious question, but I've tried looking everywhere and can't seem to find an answer. Are WordPress themes automatically Child Theme-able? Or is there a process to make a theme ready for Child Themes?
Few things have already been discussed here I would like to add more In order to make your theme a good parent you also need to consider in following things: * make your functions and classes pluggable ie, wrap your theme functions with `function_exists` wrapper so that they can be overridden in child pages. if ( ! function_exists( 'theme_entry_date' ) ) : function theme_entry_date(){...} endif; * provide action and filter hooks generously
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, child theme" }
If statement for admin page How should I write `if` condition to display specific code only when I enter this page: /wordpress/wp-admin/post-new.php?post_type=slideshow This is what i was trying to get ;) Thanks to Krzysiek! function plu_admin_enqueue($hook) { $screen = get_current_screen(); if ( 'post.php' == $hook && $screen->post_type == 'slideshow' ) { wp_enqueue_script('plupload-all'); wp_register_script('cplupload', get_template_directory_uri() . '/js/cplupload.js', array('jquery')); wp_enqueue_script('cplupload'); wp_register_style('cplupload', get_template_directory_uri() . '/css/cplupload.css'); wp_enqueue_style('cplupload'); }; }; add_action( 'admin_enqueue_scripts', 'plu_admin_enqueue', 10 );
I would use `get_current_screen();` to do this. It returns a WP_Screen object. You should remember that this function will return NULL if it's called before `admin_init` action. In your case it should look like this: $screen = get_current_screen(); if ( $screen && $screen->action == 'add' && $screen->base == 'post' && $screen->post_type == 'slideshow' ) { // do your stuff }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "admin" }
Buddypress get data from wp_bp_groups_members table I have added a new column to 'wp_bp_groups_members' table it's called 'relationship'. Now I want to get data from that column. I have to pass user_id and group_id to get that data.
Simpler solution: function get_relationship($group_id,$user_id) { global $wpdb; $relationships = $wpdb->get_col("SELECT relationship FROM wp_bp_groups_members WHERE group_id = $group_id AND user_id = $user_id"); if ( !empty( $relationships ) ) { foreach ( $relationships as $relationship ) { return $relationship; } } } And it should go in plugins/bp-custom.php or your-theme/functions.php. Not bp-groups-template.php, which is a core file and should not be hacked.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "buddypress" }
Woocommerce: how to change 'Cart Updated' message I've spent several hours trawling for a solution to what would seem to be a fairly straighforward issue - but with no joy. Any help on this would be massively appreciated. I'm using my own custom theme with Woocommerce. I'd like to be able to change the message text that appears when a user updates their cart from 'Cart updated' to 'Basket updated'. **Please note:** this is the message shown when a user changes the quantity of a product within the cart, and selects 'Update Cart'. I already know how to change the text of the 'Add to Cart' button, and also the message shown when an item is added to the cart ('Item was successfully added to your basket'). Any help would be very gratefully received. Thanks.
WooCommerce is heavily localised, so you can make use of WordPress' localisation functions to change its messages. add_filter('gettext', 'wpse_124400_woomessages', 10, 3); /** * change some WooCommerce labels * @param string $translation * @param string $text * @param string $domain * @return string */ function wpse_124400_woomessages($translation, $text, $domain) { if ($domain == 'woocommerce') { if ($text == 'Cart updated.') { $translation = 'Basket updated.'; } } return $translation; }
stackexchange-wordpress
{ "answer_score": 9, "question_score": 0, "tags": "plugins" }
Posting error with P2 theme I'm getting the error: "Whoops! Looks like you are not connected to the server. P2 could not connect with WordPress." when trying to reply to comments/posts on P2, I'm on v1.5.2 Anything I can do to fix this?
This may be an issue with permalinks and Ajax. If so, the solution is simply to refresh your permalinks, by visiting `Settings -> Permalinks` in your admin, and clicking "Save".
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "theme p2" }
the correct way to use options from settings page I'm creating a plugin in Wordpress and am a little confused how I should use settings I set in my settings page. I used: < to create my settings page. All fine, it's saving the options into the options table. I can echo them out but the only way I can get it to do it is with: $value = get_option('my_option_name')['my_option']; echo $value; This doesn't seem a very nice way of doing it to me, and Netbeans gives me a red line under the code saying it's not compatible with my version of PHP, it works but this surely isn't the way I'm supposed to echo out values from my settings page is it?
`get_option( $option )` returns an array. You need to get access to that array, and _then_ get the keys/values inside of it. Try this instead: $value = get_option( 'my_option_name' ); echo $value['my_option'];
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin development, options" }
When to add_filter() to Custom Query I have complicated query where I need to join multiple tables. I'm doing that via `add_filter('posts_join')` \- my question is, when and where do I add the filter so that it only applies to the custom query? My Custom Query $test = new WP_Query(array('post_type' => 'artcpt', 'posts_per_page' => 10, 'tax_query' => array(array('taxonomy' => 'arttax', 'field' => 'id', 'terms' => array(20,41,16))))); Should I physically add the filter above the query or after? Do I need to put it into a separate file (function.php) and attach it another way? Do I need to do something with `query_vars`?
You want to add your filter before you create the query: add_filter( 'posts_join', 'custom_posts_join' ); $test = new WP_Query( $args ); where you can define the filter callback in your theme files, for example `functions.php` or in a plugin: function custom_posts_join( $join ) { // modifications // $join = ... // remove the filter remove_filter( current_filter(), __FUNCTION__ ); // return the result return $join; } Notice that we remove the filter with this line: remove_filter( current_filter(), __FUNCTION__ ); so it will not affect other queries.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "wp query, filters" }
Need To Deregister Scripts Via Functions.Php Well, I am a little disappointed how difficult Wordpress it makes to deregister scripts. First, I got a list of all handles, so I looked it up and the handle was jquery-migrate I then added this to my functions.php wp_dequeue_script('jquery-migrate'); Also this wp_dequeue_script('jquery'); It does nothing, although the scripts are properly registered. What's up with the version strings, I can think of no reasons why they are still including those, should be removed in the next WP version asap, they only prevent caches from properly caching it in some cases and are annoying. Any input on how to "properly" deregister scripts is appreciated.
Ok the following does work now, I think it was a caching issue and I forgot to add the correct priorities Using the priorities now it definitely works and I also managed to de-register Buddypress scripts add_action( 'wp_print_scripts', 'de_script', 100 ); function de_script() { wp_dequeue_script( 'jquery' ); wp_deregister_script( 'jquery' ); wp_dequeue_script( 'bp-legacy-js' ); wp_deregister_script( 'bp-legacy-js' ); }
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "jquery" }
Function that outputs second theme url I have a multisite and need a function (added to functions.php) that will get the template url of the second theme (probably by name or other identifier)? Example: theme-1 (used by main site) contains function to get url of theme-2 (theme-2 is used by sub-sites) Thanks
You can use two inbuilt functions to do this. 1. switch_to_blog 2. get_stylesheet_directory_uri You can use both in the following way to make a function out of it which would give you the url to the theme. Put the below in the **`functions.php`** file function wpse_get_theme_url( $blog_id = 1 ){ switch_to_blog( $blog_id ); $template_url = get_stylesheet_directory_uri(); restore_current_blog(); // Switch back to the original blog return $template_url; } Now you can use the above function to fetch the url by using the function and passing the blog id/ sub site id. $theme_url = wpse_get_theme_url( $blog_id ); // Replace the $blog_id with blog id of your sub sites.
stackexchange-wordpress
{ "answer_score": 4, "question_score": 0, "tags": "functions, multisite, themes, directory" }
how to remove the default title of Categories widget hi i'm using the Categories widget show hierarchy. I leave the space for title because I don't need to show any title. but it then displays on the website as "Categories". how can I remove that?
There is a filter you can use to do this. (Kruti has even found it, but instead of using it, he modified core files...) $title = apply_filters('widget_title', empty( $instance['title'] ) ? __( 'Categories' ) : $instance['title'], $instance, $this->id_base); So what you really need to do, is to add this to your functions.php: function my_repair_categories_empty_title($title, $instance, $base) { if ( $base == 'categories' ) { if ( trim($instance['title']) == '' ) return ''; } return $title; } add_filter('widget_title', 'my_repair_categories_empty_title', 10, 3);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "categories, widgets, title" }
Permalink for pages As you know we can change the post permalink as we want /%postname%.htm -->/mypostname.htm Can we do the same for the pages also? /%pagename%.htm -->/mypagename.htm permalink for the pages is %pagename% whe we use the custom permalink for the post.
Permalinks work for everything, pages, posts, etc... Have a look at <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "permalinks, pages" }
User registration on subsite in multisite configuration As a network admin in multisite configuration, I have the option to enable or disable the user registration \ site registration. is there any way i can enable the user registration on s single sub site , not on all sites. In my WP setup, I have a main blog which is managed by me and I dont want user to register here. i have a another blog installed on sub directory dedicated for forum. I would like to enable user registration here, so that user can use the forum
The multisite setup allows you to enable and disable user registration at the network level but if you see the database it store the value in the **`wp_options`** tables for each site. So we can try the below and see if this work. Use the below code in the **`functions.php`** file. function wpse_enable_user_registration( $blog_id = 1 ) { switch_to_blog( $blog_id ); // Fetching the present option $user_registration_option = get_option( 'users_can_register', 0 ); if( '0' == $user_registration_option ) $site_registration_option = update_option( 'users_can_register', 1 ); restore_current_blog(); // Switches back to the original blog return $site_registration_option; } If the updation is successful, you will get `true` else `false` Now you can use the function to enable any subsites in the MU setup by passing the sub sites `id` to the function in place of `$blog_id`
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "multisite, multisite user management" }
How to add custom Types to navigation menu I'm using the Types plugin, and I created some custom types, linked to custom fields. It appears in the admin menu, and I can create new entries. But on the FO, how can I link my Custom type to a menu item ? When I go to theme->menu, I can select individual entry of my custom Types, but not the custom Types itself, so that its displays a page with the liste of all my entries in it. I could simulate it with categories, but it should be a more automatic way, no ?
You can use Post Type Archive Link plugin. After enabling it, go to appearence->menu and you will have the option to add the post type archive link on your menu.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugin types" }
Ensure an external javascript file called from plugin is loaded after jquery is called I am calling a javascript file from my wordpress plugin code using: add_action('init','gallery_sugar_js_init'); function gallery_sugar_js_init() { wp_enqueue_script( 'gallery_sugar_js', plugins_url( '/js/gallery_sugar.js', __FILE__ )); } But in source code for WordPress I'm seeing this (my javascript file loading first): <script type='text/javascript' src=' <script type='text/javascript' src=' How do I make sure jquery is loaded first in my Wordpress plugin file?
Try this: add_action('init','gallery_sugar_js_init'); function gallery_sugar_js_init() { wp_enqueue_script( 'gallery_sugar_js', plugins_url( '/js/gallery_sugar.js', __FILE__ ), array( 'jquery' ) ); } Check Function Reference for more info.
stackexchange-wordpress
{ "answer_score": 1, "question_score": -1, "tags": "jquery, javascript" }
Remove "show sharing buttons" metabox Jetpack from custom post type I have installed Jetpack and now my custom post types feature a meta-box that says "Sharing: Show sharing buttons" with a checkbox. This is unnecessary for this custom post type and I would like to remove it altogether (not just hide it via screen options). I tried adding add_action( 'init', array( $this, 'my_remove_filters_func' ) ); function my_remove_filters_func() { remove_all_filters( 'the_content', 'sharing_display',19 ); remove_all_filters( 'the_excerpt', 'sharing_display',19 ); } however it doesn't seem to be working
you can try this if (is_admin()){ function my_remove_meta_boxes() { global $typenow; if( 'YOUR_CUSTOM_POST_TYPE' == $typenow ) { remove_meta_box('sharing_meta', 'YOUR_CUSTOM_POST_TYPE', 'high'); } } add_action( 'admin_menu', 'my_remove_meta_boxes' ); } Which removes the metabox registered by the jetpack plugin. Just make sure to change `YOUR_CUSTOM_POST_TYPE` with the actual name of your custom post type.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom post types, metabox, plugin jetpack" }
How to *disable* the post content editor Any good ideas on how to _disable_ the post content editor? I don't want to hide it, remove it, or remove the page. The goal is to allow users with few permissions to view the edit screen so they can read the content, but not be able to make changes to the content. (I also need to figure out how to disable other elements on the page, but one step at a time). I've done this with Javascript already by just targeting the textarea and added `disabled`, but looking for a less flimsy method. Background for why I need this: <
I think the best way is remove it and then print the content out of any textarea, but just as html: add_action('load-post.php', 'read_only_content'); function read_only_content() { if ( ! current_user_can('manage_options') ) { // change the cap with the wanted one $scr = get_current_screen(); remove_post_type_support( $scr->post_type, 'editor' ); add_action('edit_form_after_editor', 'print_the_content'); } } function print_the_content( $post ) { echo '<h2>' . __('Post Content:') . '</h2>'; echo '<div id="content" style="width=99%;margin:15px 0;padding:1%;border:1px solid #aaa">'; echo apply_filters('the_content', $post->post_content); echo '</div>'; }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 2, "tags": "editor, post content" }
Custom ajax call returns 0 I' am still searching on why am getting 0 when doing a ajax call on wordpress. I know that when a ajax call is successfull it returns 0. I' am returning some value from the ajax call and it returns 0 with it. Here's my code Javascript $.ajax({ url: "/wp-admin/admin-ajax.php", type: 'POST', data:{ action: 'registerform', name: 'John', age: '38' }, success: function( data ){ alert(data); } }); PHP Function function registerform(){ echo $_POST['name']; } add_action('wp_ajax_registerform', 'registerform'); add_action('wp_ajax_nopriv_registerform', 'registerform'); Above Code returns John0 Please help?
Modify your registerform() function to include die() after you echo your response. Example: function registerform(){ echo $_POST['name']; die(); } add_action('wp_ajax_registerform', 'registerform'); add_action('wp_ajax_nopriv_registerform', 'registerform');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "php" }
Wordpress query_posts by tag doesn't work anymore(?) I had this code running fine forever. Some days ago it just started outputting nothing (just the `<ul></ul>`). No errors in logs: <ul style="margin-left:0"> <?php query_posts('tag=pp&showposts=4'); ?> <?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?> <li><a href="<?php the_permalink(); ?>" title="<?php the_title(); ?>"><?php the_title(); ?></a></li> <?php endwhile; ?> </ul> Of course there are posts with that tag.
Turns out it was a problem of the plugin "The Events Calendar": _<
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, wp query, query posts, tags" }
Wordpress postmeta: Store data as an array or single item? I know it could be difficult to query a single item that saved in an array in wordpress postmeta table, but I have lots of metadata for a single post which may create too many rows for the postmeta table. So, I guess it might be better to save the meta in an array for each post, then, create an object to query the meta so that I can access the data by `$obj->meta1.` My question is: 1. Will it be really bothering when the postmeta table has too many rows? 2. Does saving data as array really solve my doubts?
1. Unless you are building a heavy web application, with billions of rows ( and maybe even then ), the number of rows for MySQL is not an issue. 2. Saving your data in an array will make calling the data simpler (just one call), and keep the database smaller, but it will make parsing and searching through the data more complicated. More often than not, simple and efficient searching greatly outweighs the benefits of a smaller database.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "post meta" }
Modify a parent theme's PHP file, and save in child theme I'm working with a paid theme, and we're using a child theme to display a slightly different design. The parent theme has a file called /includes/forms/register-form.php I'd like to customise this file, and save it in my child theme. How do I tell Wordpress to use my child theme's version of this file, instead of my parent theme's version?
Just copy register-form.php from your parent theme and paste it under yourchildtheme/includes/forms/register-form.php , from there start changes what you want and wordpress will use that file.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "child theme" }
How to setup a wordpress backup in localhost? I have a database backup and entire site folder backup of a wordpress site. I want to setup it in my localhost. These are the steps I followed. 1. Create a database 2. Import the database_backup.sql 3. Open the wp-config.php and edit the following details > define( 'DB_NAME', 'contents_wp' ); > > define( 'DB_USER', 'root' ); > > define( 'DB_PASSWORD', '' ); > > define( 'DB_HOST', '127.0.0.1' ); But I cannot log in to the admin panel. It redirects to the live site. How to solve this? What I am doing wrong here? Any suggestions will be appreciated.
Before import database_backup.sql. You have to replace server url with your local url in sql. for example: you took backup from abc.com , and your local url is localhost/abc .then open database_backup.sql and find and replace abc.com with localhost/abc. Save and import now.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "backup, local installation" }
If custom field is empty, use one from a previous post Let's say you have a few custom fields (I use the advanced custom fields plugin for it). There is an extra field in posts called 'afbeelding_onder'. It is not required but on `index.php` within the loop the custom field 'afbeelding onder' from the last post will be printed. If it is possible, is there a way to check if the custom field is empty, if it isn't than it will print the value, but else (when the custom field is empty) the value of the last post which contains a value in that box will be printed. Hope my question was clear enough, my English grammar is not that good.
if(!get_field('afbeelding_onder')) { $prev_post = get_previous_post(); echo '<p>' . get_field('afbeelding_onder', $prev_post->ID) . '</p>'; } else { echo '<p>' . get_field('afbeelding_onder') . '</p>'; } not tested. you might want to include a while loop, if the previous post does also not have that value set?
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, custom field, loop, advanced custom fields" }
JS script not being included I am trying to enqueue a js file in functions.php but its not working. Following is my code add_action('init','shopswing'); function shopswing(){ if(!is_admin()){ wp_register_script('swing',get_stylsheet_directory_uri(). '/js/swing.js',array('jquery')); wp_enqueue_script('swing'); } } and somehow, my site stop responding when i include the code of swing.js jQuery(document).ready(function() { $("ul>li>img").mouseenter(function(){ $(this).parents("ul") .find(".toolTip") .animate({ 'height':'200px'}) //.css({"display":"block"}); }) .mouseout(function(){ $(this).parents("ul") .find(".toolTip") .animate({ 'height':'0'}) //.css({"display":"none"}); }); });
found the problem! The problem was with the name of function, i am using woocommerce and i think the function name conflicted, changed it and it working!
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "jquery" }
How to disable W3 Total Cache “Performance” menu under multisite? I came across the following article W3 Total Cache - How to disable “Performance” menu under multisite? However on testing it with the latest version of WordPress 3.7 and W3 Total Cache v0.9.3 it seems to no longer work. How can I update the code from the link above so it works I also have the following code which works it removes the “Performance” from the admin top bar //Remove Performance function ds_w3tc_remove_adminbar() { global $wp_admin_bar; if ( ! is_super_admin() ) { $wp_admin_bar->remove_menu('w3tc'); } } add_action( 'admin_bar_menu','ds_w3tc_remove_adminbar',999);
Please try to remove it with the menu slug `'w3tc_dashboard'` instead of `'w3tc_general'`: i.e. use remove_menu_page( 'w3tc_dashboard' ); instead of remove_menu_page( 'w3tc_general' ); in the linked code example.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 1, "tags": "multisite, plugin w3 total cache" }
Limit username to specific characters (A-Z and 0-9) How do I limit the username field upon registration to `A-Z` and `0-9` for single site? So no spaces, hyphens, underscores, dots etc.
Using the regex posted by **Moaz** (and adding capitals), we will need to hook into the `registration_errors` filter: // Restrict username registration to alphanumerics add_filter('registration_errors', 'limit_username_alphanumerics', 10, 3); function limit_username_alphanumerics ($errors, $name) { if ( ! preg_match('/^[A-Za-z0-9]{3,16}$/', $name) ){ $errors->add( 'user_name', __('<strong>ERROR</strong>: Username can only contain alphanumerics (A-Z 0-9)','CCooper') ); } return $errors; }
stackexchange-wordpress
{ "answer_score": 4, "question_score": -3, "tags": "user registration, limit, username, characters" }
Taxonomy term breadcrumb; how? Given a taxonomy term (perhaps in a taxonomy*.php template) how to construct a breadcrumb going up the full ancestry of the term? Is there any shorter way other than a "brute-force" loop to query current term's parent -> query term's parent -> query term's parent etc.?
You can use `get_ancestors` for this: get_ancestors( $term_id, 'taxonomy' ); Of course this will only work on hierarchical elements. Additionally, this will only work reasonably well if only one term per level is assigned, take a look at my comment here and my answer here to get a little bit deeper insight into that.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "custom taxonomy, taxonomy, hierarchical, terms, breadcrumb" }
Should I create multiple sidebars, or use or one dynamic sidebar with logic to determine it's abilities? I am wondering what the standard procedure for Sidebars in WordPress. My theme needs to have 3 different types of sidebars, to be used on three different pages. I am wondering if I should create a seperate sidebar for each of these pages or use logic, to determine which form it will take? As stated earlier each sidebar will have different uses for each page template it is on.
Create separate sidebars for each page unless all of them are supposed to display the same set of widgets. I guess you will be managing your sidebar widgets through Appearance Widgets Screen (which displays all registered widgets) so just use register_sidebar() three times or preferably register_sidebars() (set _number_ to 3) within your functions.php file and then you're ready to put these in your template files: <?php dynamic_sidebar( 'id-of-your-first-sidebar' ); ?> <?php dynamic_sidebar( 'id-of-your-second-sidebar' ); ?> <?php dynamic_sidebar( 'id-of-your-third-sidebar' ); ?> Hope it helps. I might be wrong but I don't really see a point in creating one sidebar and using logical operators to modify them.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, sidebar" }
Wordpress include scripts and style in plugin page I am working on a Wordpress plugin where I want to include some jquery scripts and stylesheet. I found dit piece of code in an article and this should do the job, but it doesn't work for me. Can someone tell me what I am doing wrong? // Include files function my_scripts() { wp_enqueue_script( 'jquery' ); wp_register_style( 'filename.css', plugins_url('filename.css', __FILE__) ); wp_enqueue_style( 'filename.css' ); } add_action('wp_enqueue_scripts','my_scripts');
`wp_enqueue_scripts` is a front-end hook. It will not execute on the back-end. You need to use `admin_enqueue_scripts` instead. This is even mentioned on the Codex page just refrerenced. See also: <
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "plugins, wp enqueue script, wp enqueue style" }
Broken theme, template is missing I'm beginning to learn theme creation, so I have created a simple theme: my_theme css style.css images logo.png index.php Why does it appear as a broken theme ("missing template") in WordPress? `style.css` : /* Theme Name: Kaoka Description: Theme personnalise pour le site Kaoka Version: 0.1 Author: Agence Nature / Brunet Production */ * { border:0px; } `index.php` : <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Mon premier tutoriel</title> <link rel="stylesheet" href="<?php bloginfo('stylesheet_url'); ?>" type="text/css"> </head> <body> <h1>Bienvenue sur le site <?php bloginfo('name'); ?></h1> <p><?php bloginfo('description'); ?></p> </body> </html>
Your CSS file should be in the root of your theme, not in a folder Edit: in case I wasn't clear, you need to take the CSS file out of the css folder, and place in the my_theme folder itself. It should be on the same depth as index.php
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "theme development, templates, css" }
Style wp_list_categories I think this is a fairly simple question and im sorry if it is but how would I add a `<div>` to each individual category within this code: <?php $taxonomy = 'category'; // get the term IDs assigned to post. $post_terms = wp_get_object_terms( $post->ID, $taxonomy, array( 'fields' => 'ids' ) ); // separator between links $separator = ','; if ( !empty( $post_terms ) && !is_wp_error( $post_terms ) ) { $term_ids = implode( ',' , $post_terms ); $terms = wp_list_categories( 'title_li=&style=none&echo=0&taxonomy=' . $taxonomy . '&include=' . $term_ids ); $terms = rtrim( trim( str_replace( '<br />', $separator, $terms ) ), $separator ); // display post categories echo $terms; } ?> I want to add `<div class="btn-standard">` to each category. Please note that I only want to display the categories relavent to the post.
My suggestion. $categories = get_the_category(); $output = ''; if($categories) { $output = "<ul>"; foreach($categories as $category) { $output .= '<li><div class="btn-standard"><a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a></div></li>'; } $output .= "</ul>"; } echo $output; You can check Codex for more reference.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "categories" }
How to limit the number of results for all query_posts on mysite I have a huge number of posts and the pagination with no limits eats my server CPU and ram so I need a function to limit the number of posts for all `query_posts` on my site and I need this function to work in the admin area too if possible, any suggestions?? function limit_posts { $args = array( 'posts_per_page' => 10, 'post_type' => 'job_listing', ); global $wp_query; $wp_query = new WP_Query( $args );
It is not that hard to enforce a hard limit on results: add_action( 'post_limits', function($limit) { $limits = explode(',',$limit); if (isset($limits[1]) && 2000 < $limits['1']) { $limits[1] = 2000; } $limit = implode(',',$limits); return $limit; } ); I would not be surprised if that does not solve your problem though. Just searching over that many posts may be too much for your server, no matter what the limit is on the returned results. I am also not 100% sure that that will not break things. Be careful. You could use `'no_found_rows'=>true` for any queries that do not need pagination. That might help. Ultimately, I suspect that you are just doing too much for your server and/or you need someone who is very, very good with server configuration to help you tweak settings and possibly load balance.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, php, functions, query posts, limit" }
Can't see custom field after the Loop I have created a loop to show some products on my wordpress site and they seem to be working fine they reel out the products however if I place one of custom fields after the loop it doesn't show. I know its not an issue with the custom field itself as it works fine if I put it above the loop. Does anyone know where I could be going wrong? Here is my code: < Thanks
When you output your `get_posts` results and do this: setup_postdata($post); You overwrite the original value of `$post` which `the_field` uses to fetch the field data. It's trying to get that field belonging to the last post in `$products_mono_posts` instead of the page that the field actually belongs to. After running custom queries where the value of the global `$post` is modified, you need to call `wp_reset_postdata()` to restore the value of `$post` to its original value.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "loop, advanced custom fields" }
Dynamic Wordpress Admin Panel I would like to create a customized Wordpress admin panel that changes based on the user's log in credentials. For example, if the site administrator logs in from the WP-Admin page, they would be directed to a full suite of administrative options in their admin view. If User Type A logs in from the WP-Admin page, they would see a limited set of custom options in their admin panel. User Type B would see a different set of admin option from Type A, and so on... How can I create a dynamic WP-admin panel using Wordpress? Thanks,
WordPress admin pages are typically created using `add_menu_page()` function that takes care of menu entry and calls custom function (provided by you) to generate content of the page. Obviously content of the page is arbitrary and should be easy to modify conditionally, using `current_user_can()` or other necessary checks.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin, wp admin" }
Show latest custom post types on dashboard I am using this code which shows latest posts on my dashboard but it doesn't work for custom post types. Would appreciate how to modify code. function wps_recent_posts_dw() { ?> <ol> <?php global $post; $args = array( 'numberposts' => 5 ); $myposts = get_posts( $args ); foreach( $myposts as $post ) : setup_postdata($post); ?> <li> (<? the_date('Y / n / d'); ?>) <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li> <?php endforeach; ?> </ol> <?php } function add_wps_recent_posts_dw() { wp_add_dashboard_widget( 'wps_recent_posts_dw', __( 'Recent Posts' ), 'wps_recent_posts_dw' ); } add_action('wp_dashboard_setup', 'add_wps_recent_posts_dw' ); In terms of database performance is this function going to be a strain or I shouldn't worry that much?
This is because by default the paramater for `post_type` is `post`. To include all the post type add the below to you arguements $args = array( 'numberposts' => 5, 'post_type' => 'any' ); The above will include all the post_types including pages and custom post types and if you would to include specific post types use an array like $args = array( 'numberposts' => 5, 'post_type' => array( 'post', 'movie', 'book' ) ); For more details check the **codex**
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions" }
Can I use a space in an option name/key? Is there any reason at all that I can't use a space in a WP option name/key? Ex. `update_option( 'my option name', 'abc' );` I can't find anything that states I can't, but every example uses an underscore instead. I want to know if using a space will actually break anything now or in the future.
Other than general WordPress practice (< which encourages spaces to always be replaced with - in file names and _ for other purposes, there isn't a set reason that you can't use spaces in an option name. From my tests, there is no technical reason to limit you from using a space. (edit) looking further, the SQL is: $row = $wpdb->get_row( $wpdb->prepare( "SELECT autoload FROM $wpdb->options WHERE option_name = %s", $option ) ); so any escaped value should work but just to be safe, you should always use esc_sql() as it doesn't do it specifically.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "options" }
What is an "Options Framework" for Wordpress I am exploring a couple options frameworks for wordpress like the Redux Framework. As a non-developer interested in maintaining my own Wordpress based web app, when would an options framework like Redux be useful? Most sites for options framework market their tool to the wordpress developer community. I have not found a simple explanation geared toward non-developers or newbies that clarifies when an options framework should be used. < Thanks,
An options framework is designed to make the creation of settings pages for plugins and themes easier. An options (or settings) page is a page in the WordPress Dashboard where the behavior of the theme or plugin can be controlled. For example, themes will often have a settings page to setup color schemes, logos, and other similar options. WordPress core (the main base software) has a system for setting up option pages, but it is a bit clunky and can be difficult for developers to get the hang of. Option frameworks, such as Redux, aid developers in the creation of their settings pages by making it much simpler to setup the settings.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "wp admin, options, framework" }
Display count of new members registered today I would like to display the registered members count for today in BuddyPress. Something like: **20** new members registered today I have no clue where to start, so I cannot provide any code yet :(
function bp_registrations_today($activated = false) { global $wpdb; $query = "SELECT COUNT(ID) FROM {$wpdb->prefix}users WHERE DATE(user_registered) = CURDATE()"; if ( $activated ) { $query .= " AND user_status = 0"; } return $wpdb->get_var($query); } To get the number of users registered today, call the function as echo bp_registrations_today(); To get the number of users registered today with activated accounts, call the function as echo bp_registrations_today(true);
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "buddypress, count, members" }
How to restore deleted pages/posts? I recently deleted some pages in my wordpress site. Now I want to re-store them. How can I do this? Any suggestions will be appreciated. Thanks in advance
Then you should see a link "Trash" on the top of pages/posts listing section. * Click on that link which will take you the section where all the trashed pages/posts are listed. * Select the pages/posts using the checkboxes against them. * Select `Restore` from `Bulk Actions` dropdown, then hit the `Apply` button. * Now go to pages/posts listing section and you should see the trashed pages/posts published again.
stackexchange-wordpress
{ "answer_score": 11, "question_score": 4, "tags": "get posts, customization" }
Installing multisite network admin on sub-domain I was searching the Net and also playing around Wordpress to achieve my desired multisite installation, but I wasn't successful yet. What I want to do is to have the network admin site installed on a sub-domain like `www.example.com` (not `example.com`) and other sites in the network on sub-domains like `client.example.com` (not `client.www.example.com`). Is there any way to make it possible!? Important Note: I want to map `example.com` to a different server with different IP than `www.example.com` and the rest of sites. Also, I don't want to map each sub site address by hand. I want it to be automatic. Server specification: I use nginx + php-fpm + fastcgi + centos 5.9.
Yes. Here are the instructions: 1. Install and configure WP for www.example.com 2. Configure multisite - can use either sub-domain or sub-directory 3. Install WP Domain Mapping plugin - < 4. Create new site, e.g. site1 5. Using Domain Mapping plugin, map site (site1.www.example.com or www.example.com/site1) to preferred sitename (site1.example.com) I actually have two separate WP sites setup as above, one is sub-domain and another sub-directory. One of the sites is hosting 200 different hostnames. The other is in development and only setup for two hostnames.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 2, "tags": "multisite" }
Wordpress make Grandparent and great grandparent filterable in custom columns Is there a way to make a Custom Post Type's grandparent and great grandparent filterable in the CPT's columns? For parents I use : esc_url( add_query_arg( 'post_type' => $post->post_type, 'post_parent' => $parentID , 'edit.php' ) )enter code here But this wont work for the Grandparent of the CPT. I tryed several relative solutions (like child_of, post_parent__in) found here but with no luck. Any suggestions on this? Thanks!
So after reading through the codex, I came across the `pre_get_posts` hook, and I decided to try changing the query with it, which worked for me. Not sure if it is the best way though. For anyone that is interested here is what I did: add_action('pre_get_posts', 'get_grandchildren' ); function get_grandchildren() { if ( isset( $_GET['child_of'] ) ) { //Make a custom loop which selects the id of grandchildren of parents and puts them in an array and then set_query_var('post__in', $childrenArray ); } }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "custom post types, columns" }
Change the default number of posts to show on mobile version I want to change the default number of posts shown for my mobile site. Here is my theme's loop <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php get_template_part( 'mobile-content' ); ?> <?php endwhile; ?> I have 25 posts showing on desktop version set in wordpress settings but how can I show 15 posts per page for mobile version?
_Firstly_ , you need to detect mobile devices, probably the easiest and a built in possibility is `wp_is_mobile`. It is simpler then other solutions that are available, but works reasonably well. It can be altered, if necessary, take a look at this question for a first insight into that. _Secondly_ , if that concerns your main query, like your code suggests, you can use `pre_get_posts` to alter it. Below a basic example on how to bring those together: **Code:** add_action('pre_get_posts','wpse124949_alter_main_query_ppp_mobile'); function wpse124949_alter_main_query_ppp_mobile( $query ){ if ( is_admin() || ! $query->is_main_query() ) { return; } if( $query->is_main_query() && wp_is_mobile() ) { $query->set('posts_per_page', '15'); } }
stackexchange-wordpress
{ "answer_score": 5, "question_score": 4, "tags": "posts, mobile" }
DIR vs URI when defining a path to a file When including files in a plugin, I've seen people do `WP_PLUGIN_DIR.'/'.dirname(plugin_basename( **__ _FILE_ __**)).'/somefile.css'` and yet WordPress `wp_enqueue_script/style` uses URI for the file path (such as `plugins_url`). What difference is there? I'm confused...
When you include something, you use the file path because it's a local file and you're reading into the environment right here and now and using that code. When you "enqueue" something, you're not reading the file in, you're sending the URL of the file to a system that puts that URL in the resulting output webpage, for the viewer's browser to then load and read. You use a file path when the PHP code is manipulating the file. You use a URL when the browser needs to see that URL and retrieve the file itself.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugin development" }
How does child theme functions.php work with parent theme functions.php? Is it like CSS? I am looking for help on understanding how child themes and parent themes `functions.php` work. I know with CSS, the cascade overrides CSS declared earlier in the style sheet. It is my understanding that the `functions.php` does not operate the same way. I understand that both `functions.php` are loaded. What happens if you want to have the function in the child theme override a function in the parent theme and the parent theme is not using if statements like the codex recommends?
The comparison of CSS and `functions.php` files is pretty flawed. PHP doesn't "cascade". To answer your question, both files are loaded, child theme `functions.php` first then the parent's. > What happens if you want to have the function in the child theme override a function in the parent theme and the parent theme is not using if statements like the codex recommends? You mean, if the parent function is not wrapped in `function_exists` conditional? Then you can't override the function. That is basic PHP. Try to re-declare a function and you will get an error. You can't get around that. The best you can do is hope for a filter that will let you do what you need, and contact the parent theme developer. This answer might be of interest. Or this one
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "functions, themes" }
How to 'If Author' Comments Check I would like to add extra markup to a comment made by the site admin/post author. Is there a check for this and how would I add it to my code below? Basically, if the comment is from the post author I would like to add HTML next to their name (Author or Admin). Thanks <div class="comment-meta commentmetadata "> <?php printf(__('<cite class="fn">%s</cite> <span class="says">said on</span>'), get_comment_author_link()) ?> <a href="<?php echo htmlspecialchars( get_comment_link( $comment->comment_ID ) ) ?>"> <?php printf( __('%1$s at %2$s'), get_comment_date(), get_comment_time()) ?></a><?php edit_comment_link(__('(Edit)'),' ','' ); ?> </div>
If you use the `comment_class` function to add classes to each comment, comments by the post's author can be styled via the `bypostauthor` class. You can alternately match the comment ID against the post ID: global $post; if( $comment->user_id === $post->post_author ) { // is author comment }
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "comments, admin, author" }
How to echo JS right after enqueued script to put it into noConflict mode? I want to include and use third party JavaScript file (Bootstrap Tooltip) in my plugin. Since Bootstrap is highly popular framework and `tooltip()` is rather generic name I want to make use of included `noConflict()` functionality to isolate tooltip's instance in my own variable. If I understand timing at all right, this needs to be done right after script file loaded - so that nothing else has a chance to mess up instance (it had just set up) or get messed up by it either. However there seems to be no convention in queue functionality to echo JS at such point. `$wp_scripts->print_extra_script()` is called _before_ the script. Is this at all possible to accomplish with current queue implementation?
# WordPress >= 4.1 WordPress 4.1 had added `script_loader_tag` filter for complete HTML of enqueued script. Perfect for the purpose of adding something _right_ after it. * * * ## WordPress < 4.1 I ended up hooking into `wp_print_footer_scripts` at priority `11` (after queue has finished) and calling `wp_print_scripts()` explicitly on script's handle, then echoing what I needed to. I would be hesitant to use this for something major, but for small contained script it seems acceptable.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 4, "tags": "javascript, wp enqueue script" }
Comments Pagination as an unordered list I am currently using `<?php paginate_comments_links(); ?>` to display comments pagination. How can I customise this so that it uses a UL and LI? (Such as is possible with custom post pagination). Thanks
As paginate_comments_links() is pretty much just a already customized version for comments of paginate_links(), see the documentation for a deeper insight, you can use the parameter `type` for this. paginate_comments_links( array( 'type' => 'list' ) );
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "comments, pagination" }
Detect archive and category page I would like to detect following pages: ` \- blog archive ` \- blog category For example, post type I can easly detect with: > $page_id = get_queried_object_id(); > > if (get_post_type( $page_id ) != 'slideshow') How about the above pages ? I mean any category or archive page.
There are Conditional Tags for this: `is_archive()` and `is_category()` respectively. For a custom post type archives you could use `is_post_type_archive()`. There are many conditional tags available, see above linked codex page. To determine the blog archive you have to additionally check for the post type `post`, take a look at this question and the answers for more useful information.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "blog" }
How can I get the blog page ID? As above, for example this is the blog page url: ` Let assume that I don't know the exact ID of blog page and I want to write `if` condition for this page.
You can get the blog page id using this: get_option('page_for_posts');
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "pages, blog" }
Why can't I add a custom image in my navigation? Trying to add a navigation Home icon Failing to work. **Here's my nav:** <nav id="site-navigation" class="main-navigation" role="navigation"> <h3 class="menu-toggle"><?php _e( 'Menu', 'twentytwelve' ); ?></h3> <a class="assistive-text" href="#content" title="<?php esc_attr_e( 'Skip to content', 'twentytwelve' ); ?>"><?php _e( 'Skip to content', 'twentytwelve' ); ?></a> <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?> </nav><!-- #site-navigation --> I've tried adding: `<img src="/home.png"/>` to the second line, still no success. **I have tried:** `<img src=" /><h3 class="menu-toggle"><?php _e( 'Menu', 'twentytwelve' ); ?></h3>` Thanks
I figured it out. You have to search your style.css file and find `/* Buttons */` Under that you will find the following classes .menu-toggle, article.post-password-required input[type=submit], .bypostauthor cite span {} .menu-toggle, button, {} button[disabled], input[disabled] {} .menu-toggle:active, .menu-toggle.toggled-on, button:active, {} There are 2 states of the button that you need to configure. Hover and active. Just change the `background-image:url('');` for each state to what image you want in the background. Then just either negative indent the text by -9999 or delete the text from the `header.php` file as you previously stated.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, navigation, menus" }
Execution of JavaScript on save post I got stuck with one problem, can somebody please help.. :) I would like to execute custom JavaScript function before post is saved, and i can't find how to do that. Something like JavaScript version of save_post action hook :) Thank you!
Do it like shown below, as suggested by @gyo and done by @Howdy_McGee in his answer. function admin_queue( $hook ) { global $post; if ( $hook == 'post-new.php' || $hook == 'post.php' ) { if ( 'targeted-posttype' === $post->post_type ) { wp_enqueue_script( 'custom-title-here', bloginfo( 'template_directory' ) . '/scripts/custom-script.js', 'jquery', '', true ); } } } add_action( 'admin_enqueue_scripts', 'admin_queue' );
stackexchange-wordpress
{ "answer_score": 0, "question_score": 3, "tags": "jquery, javascript, save post, autosave" }
using comments_template() in custom single-portfolio.php I am wanting my users to be able to post comments on my portfolio page. Ive created a portfolio page using custom posts. On my blog i am using the comments_template(); and then on the comments.php i have the code. On the blog side it works 100% But when I add the comments_template(); on the portfolio single page it does nothing. I get no errors or anything. How do people implement comments within the portfolio pages? Can you not use the same comment.php file for all comments, b Thanks
When registering a custom post type you need to enable comments. In the arguments defining the CPT, you need to include something like this: `'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'comments' )` The example on the Codex is shows where this option needs to go, this page also shows a list of other options you may or may not want to include: <
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "comments, comments template" }
How to write this conditional statement? What is the correct way to write a conditional statement? <?php if is_tag( 'Premium' ){ <a href="<?php the_permalink(); ?>" class="info"> Subscribe</a> }else { <a href="<?php the_permalink(); ?>" class="info">Read More</a> } ?> Help Needed.
`is_tag` checks whether the page being displayed is the tag archive page for the named tag. It does not check whether the **_post_** in a Loop has that tag, which is what you ask: "...to show if the post has tag premium...". For that you need `has_tag` if has_tag( 'premium' ){ ?> <a href="<?php the_permalink(); ?>" class="info"> Subscribe</a><?php } else { ?> <a href="<?php the_permalink(); ?>" class="info">Read More</a><?php } Note that `has_tag` requires the tag _slug_ and not the tag _name_ , hence the lowercase.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "conditional content" }
Change wording of default thumbnail metabox I want to change the wording in the Default thumbnail metabox to 'Set default thumbnail' instead of 'Set featured image'. How can I do this?
This is usually what I go with: /** Use "Featured Image" Box As A Custom Box **/ function customposttype_image_box() { remove_meta_box('postimagediv', 'page', 'side'); add_meta_box('postimagediv', __('Set Dat Image'), 'post_thumbnail_meta_box', 'page', 'side'); } add_action('do_meta_boxes', 'customposttype_image_box'); /** Change "Featured Image" box Link Text **/ function custom_admin_post_thumbnail_html( $content ) { global $post; if($post->post_type == 'page') { $content = str_replace( __( 'Set featured image' ), __( 'Upload dat Image' ), $content); $content = str_replace( __( 'Remove featured image' ), __( 'Remove dat image' ), $content); } return $content; } add_filter( 'admin_post_thumbnail_html', 'custom_admin_post_thumbnail_html' );
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "post thumbnails" }
Meta box values are displayed on Custom Fields list. Is it possible to hide them? I have multiple meta boxes for my Custom Post Type posts. I want my users to add new fields using Custom Fields. The problem is - Custom Fields display all the garbage from my metaboxes and it might be very confusing for users. Here's a screenshot, the two first fields were added by an user and the rest comes from the theme itself (there are metaboxes above this "Custom Fields" box which use / reset these fields on post save). How do I hide them? ![](
Prefix all meta data keys used in meta boxes with an underscore, this will hide them automatically from the built in Custom Fields interface. So instead of: themeprefix_source Use: _themeprefix_source
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "custom field, metabox, post meta" }
Add post tags to previously created custom post type I am trying to add post tags to the custom post types bbpress creates, so that I can do some "related topics" kind of stuff. Is there a function that adds a post support like `'taxonomies' => array('post_tag')`, but to a post type that was previously created? My thought was I could just re create the custom post type on theme install or soemthing and hope it didnt mess anything up, but I really wanted to avoid doing that.
Use the function `register_taxonomy_for_object_type` to add existing taxonomies to existing post types: function wpa_tags_for_cpt(){ register_taxonomy_for_object_type( 'post_tag', 'post_type_name' ); } add_action( 'init', 'wpa_tags_for_cpt', 999 );
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "posts, tags, customization" }
Restore Cforms II Form Presets I have a client who had to reactivate the cforms II contact forms plugin. It refused and gave the following error: *Fatal error*: Cannot use string offset as an array in */var/www/vhosts/site.com/httpdocs/wp-content/plugins/cforms/lib_activate.php* < on line *7* After I removed the values for cforms_settings - see < \- in wp_options I was able to reactivate, but I had of course lost all form presets and automatic answers. Now I have this as value in the row cforms_settings: < .When I tried to re-add some of the serialised data I got an error from the plugin saying the settings were corrupted and that I could try to fix it or reset all. How can I restore my form presets in the database using this serialised data as there were no recent form exports done from plugin before the plugin was deactivated?
By replacing of all the serialised data I had backed up in the row with key `cforms_settings` I managed to get the form presets back. The plugin accepted this and worked as before. Life is beautiful.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "forms, mysql, plugin cforms" }
Load Pages Menu in single.php I've searched a lot but didn't find an answer ... My Wordpress has got 4 main areas, each one also has a news (posts) section and an own submenu. If I load a post (with single.php) is it possible to get the corresponding submenu to that area? I'm thinking about sub stringing the slug to get the right area. Help is really appreciated. Thx, Oliver Additional Info: * There is a sidebar which I also show in single.php * The sidebar should contain the menu tree of one area * A post is not connected to the menu
Yes you can. <?php $args = array( 'theme_location' => 'primary', //change this value with coresponding menu area 'menu_id' => 'main-menu', //change this value with wanted menu ); wp_nav_menu($args); ?> menu_id is the name of menu created in WP admin>Menus. I create menu with name "Main menu" so I put main-menu there. That menu is connected with my primary menu area in WP admin>Menus. Change those values with your values and place that code into single.php in wanted area... or any other template.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, menus" }
$wpdb->get_results not returning an array I haven't really messed with $wpdb before, but I'm stuck hard on one part. I'm trying to get the values returned in an associative array. I've tried both of these $datarow = $wpdb->get_results("SELECT class_name FROM wp_wcs2_class WHERE id=$classnumber"); $datarow = $wpdb->get_results("SELECT class_name FROM wp_wcs2_class WHERE id=$classnumber",ARRAY_A); but `print_r $datarow;` just errors out with `Parse error: syntax error, unexpected T_VARIABLE` Any idea what's going wrong? I know the data is there because this returns the correct value: $nameresult = $wpdb->get_var($wpdb->prepare("SELECT class_name FROM wp_wcs2_class WHERE id=$classnumber",ARRAY_A));
It has nothing to do with `$wpdb`. It's PHP parse error. `print_r` is a function, so you can't do `print_r $datarow;` You should use `print_r( $datarow );` instead.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "wpdb" }
Google indexed pages for one page site I have created a one page site with wordpress. The basic idea used was to combine pages and their templates into index.php. The problem is that when crawlers work on the site, they get the links for the pages which is good, but they display the page as single item and not part of the one page site. How can I redirect these pages into the main site? Is there a plugin or a way to achieve it?
This is not wordpress related question but I will answer it without any special reason. First of all... all pages from old website are indexed on google and those indexed pages can not be deindexed at the same moment when you change the website. That is the reason why all pages show on google... so you have to wait or you have to play around in Google webmaster tools in order to speed up that process. You can create redirections simply with this plugin: < I hope that this will help you to understand what is going on. But... as experienced SEM guru I would never combine all those pages into one page because of many reasons.... but that is not important now.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "pages, template redirect, google search" }
How to delete all records from or empty a custom database table? I can't seem to find a simple reliable way to do this - perhaps?: // delete row ## global $wpdb; $delete = $wpdb->query( $wpdb->prepare( "DELETE * FROM `wp_table_name`" ) ); // return ## $return = __('Table Emptied.'); if ( $wpdb->last_error ) { $return = $wpdb->last_error; } But this gives me the classic: > You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* FROM wp_table_name' at line 1
Thanks @s_ha_dum - Truncate does the job nicely: // delete row ## global $wpdb; $delete = $wpdb->query("TRUNCATE TABLE `wp_table_name`");
stackexchange-wordpress
{ "answer_score": 10, "question_score": 9, "tags": "plugins, customization, database, wpdb" }
Remove date from Google Search Results Description How do I remove the date from the google search results of my posts? Is this related to WordPress or is it theme-specific?
Paste this code in `functions.php` add_filter( 'wpseo_show_date_in_snippet_preview', false); //Returning false on this will prevent the date from showing up in the snippet preview. Note: WordPress SEO api
stackexchange-wordpress
{ "answer_score": 2, "question_score": 2, "tags": "seo" }
How to only allow post to be deleted if custom field doesn't exist I have looked at both the delete_post and before_delete_posts. Neither of these hooks actually allow me to perform a check and then tell wordpress not to delete the post. Anyone got any ideas?
You can hook into `before_delete_post` and redirect before completing the deletion. add_action('before_delete_post', function($post_id) { // Get custom field $field = get_post_meta( $post_id, 'key', 'true'); // Redirect if field is empty if (!$field) { wp_redirect(admin_url('edit.php')); exit(); } }, 1);
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "posts, custom field, customization" }
Verify Nonce returns false - Request Nonce returns correct value I'm trying to verify that the nonce I created exists but for some reason it keeps returning false, why is this happening? Creating my nonce: <?php wp_nonce_field('test_slider_action','test_slider_options_nonce'); ?> Verifying my nonce exists: if($_POST && wp_verify_nonce($_REQUEST['test_slider_options_nonce'])) echo "TEST"; if I dump my `$_REQUEST` I get the correct value, but if I dump my wp_verify_nonce it returns false. If it matters, both my `$_POST` check and form / nonce creation is on the same page. What else do I need to get it to verify?
You need to pass the action to check your nonce against, wp_verify_nonce has two parameters. if($_POST && wp_verify_nonce($_REQUEST['test_slider_options_nonce'],'test_slider_action')) echo "TEST";
stackexchange-wordpress
{ "answer_score": 7, "question_score": 1, "tags": "plugin development, validation, nonce" }
Need help with else if statement I am trying to set up my blog so that there are different colors for 2 different categories, however, if there is a post that is tagged with neither of these 2 categories I want it to default to green. Here is my code: <?php if ( in_category( 'News' )) : ?> <div class="green"> <?php elseif ( in_category('Blog')) : ?> <div class="orange"> <?php endif; ?> So basically I want to change it so that if the post isn't in the "News" or the "Blog" category, it will just default to the "green" class. Thanks in advance!
You should familiarize yourself with PHP, but if you want a default color ( assuming the code below already works ) you could do: <?php if ( in_category( 'News' )) : ?> <div class="green"> <?php elseif ( in_category('Blog')) : ?> <div class="orange"> <?php else : ?> <div class="pink"> <?php endif; ?>
stackexchange-wordpress
{ "answer_score": 1, "question_score": 1, "tags": "conditional tags" }
Drop-Down Menu of Current Child Pages I would like to display the child pages of the current page in a select menu, I.E. => <select><option>This is a child page</option><option>This is another child page</option></select> Of course, the option markup would be the dynamic function; markup that says basically that we want to display the child pages of the current page wrapped in an option field for each one. The result should be a drop-down menu that someone could select the child pages title and submit it with the form. The reason being, the child pages are tours and all I need is the title to be passed to a select field so we know that' the tour they're interested in.
This can be approached by using `wp_dropdown_pages()` with the `child_of` parameter. global $post; $args = array( 'child_of' => $post->ID ); wp_dropdown_pages( $args ); The variable name will be `$_GET['post_id']` or `$_POST['post_id']`, depending on your form settings, you can change the name by altering the `name` parameter. The value of the variable is the `ID` of the chosen page. Use `get_the_title()` to get it from the id in your $_GET/$_POST variable.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "child pages, get children" }
Load custom css after bootstrap I have this in functions.php. How can I modify it so that my custom css is loaded after bootsrap.min.css? function register_css() { wp_register_style( 'bootstrap.min', get_template_directory_uri() . '/css/bootstrap.min.css' ); wp_enqueue_style( 'bootstrap.min' ); } add_action( 'wp_enqueue_scripts', 'register_css' ); I found this but it doesn't work and I don't know much about php but I think it's missing the wp_register_style part.
The above looks correct, however, you need to specify your script to enqueue after bootstrap by adding the `bootstrap-min` handle to the third, dependencies parameter. function register_css() { wp_register_style( 'bootstrap-min', get_template_directory_uri() . '/css/bootstrap.min.css' ); wp_register_style( 'custom-css', get_template_directory_uri() . '/css/custom.min.css', 'bootstrap-min' ); wp_enqueue_style( 'bootstrap-min' ); wp_enqueue_style( 'custom-css' ); } add_action( 'wp_enqueue_scripts', 'register_css' ); See wp_register_style for more. Alternatively you can, if you know you need to enqueue the files immediately from within your callback function, use `wp_enqueue_style` just like `wp_register_style`, see: wp_enqueue_style
stackexchange-wordpress
{ "answer_score": 3, "question_score": 2, "tags": "css, wp enqueue style, twitter bootstrap, wp register style" }
Order by meta value I've a custom post type that has a custom filed called **deck-number** and client wants to sort the result by deck number. FYI, deck numbers are numeric values. So I used query like bellow. get_posts('post_type=decks&nopaging=true&meta_key=deck-number&orderby=meta_value&order=ASC'); The issue I'm facing is I'm getting result sorting like 1, 10, 11, 12, 2, 3, 4, 5, 6, 7, 8, 9. I need your advice to solve. Thanks.
Use `meta_value_num` with `orderby` instead of `meta_value`. `meta_value` is used to order alphabetically. `meta_value_num` used to order numerically. For more information, check this: Codex get_posts And this for detailed information: Codex WP_Query
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "meta query" }
HTML head-tag get broken in my child theme I created a child theme from **twentythirteen** and it worked like it should. Then I made a copy of the parent theme's header.php. As soon as I created it, the outputted HTML got broken. All tags that are supposed to go in the `<head>`-tag instead shows up in the `<body>`-tag, and the `<head>` is empty. This happens even if the content of header.php in my child theme is exactly the same as the original. The same happens if I create a new functions.php in my child theme. Even though it only contains this: <?php ?> or is totally empty. If I remove the file, the head content get put in the correct place again. EDIT: The actual source code is actually correct (if I choose "view source"), the error only shows up in inspector mode in Chrome and IE, but not in Firefox's inspector.
I used to have this problem once, for me it happened because I used the wrong encoding. I also had the right sourcecode but it came out all wrong on the actual page. Try setting your editors settings to "UTF-8 without BOM" because the BOM is what seems to be causing that error. Sometimes it also happens if you copy and paste text from somewhere and it copies some invisible characters. Try typing the stuff yourself, and it might just work. (there's more people with the same problem, e.g. < < and what I said above usually worked for them to fix it)
stackexchange-wordpress
{ "answer_score": 0, "question_score": 2, "tags": "child theme" }
Register an additional image size for only some images in my media library There is a type of post on my blog which requires one extremely large image (such that it can be zoomed). I don't want to register a new image size, because I only need a certain small subset of images to have this large image size. I have managed to generate this additional large image and it sits alongside the other three "generated" images in the uploads directory, however since it is not registered with the Media Library, it does not get uploaded to the image CDN with W3 Total Cache. Can anyone suggest a better approach to my problem? Or suggest how I might register that large image with the media library (without it automatically creating the other image sizes which would not be needed). Or is there perhaps a way to register an additional image size for only some images in my media library?
Since you know the location of the image on the disk you can use wp_insert_attachment to insert your big image to the media library. By default this will generate also several smaller versions of the big image that you might not need but this is the easiest way to make all the media related plugins to be aware to your image.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 3, "tags": "media library, images" }
Different posttypes for different authors Now what I need to find a solution of is this issue: I have 8 authors, and a bunch of posts. All authors have there own adsense (or other affiliate), we wish to show the adds belongings to the authors on there OWN posts. So the author collects payment (if any) from there own posts, and only from there own posts. Is there any way to make wordpress/theme do something like that? Thanks Marius
You don't say how you have set up the different adsense. I will assume that in your template there is a folder, called `'authors-ads'`, in it you have some php files, named after your **authors ids** , e.g.: * `/authors-ads/author-1.php` * `/authors-ads/author-12.php` and so on. after that in your `single.php` or whatever template you use to display posts use global $post; get_template_part('authors-ads/author', $post->post_author ); in this way the file related to the post author is included in the page. In that file put the ads related to the author, of course.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "author, adsense" }
Checking if a woocommerce attribute is set I'm trying to figure out how I can check if a custom attribute is set in woocommerce on a product. As It generates an error if that particular attribute isn't set. Here is my code that pulls in the attribute. <?php $terms = get_the_terms( $post->ID, 'pa_size'); if ( isset ($terms)) // checking if the att is set foreach ( $terms as $term ) { echo "<li>" .$term->name. "</li>"; } ?>
Simply check this by using: if ( $terms && ! is_wp_error( $terms ) ) { //your code } Take a look at the codex page for `get_the_terms()` for a deeper insight, especially the »Returns« and »Examples« section.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, terms, conditional tags" }
Force WP to use a certain search template Any way to do this? I'd like for all the search results to be run through wp advanced search ( < ) so they appear on the wp advanced search page template instead of the default way provided by my theme.
You can use template include filter to use it on every search request. Let's assume the advanced search page template you are using is `'wp-advanced-search.php'` you can use `locate_template` to get its path: add_action('template_include', 'advanced_search_tmpl'); function advanced_search_tmpl( $template ) { if ( is_search() ) { $t = locate_template('wp-advanced-search.php', false); if ( ! empty($t) ) $template = $t; } return $template; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "search" }
How to get url of a post from admin panel I want to get post url from the back end edit post page, the edit post url is : www.ddd.com/wp-admin/post.php?post=1&action=edit the real post is: www.ddd.com/wp/?p=1 since the user can edit permalink, i need some wordpress parametrs so it will be constant. Looking for this answer: global $post; get_permalink($post->ID); thx all
You can get the `ID` of the post you're editing like this: //currently edited post id $cep_id = $_GET['post']; //permalink get_permalink( $cep_id ); This is and can only work if your editing an existing/saved post. It won't and can't work on »Add New«-Pages, because the post you're going to add isn't saved to the database yet, after »Publish« has been pressed one gets redirected to the actual »Edit«-Page and the above is possible.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 4, "tags": "permalinks, hooks, urls" }
Grab Wordpress Salt Data From URL I'm looking to grab only the values of the Wordpress salt information from this URL with PHP: < I want to target the second set of values within single quotation marks. Is this do-able with regex? I'm having issues $url = ' $ch = curl_init(); curl_setopt($ch, CURLOPT_POST,1); curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post_data)); curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_RETURNTRANSFER,1); $output= curl_exec($ch); preg_match_all("/'(.*?)'/", $output, $matches, PREG_PATTERN_ORDER); var_export($matches); I'm working on a tool that will automatically grab the content from the url, strip out everything except for the values of the defined keys and return it in an array. It seems to mess up alot and doesn't bring back the proper values, is there any other way to target the defined values only from the second set of quotation marks? Thanks
That returns PHP code. You can just eval it and then reference the various defines directly. However, that is just a random number generator on the back end. There is no pattern to it. You can just generate your own random values instead of pulling them from WordPress.org and it will work just as well for whatever your purpose is.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 1, "tags": "plugins, functions, regex" }
Setting Up "Split Site" Navigation in Wordpress I'm currently attempting to set up a WordPress install for an organization which has two separate devisions. I'm having a very hard time wrapping my mind around how to create two navigation menus and reliably switch between them based on the currently viewed content. I can't use multiple WordPress installs, as content will be shared in some cases and a single dashboard is preferred. I tried using categories, but pages can't be assigned to a category. I tried using page parents, but posts can't be assigned a parent. I'd like the solution to allow non-technical people to maintain both navigations easily. How can I achieve this? Related questions: * Different menu navigation per category * Get top level page parent title
You can use categories with pages, via `register_taxonomy_for_object_type`, but if you were to use a taxonomy for this, it may be better to register a custom taxonomy specifically for that purpose. Another option is to add a meta box and provide simple means of selecting a menu, which would be saved and accessed via post meta data, otherwise known as Custom Fields.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "navigation" }
Update the value of a constant I have a file containing all the constants used in the plugin. For example, I have a variable in one of my file `define('APPOINTMENTS_DEFAULT_ENABLE_PAYPAL', 1);` I have a checkbox in admin area where user can enable or disable the paypal feature. This is the checkbox code: `<input type="checkbox" name="enable_paypal" size="40" value=""/>` **Issue:** Can anybody please tell me how can I write code to modify the `define()` so that when checkbox is clicked then make the value to 1 and otherwise value should be 0?
You can't alter a constant once it is defined. That is how PHP works. Don't fight it. The good news is that you should not be using a constant at all. Use options. // get your value // the second parameter is the default $enable_paypal = get_option('enable_paypal',true); // set your value based on, I assume, a form of some kind update_option('enable_paypal',false); # Reference < <
stackexchange-wordpress
{ "answer_score": 3, "question_score": 0, "tags": "paypal, input, constants" }
Conditional On custom field plugin metabox I've trying to run a conditional on the custom field I made with the Custom Fields plugin, I made a true and false check box. I just need to check if the box is true or false really. I've tried something like this but the word hello appears even when the <?php $premium = get_field('premium'); if ( !isset($premium)) { echo 'hello'; } ?> Basically I've trying to change the page layout if this is ticked. I'm sure this is quite easy. Thanks for any input
This can't work because `isset()` returns true if there is a value, `true`and `false` are values, ergo it won't work. Do it like this instead: $premium = get_field('premium'); if ( ! $premium ) { // this is basically short for $premium == false echo 'not premium'; }
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "php, custom field, functions" }
How should I setup the "Users" area to hand over to a client? We're about to hand over a Wordpress site to a client; this is the first one we've built from scratch. Our "Users" area just consists boringly of the **admin** login with my work email like so: !enter image description here. What's the best way to set this up to hand over to the client? We want to retain the ability for us to login and support them and have full powers but not look like we still own it. As things stand, if we just add a couple of their members of staff to it now it'll still look like we're still the supreme user. What do agencies normally do? This isn't a big project or client. They have a main person their end and a couple of junior users to help them.
1. Create an admin level user for your client, preferably not one named "admin". If you track the number of attempted hacks on your site you will notice that most try to use the "admin" username. 2. Change the email for the admin use to reflect your client's email address 3. Or, preferably, delete the "admin" user and create another one with a less guessable name.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "admin, users, user roles" }
How to use RSS reader plugin for displaying as posts? I am running WP 3.7.1-powered website. I would like to read news from several RSS sources and display them on one page in very similar manner as if they were posts from users of my site. Particularly, I need them to be displayed in the main area of a page (not in a widget) and I need them to be commented as regular posts. I tried "WP Simple Rss Feed Reader" and "RSS Importer", but I did not manage to configure or use them in such a way which would solve my problem. Is there any solution? Thanks.
1-FeedWordPress 2- WP RSS Multi Importer use one of these, which suits you.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "rss" }
Find and replace weird characters in the_content So, I am using the following code to filter out certain letters. $phrase = get_the_content(); $phrase = apply_filters('the_content', $phrase); $replace = 'ï'; echo str_replace('ï', $replace, $phrase); Unfortunately, it doesn't seem to handle special characters that well. Any ideas?
You could try this: <?php function replace_content($content) { $search = array('&', 'é', '—', '‘', '’', '“', '”'); $replace = array('&', 'é', '—', '‘', '’', '“', '”'); $content = str_replace($search, $replace, $content); return $content; } ?> Credit to Harry on WordPress forums
stackexchange-wordpress
{ "answer_score": 0, "question_score": -1, "tags": "the content" }
Conditionally bypass plugin I would like to defer the loading of an othervise active plugin for certain pages. Since all plugins reside in the same folder, and WordPress only loads the activated ones, it must have an array of active plugin-handles at some point that it goes through. There's probably even a filter available to modify this array just before its being read (I'm hoping..). So is it possible to conditionally bypass the loading of an otherwise active plugin, by removing it's handle from the list of active plugins, dynamically, without deactivating the plugin using deactivate_plugins()?
The list of active plugins is provided by `wp_get_active_and_valid_plugins()` during core load and comes from `active_plugins` option (multisite details aside). While there is no explicit filter for it as any option it can be filtered via `'option_' . $option` hook (so `option_active_plugins`) and mu-plugin (which are being loaded earlier) should be able to do it. Note that it is more common and better practice to control what plugin _does_ (such as thing it hooks) rather than if it loads completely.
stackexchange-wordpress
{ "answer_score": 3, "question_score": 1, "tags": "plugins" }
Why isn't my rewrite rule working when there is no second parameter? Here is my rewrite rule code: add_rewrite_rule('tides/([^/]+)/([^/]*)', 'index.php?page_id=4348&location=$matches[1]&month=$matches[2]', 'top'); add_rewrite_tag('%location%', '([^&]+)'); add_rewrite_tag('%month%', '([^&]*)'); This works great for the following URL: /tides/mylocation/mymonth/ but 404's on the following: /tides/mylocation/ I'm flushing the rewrite rules every time I change the code. I tried changing `*` to `+` but no help there. Any ideas? **Edit:** Some answers were suggesting adding another rewrite rule so I added: add_rewrite_rule('tides/([^/]+)/$', 'index.php?page_id=4348&location=$matches[1]', 'top'); before my other rule, but still no luck.
Your regular expression is requiring the last slash be present which it will not be by default. So the path `tides/mylocation/` is shortened to `tides/mylocation` and then tested. Instead, wrap the last part in an optional group using the `?` and update the match number. add_rewrite_rule('tides/([^/]+)(/([^/]+))?', 'index.php?page_id=4348&location=$matches[1]&month=$matches[3]', 'top');
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "rewrite rules, regex, rewrite tag" }
User registration is currently not allowed I'm running into issues on my localhost where when I navigate to my registration page I get the following error message _User registration is currently not allowed._ What I've tried so far: 1. I've checked my settings menu under `wp-admin/network/site-settings.php?id=1` and under _Users can register_ I have a `1` entered. 2. I've tried turning my plugins on and off. 3. I've checked `wp-admin/admin.php?page=bp-page-settings` and all necessary pages exist and are listed. 4. I've tried echoing `wp_register('','',false);` to see if that lends any clues and it just turns up blank. This isn't the case on my other server (which I had thought was configured identically to my localhost). Registration is allowed and the echo above provides the link. No idea what's going on here and am working against a deadline (aren't we all, right?) so any ideas would be greatly appreciated.
No sooner did I post than I ran across this forum thread. I had to go into `Network Admin > Settings > Network Settings` There, I had to select "User Accounts may be registered" in addition to entering a 1 in the site settings area. Problem solved. Maybe this helps someone else.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "multisite, buddypress, user registration, multisite user management" }
Orion theme (from theme forest) I was given a theme called Orion available from themeforest. I had experienced troubles installing it via GUI (style.css was missing), therefore I did that operation manually by copying Update directory up the directory tree. Now the theme appears somehow empty/broken. I was wondering whether this specific theme is meant to be standalone or just as an update to a prerequired theme (and which one, if this is the case). Thank you! Edit: I apologize as I wasn't clear enough. Is it normal that the theme .zip file which should be used to install the theme does not contain style.css? Why is the stylesheet only included in Update folder and what is (usually) the purpose of that subfolder?
Every WordPress theme, including child themes, is required to have a `style.css` file. The first few lines in `style.css` tell WordPress the name of the theme, the description, and some other meta information about the theme. You'll have to ask the theme developer why there are files missing in your theme.
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "themes, installation, css" }
str_replace not responding in functions.php I'm tring to use `str_replace` within a wordpress function but its not working. My code: function fields($content) { if(is_feed()) { $post_id = get_the_ID(); $url = str_replace(' '', '' . get_post_meta($post_id, 'book-author', true) . ''); $output = '<div>'; $output .= '' .url. ''; $output .= '</div>'; $content = $content.$output; } return $content; } add_filter('the_content','fields'); What I'm getting in result of `' .url. '` is just "url" printed in my feed. Please help. Thank you.
That could not work, you simply miss the $ before $url. $output .= '' .$url. '';
stackexchange-wordpress
{ "answer_score": 0, "question_score": 0, "tags": "php, functions" }
preg_replace not removed "class" Use this code to remove the label "class" of the images, but does not work. The label does not disappear in the new post. function the_post_thumbnail_remove_class($output) { $output = preg_replace('/class=".*?"/', '', $output); return $output; } add_filter('post_thumbnail_html', 'the_post_thumbnail_remove_class'); It only works on the main page with highlighted images(thumbnail).
The hook `post_thumbnail_html` is just working for featured images aka post thumbnails, hence the name. I'm guessing that's what you're missing and where the "problem" originates. But luckily there is another hook for manipulating image tags `get_image_tag`, there is actually one for just altering the class `get_image_tag_class` too. Take a look into those. Another hook used in these scenarios is `wp_get_attachment_image_attributes`, but I only mention this one for completeness reasons.
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "posts, images, post thumbnails, hooks" }
how to know if admin is in edit page or post I use this after I checked if the user is admin if ( isset($_GET['action']) && $_GET['action'] === 'edit' ) is there better way?
You can use `get_current_screen` to determine this. $screen = get_current_screen(); if ( $screen->parent_base == 'edit' ) { echo 'edit screen'; } I don't know if I exactly would say this is always better, it depends on what's needed, but it's probably the way I'd do it. The big benefit with this method is that you get access to more information and ergo can do more and different distinctions. Just take a look at the documentation to understand what I mean. It should be used in later hooks, Codex says: > The function returns `null` if called from the `admin_init` hook. It should be OK to use in a later hook such as `current_screen`.
stackexchange-wordpress
{ "answer_score": 26, "question_score": 25, "tags": "admin, editor" }
How to get page title with the page ID? My page ID is: `30601`. I want to get the page's title with ID.
Try with this: <?php echo get_the_title( $ID ); ?>
stackexchange-wordpress
{ "answer_score": 42, "question_score": 19, "tags": "pages, title, id" }
http_response_timeout filter not working I am writing a Wordpress plugin that makes calls to external sites. I want to raise the timeout for all `wp_remote_*` calls, so I added the following to the `__construct` function of my plugin: add_filter("http_response_timeout", function($timeout) { return 30; }); But the calls still time out after 5 seconds. I also tried using a separate function as the second argument, same result. When I pass `array("timeout" => 30)` to the `wp_remote_*` functions directly, it works... Any idea why the filter is not respected?
There is no filter named "http_response_timeout" in the WordPress core. Where are you finding this filter name from? The timeout parameter as passed to a wp_remote call has a default of five seconds, and that default can be changed using the "http_request_timeout" filter, which is a different name than you used. Maybe you're just using the wrong word?
stackexchange-wordpress
{ "answer_score": 2, "question_score": 0, "tags": "plugins, http api, wp remote get, wp remote request, wp remote post" }
how to make wordpress not to look for themes For a particular project, I'm currently using only wp's admin and core functions/sugars, so no themes. Still, I'm forced to choose a theme. I would like a couple of things: 1. move theme's functions.php (that currently contains only custom code by me) in /wp-contents, outside the themes and make WP still load it 2. force WP not to look for themes, so I can succefully delete the themes folder without getting an error in wp-admin Is this possible? What's the best way (without hacking the core)? Point 2 is less crucial, since I can always hide the admin's themes button. Point 1 is important. For point 1, maybe I could load functions at the end of wp-config.php, or maybe (still in wp-config) I could hook at 'init' or 'setup_theme'. Or maybe something else.. I'd like to know the best practice here. thank you
I can't see a reasons why you not just put your code from the `functions.php` into Plugins or Must Use Plugins, it isn't that hard to do and is, in my mind preferable, to connecting this task somehow to the `wp-config.php`. Besides that, if you don't absolutely have to remove the backend/admin themes functionality itself, just remove, unset and/or make it inaccessible from the backend/admin area. Seems more practical to me, probably not knowing all the determining factors of course. Edit: this is complementary to what @ravs suggested
stackexchange-wordpress
{ "answer_score": 1, "question_score": 3, "tags": "functions" }
Any kind of custom post type in the front page and in the archive listing I have a custom post type:products to have my post from my custom post type i have changeed these codes <?php $post_count = 1; ?> <?php if (have_posts()) : while ( have_posts() ) : the_post() ?> to ?php $post_count = 1; $args = array( 'post_type' => 'products' ); $products = new WP_Query( $args ); ?> <?php if ($products->have_posts()) : while ( $products->have_posts() ) : $products->the_post() ?> I have done same things for the archive.php also. But Now what i want to do i wont to get posts from different post types on my front page. Not any. And when i chose a category to get posts i want to get from different post types. Not any thispart inside of archive.php How we can do that.
function namespace_add_custom_types( $query ) { if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) { $query->set( 'post_type', array( 'post', 'post_type1', 'post_type2' )); return $query; } } add_filter( 'pre_get_posts', 'namespace_add_custom_types' ); it worked realy good.
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "archives, categories" }
How to add a link to our wp.org profile from wordpress.org plugin page? We have written a few plugin which are available on the wordpress.org public repository for example \- and I see that other authors have a link to their profile and a count of the plugins they're added, which would be a nice way to show other plugins we're produced - but how to do it? !other plugins The sidebar on plugins we released looks like this: !our plugins Do we need to add something extra to the readme.txt - or what is the trick - anyone know?
The link was created automatticly, if you have a profile on wordpress.org. As example: see my profile: < and see also a plugin of my, same user-slug: < But it is important, that you write case sensitive. The user must include in the readme of the plugin, on the string `Contributors:`. See also a example from the plugin above: < === Adminimize === Contributors: Bueltge, inpsyde ....
stackexchange-wordpress
{ "answer_score": 1, "question_score": 0, "tags": "plugins, repository" }